Welcome To PHP
Welcome To PHP
Welcome To PHP
PHP: Hypertext Preprocessor (PHP) is a free, highly popular, open source scripting
language. PHP scripts are executed on the server.
Before starting this tutorial, you should have a basic understanding of HTML.
Why PHP
PHP runs on numerous, varying platforms, including Windows, Linux, Unix, Mac OS X,
and so on.
PHP is compatible with almost any modern server, such as Apache, IIS, and more.
PHP supports a wide range of databases.
PHP is free!
PHP Syntax
A PHP script starts with <?php and ends with ?>:
Here is an example of a simple PHP file. The PHP script uses a built in function called "echo" to
output the text "Hello World!" to a web page.
<html>
<head>
</head>
<body>
<?php
?>
</body>
</html>
Result:
PHP Syntax
Alternatively, we can include PHP in the HTML <script> tag.
PHP Syntax
You can also use the shorthand PHP tags, <? ?>, as long as they're supported by the
server.
<?
?>
Result:
Echo
PHP has a built-in "echo" function, which is used to output text.
In actuality, it's not a function; it's a language construct. As such, it does not require
parentheses.
?>
Result:
PHP Statements
Each PHP statement must end with a semicolon.
<?php
echo "A";
echo "B";
echo "C";
?>
Result:
Echo
HTML markup can be added to the text in the echo statement.
<?php
?>
Result:
Comments
In PHP code, a comment is a line that is not executed as part of the program. You can
use comments to communicate to others so they understand what you're doing, or as a
reminder to yourself of what you did.
?>
Result:
Multi-Line Comments
Multi-line comments are used for composing comments that take more than a single
line.
A multi-line comment begins with /* and ends with */.
<?php
/*
multiple lines
*/
?>
Result:
Variables
Variables are used as "containers" in which we store information.
A PHP variable starts with a dollar sign ($), which is followed by the name of the
variable.
For example:
<?php
$name = 'John';
$age = 25;
echo $name;
?>
Result:
In the example above, notice that we did not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its value.
Constants
Constants are similar to variables except that they cannot be changed or undefined after
they've been defined.
Begin the name of your constant with a letter or an underscore.
To create a constant, use the define() function:
Parameters:
name: Specifies the name of the constant;
value: Specifies the value of the constant;
case-insensitive: Specifies whether the constant name should be case-insensitive. Default
is false;
echo MSG;
?>
Result:
echo msg;
?>
Result:
Data Types
Variables can store a variety of data types.
Data types supported by PHP: String, Integer, Float, Boolean, Array, Object, NULL,
Resource.
PHP String
A string is a sequence of characters, like "Hello world!"
A string can be any text within a set of single or double quotes.
PHP Integer
An integer is a whole number (without decimals) that must fit the following criteria:
- It cannot contain commas or blanks
- It must not have a decimal point
- It can be either positive or negative
PHP Float
A float, or floating point number, is a number that includes a decimal point.
PHP Boolean
Most of the data types can be used in combination with one another. In this
example, string and integer are put together to determine the sum of two numbers.
<?php
$str = "10";
$int = 20;
echo ($sum);
?>
Result:
Variables Scope
PHP variables can be declared anywhere in the script.
The scope of a variable is the part of the script in which the variable can be referenced or
used.
$name = 'David';
function getName() {
echo $name;
getName();
?>
Result:
This script will produce an error, as the $name variable has a global scope, and is not accessible
within the getName() function.
$name = 'David';
function getName() {
global $name;
echo $name;
getName();
?>
Result:
Variable Variables
With PHP, you can use one variable to specify another variable's name.
So, a variable variable treats the value of another variable as its name.
For example:
<?php
$a = 'hello';
$hello = "Hi!";
echo $$a;
?>
Result:
Arrays
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of names, for example), storing them in single variables
would look like this:
But what if you have 100 names on your list? The solution: Create an array!
Numeric Arrays
Numeric or indexed arrays associate a numeric index with their values.
The index can be assigned automatically (index always starts at 0), like this:
echo $names[1];
?>
Result:
Numeric Arrays
You can have integers, strings, and other data types together in one array.
Example:
<?php
$myArray[0] = "John";
$myArray[1] = "<strong>PHP</strong>";
$myArray[2] = 21;
?>
Result:
Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
Associative Arrays
Use the named keys to access the array's members.
<?php
$people = array("David"=>"27", "Amy"=>"21", "John"=>"42");
echo $people['Amy'];
?>
Result:
Multi-Dimensional Arrays
A multi-dimensional array contains one or more arrays.
The dimension of an array indicates the number of indices you would need to select an
element.
- For a two-dimensional array, you need two indices to select an element
- For a three-dimensional array, you need three indices to select an element
Multi-Dimensional Arrays
Let's create a two-dimensional array that contains 3 arrays:
Now the two-dimensional $people array contains 3 arrays, and it has two
indices: row and column.
To access the elements of the $people array, we must point to the two indices.
<?php
$people = array(
'online'=>array('David', 'Amy'),
'away'=>array('Arthur', 'Daniel')
);
echo $people['online'][0];
echo $people['away'][1];
?>
Result:
Conditional Statements
Conditional statements perform different actions for different decisions.
The if else statement is used to execute a certain code if a condition is true, and another
code if the condition is false.
Syntax:
If Else
The example below will output the greatest number of the two.
<?php
$x = 10;
$y = 20;
echo $x;
} else {
echo $y;
?>
Result:
Syntax:
$age = 21;
if ($age<=13) {
echo "Child.";
echo "Teenager";
} else {
echo "Adult";
?>
Result:
Loops
When writing code, you may want the same block of code to run over and over again. Instead of
adding several almost equal code-lines in a script, we can use loops to perform a task like this.
$i = 1;
$i++;
?>
Result:
$i = 5;
do {
$i++;
?>
Result:
Parameters:
init: Initialize the loop counter value
test: Evaluates each time the loop is iterated, continuing if evaluates to true, and ending if it
evaluates to false
increment: Increases the loop counter value
The for Loop
The example below displays the numbers from 0 to 5:
<?php
?>
Result:
The first form loops over the array. On each iteration, the value of the current element is assigned
to $value, and the array pointer is moved by one, until it reaches the last array element.
The second form will additionally assign the current element's key to the $key variable on each
iteration.
The following example demonstrates a loop that outputs the values of the $names array.
<?php
?>
Result:
Syntax:
First, our single expression, n (most often a variable), is evaluated once. Next, the value of the
expression is compared with the value of each case in the structure. If there is a match, the block
of code associated with that case is executed.
Switch
Consider the following example, which displays the appropriate message for each day.
<?php
$today = 'Wed';
switch ($today) {
case "Mon":
break;
case "Tue":
break;
case "Wed":
break;
case "Thu":
break;
case "Fri":
break;
case "Sat":
break;
case "Sun":
break;
default:
echo "Invalid day.";
?>
Result:
default
The default statement is used if no match is found.
<?php
$x=5;
switch ($x) {
case 1:
echo "One";
break;
case 2:
echo "Two";
break;
default:
?>
Result:
Switch
Failing to specify the break statement causes PHP to continue to executing the
statements that follow the case, until it finds a break. You can use this behavior if you
need to arrive at the same output for more than one case.
<?php
$day = 'Wed';
switch ($day) {
case 'Mon':
break;
case 'Tue':
case 'Wed':
case 'Thu':
break;
case 'Fri':
echo 'Friday!';
break;
default:
echo 'Weekend!';
?>
Result:
The break Statement
As discussed in the previous lesson, the break statement is used to break out of
the switch when a case is matched.
If the break is absent, the code keeps running. For example:
<?php
$x=1;
switch ($x) {
case 1:
echo "One";
case 2:
echo "Two";
case 3:
echo "Three";
default:
?>
Result:
Break can also be used to halt the execution of for, foreach, while, do-while structures.
if ($i%2==0) {
continue;
?>
Result:
include
The include and require statements allow for the insertion of the content of one PHP file
into another PHP file, before the server executes it.
Including files saves quite a bit of work. You can create a standard header, footer, or
menu file for all of your web pages. Then, when the header is requiring updating, you can
update the header include file only.
Result:
include vs require
The require statement is identical to include, the exception being that, upon failure, it
produces a fatal error.
When a file is included using the include statement, but PHP is unable to find it, the
script continues to execute.
In the case of require, the script will cease execution and produce an error.
Functions
A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads. It will be executed by a call
to the function.
A user defined function declaration starts with the word function:
A function name can start with a letter or an underscore, but not with a number or a special
symbol.
Functions
In the example below, we create the function sayHello(). The opening curly brace ({)
indicates that this is the beginning of the function code, while the closing curly brace (})
indicates that this is the end.
To call the function, just write its name:
<?php
function sayHello() {
echo "Hello!";
?>
Result:
Function Parameters
Information can be passed to functions through arguments, which are like variables.
Arguments are specified after the function name, and within the parentheses.
Here, our function takes a number, multiplies it by two, and prints the result:
<?php
function multiplyByTwo($number) {
$answer = $number * 2;
echo $answer;
multiplyByTwo(3);
?>
Result:
You can add as many arguments as you want, as long as they are separated with commas
<?php
multiply(3, 6);
?>
Result:
Default Arguments
Default arguments can be defined for the function arguments.
In the example below, we're calling the function setCounter(). There are no arguments,
so it will take on the default values that have been defined.
<?php
function setCounter($num=10) {
setCounter(42); //Counter is 42
setCounter(); //Counter is 10
?>
Result:
Return
A function can return a value using the return statement.
Return stops the function's execution, and sends the value back to the calling code.
For example:
<?php
return $res;
?>
Result:
Predefined Variables
A superglobal is a predefined variable that is always accessible, regardless of scope. You can
access the PHP superglobals through any function, class, or file.
$_SERVER
$_SERVER is an array that includes information such as headers, paths, and script locations. The
entries in this array are created by the web server.
$_SERVER['SCRIPT_NAME'] returns the path of the current script:
<?php
echo $_SERVER['SCRIPT_NAME'];
?>
Result:
$_SERVER
$_SERVER['HTTP_HOST'] returns the Host header from the current request.
This method can be useful when you have a lot of images on your server and need to transfer the
website to another host. Instead of changing the path for each image, you can do the following:
Create a config.php file, that holds the path to your images:
Result:
Forms
The action attribute specifies that when the form is submitted, the data is sent to a PHP
file named first.php.
HTML form elements have names, which will be used when accessing the data with
PHP.
Forms
Now, when we have an HTML form with the action attribute set to our PHP file, we can
access the posted form data using the $_POST associative array.
In the first.php file:
The $_POST superglobal array holds key/value pairs. In the pairs, keys are the names of the
form controls and values are the input data entered by the user.
POST
The two methods for submitting forms are GET and POST.
Information sent from a form via the POST method is invisible to others, since all names
and/or values are embedded within the body of the HTTP request. Also, there are no
limits on the amount of information to be sent.
Moreover, POST supports advanced functionality such as support for multi-part binary
input while uploading files to the server.
However, it is not possible to bookmark the page, as the submitted values are not visible.
GET
Information sent via a form using the GET method is visible to everyone (all variable
names and values are displayed in the URL). GET also sets limits on the amount of
information that can be sent - about 2000 characters.
However, because the variables are displayed in the URL, it is possible to bookmark the
page, which can be useful in some situations.
For example:
actionGet.php
Now, the form is submitted to the actionGet.php, and you can see the submitted data in
the URL:
Sessions
Using a session, you can store information in variables, to be used across multiple pages.
Information is not stored on the user's computer, as it is with cookies.
By default, session variables last until the user closes the browser.
Now, the color and name session variables are accessible on multiple pages, throughout the
entire session.
Session Variables
Another page can be created that can access the session variables we set in the previous
page:
Cookies
Cookies are often used to identify the user. A cookie is a small file that the server embeds
on the user's computer. Each time the same computer requests a page through a browser,
it will send the cookie, too. With PHP, you can both create and retrieve cookie values.
Cookies
The following example creates a cookie named "user" with the value "John".
The cookie will expire after 30 days, which is written as 86,400 * 30, in which 86,400
seconds = one day. The '/' means that the cookie is available throughout the entire
website.
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE).
We also use the isset() function to find out if the cookie is set:
Manipulating Files
PHP offers a number of functions to use when creating, reading, uploading, and editing
files.
The fopen() function creates or opens a file. If you use fopen() with a file that does not
exist, the file will be created, given that the file has been opened for writing (w) or
appending (a).
The example below creates a new file, "file.txt", which will be created in the same
directory that houses the PHP code.
Write to File
When writing to a file, use the fwrite() function.
The first parameter of fwrite() is the file to write to; the second parameter is the string to
be written.
The example below writes a couple of names into a new file called "names.txt".
Notice that we wrote to the file "names.txt" twice, and then we used the fclose() function to close
the file.
fclose()
The fclose() function closes an open file and returns TRUE on success or FALSE on
failure.
fopenAppending to a File
If you want to append content to a file, you need to open the file in append mode.
For example:
Appending to a File
Let's create an example of a form that adds filled-in data to a file.
Now, each time a name is entered and submitted, it's added to the "names.txt" file, along with a
new line.
The isset() function determined whether the form had been submitted, as well as whether the text
contained a value.
Reading a File
The file() function reads the entire file into an array. Each element within
the array corresponds to a line in the file:
<?php
$txt = "John\n";
fwrite($myfile, $txt);
$txt = "David\n";
fwrite($myfile, $txt);
fclose($myfile);
$read = file('names.txt');
?>
Result:
This prints all of the lines in the file, and separates them with commas.
Reading a File
At the end of the output in the previous example, we would have a comma, as we print it
after each element of the array.
The following code lets us avoid printing that final comma.
<?php
$myfile = fopen("names.txt", "w");
$txt = "John\n";
fwrite($myfile, $txt);
$txt = "David\n";
fwrite($myfile, $txt);
fclose($myfile);
$read = file('names.txt');
$count = count($read);
$i = 1;
echo $line;
$i++;
?>
Result:
The $count variable uses the count function to obtain the number of elements in the $read array.
Then, in the foreach loop, after each line prints, we determine whether the current line is less than
the total number of lines, and print a comma if it is.