PHP Basics
PHP Basics
com)
What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC,
etc.) PHP is an open source software PHP is free to download and use
What is a PHP File? PHP files can contain text, HTML tags and scripts PHP files are returned to the browser as plain HTML PHP files have a file extension of ".php", ".php3", or ".phtml"
PHP code is executed on the server, and the plain HTML result is sent to the browser.
<?php ?>
A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code. Below, we have an example of a simple PHP script which sends the text "Hello World" to the browser:
Comments in PHP
In PHP, we use // to make a single-line comment or /* and */ to make a large comment block.
<html> <body> <?php //This is a comment /* This is a comment block */ ?> </body>
</html>
Variables are used for storing values, such as numbers, strings or function results, so that they can be used many times in a script.
Variables in PHP
Variables are used for storing a values, like text strings, numbers or arrays. When a variable is set it can be used over and over again in your script All variables in PHP start with a $ sign symbol. The correct way of setting a variable in PHP:
$var_name = value;
New PHP programmers often forget the $ sign at the beginning of the variable. In that case it will not work. Let's try creating a variable with a string, and a variable with a number:
Variable Naming Rules A variable name must start with a letter or an underscore "_" A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ ) A variable name should not contain spaces. If a variable name is more than one word, it should be
separated with underscore ($my_string), or with capitalization ($myString)
Strings
Strings in PHP
String variables are used for values that contains character strings. In this tutorial we are going to look at some of the most common functions and operators used to manipulate strings in PHP. After we create a string we can manipulate it. A string can be used directly in a function or it can be stored in a variable. Below, the PHP script assigns the string "Hello World" to a string variable called $txt:
Hello World
Now, lets try to use some different functions and operators to manipulate our string.
There is only one string operator in PHP. The concatenation operator (.) is used to put two string values together. To concatenate two variables together, use the dot (.) operator:
12
The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string)
6
As you see the position of the string "world" in our string is position 6. The reason that it is 6, and not 7, is that the first position in the string is 0, and not 1. Operators are used to operate on values.
PHP Operators
This section lists the different operators used in PHP. Arithmetic Operators Operator Description Example Result + Addition x=2 x+2 4 - Subtraction x=2 5-x 3 * Multiplication x=4 x*5 20 / Division 15/5 5/2 3 2.5 % Modulus (division remainder) 5%2 10%8 10%2 1 2 0 ++ Increment x=5 x++ x=6
-- Decrement x=5 x-x=4 Assignment Operators Operator Example Is The Same As = x=y x=y += x+=y x=x+y -= x-=y x=x-y *= x*=y x=x*y /= x/=y x=x/y .= x.=y x=x.y %= x%=y x=x%y Comparison Operators Operator Description Example == is equal to 5==8 returns false != is not equal 5!=8 returns true > is greater than 5>8 returns false < is less than 5<8 returns true >= is greater than or equal to 5>=8 returns false <= is less than or equal to 5<=8 returns true Logical Operators Operator Description Example && and x=6 y=3 (x < 10 && y > 1) returns true || or x=6 y=3 (x==5 || y==5) returns false ! not x=6 y=3 !(x==y) returns true
If.. Else
The if, elseif and else statements in PHP are used to perform different actions based on different conditions.
Conditional Statements
Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. if...else statement - use this statement if you want to execute a set of code when a condition is true and another if the condition is not true elseif statement - is used with the if...else statement to execute a set of code if one of several condition are true
If you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement.
The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!":
Syntax if (condition) code to be executed if condition is true; else code to be executed if condition is false; Example <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; else
<html> <body> <?php $d=date("D"); if ($d=="Fri") { echo "Hello!<br />"; echo "Have a nice weekend!"; echo "See you on Monday!"; } ?> </body> </html>
Syntax if (condition) code to be executed if condition is true; elseif (condition) code to be executed if condition is true; else code to be executed if condition is false; Example <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; elseif ($d=="Sun") echo "Have a nice Sunday!"; else echo "Have a nice day!"; ?> </body> </html>
The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":
Switch
The Switch statement in PHP is used to perform one of several different actions based on one of several different conditions.
If you want to select one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code.
break; case label2: code to be executed if expression = label2; break; default: code to be executed if expression is different from both label1 and label2; } Example
This is how it works: A single expression (most often a variable) is evaluated once The value of the expression is compared with the values for each case in the structure If there is a match, the code associated with that case is executed After a code is executed, break is used to stop the code from running into the next case The default statement is used if none of the cases are true
<html> <body> <?php switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3"; } ?> </body> </html>
What is an array?
When working with PHP, sooner or later, you might want to create many similar variables. Instead of having many similar variables, you can store the data as elements in an array. Each element in the array has its own ID so that it can be easily accessed. There are three different kind of arrays: Numeric array - An array with a numeric ID key Associative array - An array where each ID key is associated with a value Multidimensional array - An array containing one or more arrays
Numeric Arrays
A numeric array stores each element with a numeric ID key. There are different ways to create a numeric array.
Example 1
$names[2] = "Joe"; echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors"; ?>
The code above will output:
Associative Arrays
An associative array, each ID key is associated with a value. When storing data about specific named values, a numerical array is not always the best way to do it. With associative arrays we can use the values as keys and assign values to them.
Example 1
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); Example 2 $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34";
The ID keys can be used in a script:
This example is the same as example 1, but shows a different way of creating the array:
<?php $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; echo "Peter is " . $ages['Peter'] . " years old."; ?>
The code above will output:
Multidimensional Arrays
In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.
Example
$families = array ( "Griffin"=>array ( "Peter", "Lois", "Megan" ), "Quagmire"=>array ( "Glenn" ), "Brown"=>array ( "Cleveland", "Loretta", "Junior" ) );
The array above would look like this if written to the output:
Array ( [Griffin] => Array ( [0] => Peter [1] => Lois
[2] => Megan ) [Quagmire] => Array ( [0] => Glenn ) [Brown] => Array ( [0] => Cleveland [1] => Loretta [2] => Junior ) ) Example 2
Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to perform this. In PHP we have the following looping statements: while - loops through a block of code if and as long as a specified condition is true do...while - loops through a block of code once, and then repeats the loop as long as a special condition is true for - loops through a block of code a specified number of times foreach - loops through a block of code for each element in an array
Looping
The while statement will execute a block of code if and as long as a condition is true.
The following example demonstrates a loop that will continue to run as long as the variable i is less than, or equal to 5. i will increase by 1 each time the loop runs:
<html> <body> <?php $i=1; while($i<=5) { echo "The number is " . $i . "<br />"; $i++; } ?> </body> </html>
The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true.
<html> <body> <?php $i=0; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<5); ?> </body> </html>
The for statement is the most advanced of the loops in PHP. In it's simplest form, the for statement is used when you know how many times you want to execute a statement or a list of statements.
Example
The following example prints the text "Hello World!" five times:
<html> <body> <?php for ($i=1; $i<=5; $i++) { echo "Hello World!<br />"; } ?> </body> </html>
The foreach statement is used to loop through arrays. For every loop, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop, you'll be looking at the next element.
The following example demonstrates a loop that will print the values of the given array:
<html> <body> <?php $arr=array("one", "two", "three"); foreach ($arr as $value) { echo "Value: " . $value . "<br />"; } ?> </body> </html>
The real power of PHP comes from its functions. In PHP - there are more than 700 built-in functions available.
PHP Functions
In this tutorial we will show you how to create your own functions. For a reference and examples of the built-in functions, please visit our PHP Reference.
A function is a block of code that can be executed whenever we need it. Creating PHP functions: All functions start with the word "function()" Name the function - It should be possible to understand what the function does by its name. The name can start with a letter or underscore (not a number) Add a "{" - The function code starts after the opening curly brace Insert the function code Add a "}" - The function is finished by a closing curly brace
Example
<html> <body> <?php function writeMyName() { echo "Kai Jim Refsnes"; } writeMyName(); ?> </body> </html>
<html> <body> <?php function writeMyName() { echo "Kai Jim Refsnes"; } echo "Hello world!<br />"; echo "My name is "; writeMyName(); echo ".<br />That's right, "; writeMyName(); echo " is my name."; ?> </body> </html>
The output of the code above will be:
Hello world! My name is Kai Jim Refsnes. That's right, Kai Jim Refsnes is my name.
Example 1
The following example will write different first names, but the same last name:
<html> <body> <?php function writeMyName($fname) { echo $fname . " Refsnes.<br />"; } echo "My name is "; writeMyName("Kai Jim"); echo "My name is "; writeMyName("Hege"); echo "My name is "; writeMyName("Stale"); ?> </body> </html>
The output of the code above will be:
My name is Kai Jim Refsnes. My name is Hege Refsnes. My name is Stale Refsnes. Example 2
<html> <body> <?php function writeMyName($fname,$punctuation) { echo $fname . " Refsnes" . $punctuation . "<br />"; } echo "My name is "; writeMyName("Kai Jim",".");
echo "My name is "; writeMyName("Hege","!"); echo "My name is "; writeMyName("Stle","..."); ?> </body> </html>
The output of the code above will be:
My name is Kai Jim Refsnes. My name is Hege Refsnes! My name is Stle Refsnes...
Example <html> <body> <?php function add($x,$y) { $total = $x + $y; return $total; } echo "1 + 16 = " . add(1,16); ?> </body> </html>
The output of the code above will be:
1 + 16 = 17
FORMS
The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input.
The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts. Form example:
<html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html>
The example HTML page above contains two input fields and a submit button. When the user fills in this form and click on the submit button, the form data is sent to the "welcome.php" file. The "welcome.php" file looks like this:
<html> <body> Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html>
A sample output of the above script may be:
The PHP $_GET and $_POST variables will be explained in the next chapters.
Form Validation
User input should be validated whenever possible. Client side validation is faster, and will reduce server load. However, any site that gets enough traffic to worry about server resources, may also need to worry about site security. You should always use server side validation if the form accesses a database. A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error.
$_GET
The $_GET variable is used to collect values from a form with method="get".
The $_GET variable is an array of variable names and values sent by the HTTP GET method. The $_GET variable is used to collect values from a form with method="get". Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and it has limits on the amount of information to send (max. 100 characters).
Example <form action="welcome.php" method="get"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form>
When the user clicks the "Submit" button, the URL sent could look something like this:
http://www.w3schools.com/welcome.php?name=Peter&age=37
The "welcome.php" file can now use the $_GET variable to catch the form data (notice that the names of the form fields will automatically be the ID keys in the $_GET array):
Welcome <?php echo $_GET["name"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old!
Note: When using the $_GET variable all variable names and values are displayed in the URL. So this method should not be used when sending passwords or other sensitive information! However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. Note: The HTTP GET method is not suitable on large variable values; the value cannot exceed 100 characters.
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.
Example Welcome <?php echo $_REQUEST["name"]; ?>.<br /> You are <?php echo $_REQUEST["age"]; ?> years old!
The $_POST variable is used to collect values from a form with method="post".
The $_POST variable is an array of variable names and values sent by the HTTP POST method. The $_POST variable is used to collect values from a form with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.
Example <form action="welcome.php" method="post"> Enter your name: <input type="text" name="name" /> Enter your age: <input type="text" name="age" /> <input type="submit" /> </form>
When the user clicks the "Submit" button, the URL will not contain any form data, and will look something
like this:
http://www.w3schools.com/welcome.php
The "welcome.php" file can now use the $_POST variable to catch the form data (notice that the names of the form fields will automatically be the ID keys in the $_POST array):
Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old!
Why use $_POST? Variables sent with HTTP POST are not shown in the URL Variables have no length limit
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.
Example Welcome <?php echo $_REQUEST["name"]; ?>.<br /> You are <?php echo $_REQUEST["age"]; ?> years old!
The PHP date() function is used to format a time or a date.
The PHP date() function formats a timestamp to a more readable date and time.
Parameter Description format Required. Specifies the format of the timestamp timestamp Optional. Specifies a timestamp. Default is the current date and time (as a timestamp)
<?php echo date("Y/m/d"); echo "<br />"; echo date("Y.m.d"); echo "<br />"; echo date("Y-m-d"); ?>
The output of the code above could be something like this:
The second parameter in the date() function specifies a timestamp. This parameter is optional. If you do not supply a timestamp, the current time will be used. In our next example we will use the mktime() function to create a timestamp for tomorrow. The mktime() function returns the Unix timestamp for a specified date.
Syntax mktime(hour,minute,second,month,day,year,is_dst)
To go one day in the future we simply add one to the day argument of mktime():
Tomorrow is 2006/07/12
For more information about all the PHP date functions, please visit our PHP Date Reference. Server Side Includes (SSI) are used to create functions, headers, footers, or elements that will be reused on multiple pages. You can insert the content of a file into a PHP file before the server executes it, with the include() or require() function. The two functions are identical in every way, except how they handle errors. The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error). These two functions are used to create functions, headers, footers, or elements that can be reused on multiple pages. This can save the developer a considerable amount of time. This means that you can create a standard header or menu file that you want all your web pages to include. When the header needs to be updated, you can only update this one include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all web pages).
The include() function takes all the text in a specified file and copies it into the file that uses the include function. Assume that you have a standard header file, called "header.php". To include the header file in a page, use the include() function, like this:
<html> <body> <?php include("header.php"); ?> <h1>Welcome to my home page</h1> <p>Some text</p> </body> </html> Example 2
Now, let's assume we have a standard menu file that should be used on all pages (include files usually have a ".php" extension). Look at the "menu.php" file below:
<html> <body> <a href="http://www.w3schools.com/default.php">Home</a> | <a href="http://www.w3schools.com/about.php">About Us</a> | <a href="http://www.w3schools.com/contact.php">Contact Us</a>
The three files, "default.php", "about.php", and "contact.php" should all include the "menu.php" file. Here is the code in "default.php":
<?php include("menu.php"); ?> <h1>Welcome to my home page</h1> <p>Some text</p> </body> </html>
If you look at the source code of the "default.php" in a browser, it will look something like this:
<a href="contact.php">Contact Us</a> <h1>Welcome to my home page</h1> <p>Some text</p> </body> </html>
And, of course, we would have to do the same thing for "about.php" and "contact.php". By using include files, you simply have to update the text in the "menu.php" file if you decide to rename or change the order of the links or add another web page to the site.
The require() function is identical to include(), except that it handles errors differently. The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error). If you include a file with the include() function and an error occurs, you might get an error message like the one below. PHP code:
<html> <body> <?php include("wrongFile.php"); echo "Hello World!"; ?> </body> </html>
Error message:
Warning: include(wrongFile.php) [function.include]: failed to open stream: No such file or directory in C:\home\website\test.php on line 5 Warning: include() [function.include]: Failed opening 'wrongFile.php' for inclusion (include_path='.;C:\php5\pear') in C:\home\website\test.php on line 5 Hello World!
Notice that the echo statement is still executed! This is because a Warning does not stop the script execution. Now, let's run the same example with the require() function. PHP code:
<html> <body> <?php require("wrongFile.php"); echo "Hello World!"; ?> </body> </html>
Error message:
Warning: require(wrongFile.php) [function.require]: failed to open stream: No such file or directory in C:\home\website\test.php on line 5 Fatal error: require() [function.require]: Failed opening required 'wrongFile.php' (include_path='.;C:\php5\pear') in C:\home\website\test.php on line 5
The echo statement was not executed because the script execution stopped after the fatal error. It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.
The fopen() function is used to open files in PHP. The fopen() function is used to open files in PHP. The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened:
Example
The following example generates a message if the fopen() function is unable to open the specified file:
<html> <body> <?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); ?> </body> </html>
Closing a File
The fclose() function is used to close an open file:
Check End-of-file
The feof() function checks if the "end-of-file" (EOF) has been reached. The feof() function is useful for looping through data of unknown length. Note: You cannot read from files opened in w, a, and x mode!
Example
The example below reads a file line by line, until the end of file is reached:
<?php $file = fopen("welcome.txt", "r") or exit("Unable to open file!"); //Output a line of the file until the end is reached while(!feof($file)) { echo fgets($file). "<br />";
} fclose($file); ?>
The fgetc() function is used to read a single character from a file. Note: After a call to this function the file pointer moves to the next character. The example below reads a file character by character, until the end of file is reached:
<?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); while (!feof($file)) { echo fgetc($file); } fclose($file); ?>
When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks. This tutorial contains some of the most common error checking methods in PHP. We will show different error handling methods: Simple "die()" statements Custom errors and error triggers Error reporting
The first example shows a simple script that opens a text file:
Warning: fopen(welcome.txt) [function.fopen]: failed to open stream: No such file or directory in C:\webfolder\test.php on line 2
To avoid that the user gets an error message like the one above, we test if the file exist before we try to access it:
This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context):
Syntax
error_function(error_level,error_message, error_file,error_line,error_context)
Parameter Description error_level Required. Specifies the error report level for the user-defined error. Must be a value number. See table below for possible error report levels error_message Required. Specifies the error message for the user-defined error error_file Optional. Specifies the filename in which the error occurred error_line Optional. Specifies the line number in which the error occurred error_context Optional. Specifies an array containing every variable, and their values, in use when the error occurred These error report levels are the different types of error the user-defined error handler can be used for: Value Constant Description 2 E_WARNING Non-fatal run-time errors. Execution of the script is not halted 8 E_NOTICE Run-time notices. The script found something that might be an error, but could also happen when running a script normally 256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error() 512 E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error() 1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error() 4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler()) 8191 E_ALL All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0) Now lets create a function to handle errors:
function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr<br />"; echo "Ending Script"; die(); }
The code above is a simple error handling function. When it is triggered, it gets the error level and an error message. It then outputs the error level and message and terminates the script. Now that we have created an error handling function we need to decide when it should be triggered.
The default error handler for PHP is the built in error handler. We are going to make the function above the default error handler for the duration of the script. It is possible to change the error handler to apply for only some errors, that way the script can handle different errors in different ways. However, in this example we are going to use our custom error handler for all errors:
set_error_handler("customError");
Since we want our custom function to handle all errors, the set_error_handler() only needed one parameter, a second parameter could be added to specify an error level.
Example
Testing the error handler by trying to output variable that does not exist:
<?php //error handler function function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr"; } //set error handler set_error_handler("customError"); //trigger error echo($test);
?>
The output of the code above should be something like this:
Trigger an Error
In a script where users can input data it is useful to trigger errors when an illegal input occurs. In PHP, this is done by the trigger_error() function.
Example
In this example an error occurs if the "test" variable is bigger than "1":
Example
In this example an E_USER_WARNING occurs if the "test" variable is bigger than "1". If an E_USER_WARNING occurs we will use our custom error handler and end the script:
<?php //error handler function function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr<br />"; echo "Ending Script"; die(); } //set error handler set_error_handler("customError",E_USER_WARNING); //trigger error $test=2; if ($test>1) { trigger_error("Value must be 1 or below",E_USER_WARNING); } ?>
The output of the code above should be something like this:
Error Logging
By default, PHP sends an error log to the servers logging system or a file, depending on how the error_log configuration is set in the php.ini file. By using the error_log() function you can send error logs to a specified
file or a remote destination. Sending errors messages to yourself by e-mail can be a good way of getting notified of specific errors.
In the example below we will send an e-mail with an error message and end the script, if a specific error occurs:
<?php //error handler function function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr<br />"; echo "Webmaster has been notified"; error_log("Error: [$errno] $errstr",1, "[email protected]","From: [email protected]"); } //set error handler set_error_handler("customError",E_USER_WARNING); //trigger error $test=2; if ($test>1) { trigger_error("Value must be 1 or below",E_USER_WARNING); } ?>
The output of the code above should be something like this: