Write a comment on this article
Here you can find different tips and tricks, advice and guides which are worth knowing about PHP.
Quickmenu: Comparing values and their types, Using variable variables, Working with cookies, Handling requests and form data, Session handling, Reading server information, The thing with the string, Looping with foreach, The ternary operator, Suppressing errors
You know that comparison of two values in PHP is very tolerant and easy, like in the following example:
<?php $variable_string = "05"; $variable_int = 5; $variable_null = null; $variable_0 = 0; $variable_false = "false"; echo $variable_string == "05" ? "true" : "false"; echo "<br />"; //true echo $variable_string == $variable_int ? "true" : "false"; echo "<br />"; //true echo $variable_int == "005" ? "true" : "false"; echo "<br />"; //true echo $variable_null == "null" ? "true" : "false"; echo "<br />"; //false echo $variable_null == null ? "true" : "false"; echo "<br />"; //true echo $variable_null == $variable_0 ? "true" : "false"; echo "<br />"; //true echo $variable_false == "false" ? "true" : "false"; echo "<br />"; //true echo $variable_false == false ? "true" : "false"; echo "<br />"; //false ?>
As you can see, is some cases the datatype and even the value doesn't matter, like $variable_null == $variable_0 equals true. You can see the output of this example here: Value_comparison_example1.php.
Anyway, sometimes it is necessary to compare the datatype too. This can be achieved by using the comparison operators === (identical) and !== (not identical). Applying these operator to the example above, it will give different results:
<?php $variable_string = "05"; $variable_int = 5; $variable_null = null; $variable_0 = 0; $variable_false = "false"; echo $variable_string === "05" ? "true" : "false"; echo "<br />"; //true echo $variable_string === $variable_int ? "true" : "false"; echo "<br />"; //false echo $variable_int === "005" ? "true" : "false"; echo "<br />"; //false echo $variable_null === "null" ? "true" : "false"; echo "<br />"; //false echo $variable_null === null ? "true" : "false"; echo "<br />"; //true echo $variable_null === $variable_0 ? "true" : "false"; echo "<br />"; //false echo $variable_false === "false" ? "true" : "false"; echo "<br />"; //true echo $variable_false === false ? "true" : "false"; echo "<br />"; //false ?>
See the difference? E.g. $variable_string === $variable_int now results in false, because the types of these variables are different (string and integer). The results of the second example can be found here: Value_comparison_example2.php.
More about comparison can be found under the section "Comparison Operators" on PHP's official website: http://www.php.net/manual/en/language.operators.comparison.php
Sounds weird, right? But it's possible and sometimes useful to have variable variables. If you ever come accross the need of using a variable variable, here is how it works:
<?php $variable_a = "variable_b"; $$variable_a = "variable_c"; //now we have a variable called $variable_b with value "variable_c" echo $variable_a; //prints "variable_b" echo $variable_b; //prints "variable_c" ?>
The magic word is double dollar. By using $$ the value of a variable is taken as the name for a new variable. See the manual about variable variables on PHP's official website: http://www.php.net/manual/en/language.variables.variable.php.
PHP provides several functions to work with cookies. Most important is to set, read and delete a cookie. First things first:
Setting cookies
The following function allows you to set a cookie:
bool setcookie ( string $name
[, string $value
[, int $expire
[, string $path
[, string $domain
[, bool $secure
[, bool $httponly ]]]]]] )
Interesting are the parameters name (the name of the cookie to read it again), value (the actual value of the cookie) and expire (the time the cookie expires, set as a Unix timestamp). See http://www.php.net/manual/en/function.setcookie.php for details.
Reading cookies
Reading cookies is quite easy with the predefined variable $_COOKIE. This variable contains all cookies previously set in an associative array. Details can be found at http://www.php.net/manual/en/reserved.variables.cookies.php.
Deleting cookies
To delete a cookie, the same function as to set a cookie is used: setcookie (see above). You just need to set the expiration date to the past.
Example
Here is a simple example that contains setting, reading and deleting a cookie. Try this example here: Cookie_example.php.
<?php
if(isset($_COOKIE["my_cookie"])){ //is cookie set?
//print the value of the cookie
echo "cookie value: {$_COOKIE["my_cookie"]}";
//delete the cookie
setcookie("my_cookie","",time()-3600);
echo "<br />cookied deleted again";
}else{ //cookie is not set
//set cookie, expires in one hour
setcookie("my_cookie","cookie was set at ".date("H:m:s"),time()+3600);
echo "cookie set";
}
?>
<br><a href="Cookie_example.php">reload</a>
Remember that the user needs cookies to be enabled in his browser. Unfortunately, the method setcookie does not return false if the browser doesn't accept cookies. So you will have to check afterwards if the cookie is set.
What PHP makes so strong is the simple and easy request handling. To simplify it, an HTTP request can be one of two types: get or post. Both can contain data and have some limitations (e.g. get requests have a limited length, not by specification, but by webservers).
The get request
When you click on a link in your browser, your browser normally sends a get request to the webserver. The request consists of a type (in this case get), some client information (like language or user-agent = browser), cookies, and, most important for us, a URL (the address in your browser). This URL may contain a servername, a directoryname, a filename, etc., and parameters as strings (first parameter is delimitted with ?, following ones with &, e.g.: http://www.yourdomain.abc/foldername/filename.php?firstparam=abc&secondparam=def). These parameters consist of key-value-pairs and are accessed in PHP through the associative array $_GET. Example:
<?php //GET request //URL: /index.php?firstparam=abc&secondparam=def&thirdparam $firstparam = $_GET["firstparam"]; //variable $firstparam now is a string and contains abc $secondparam = $_GET["secondparam"]; //variable $secondparam now is a string and contains def $thirdparam = $_GET["thirdparam"]; //variable $thirdparam now is a string and is empty $fourthparam = $_GET["fourthparam"]; //variable $fourthparam now is a string and is empty ?>
The post request
Post requests are mostly sent by submitting a form and consist of nearly the same information as get requests. The difference is: it's possible to send data (text and binary) with the request. So if you want to upload a file through a form, you need to use the post request. All strings which are sent with the post request are accessible through the associative array $_POST, all files through $_FILES. Watch out: the parameters sent with the URL are still accessed through $_GET. And also important: if your form contains a field to upload a file, you must set the attribute enctype (encoding type) to "multipart/form-data":
<form method="post" action="upload.php" enctype="multipart/form-data"> <input ... </form>
Here is a short example to process post requests:
<?php //POST request //URL: /index.php?firstparam=abc //Data: firstkey=def&secondkey=ghi $firstparam = $_GET["firstparam"]; //variable $firstparam now is a string and contains abc $firstkey = $_POST["firstkey"]; //variable $firstkey now is a string and contains def $secondkey = $_POST["secondkey"]; //variable $secondkey now is a string and contains ghi ?>
All in one
There is one reserved variable that contains both get and post request data, and even cookies. This global associative array is $_REQUEST. In the example above we had to use $_GET and $_POST, because some values were retrieved from the URL, some from the post request data. In the following example, these values are retrieved from $_REQUEST:
<?php //POST request //URL: /index.php?firstparam=abc //Data: firstkey=def&secondkey=ghi $firstparam = $_REQUEST["firstparam"]; //variable $firstparam now is a string and contains abc $firstkey = $_REQUEST["firstkey"]; //variable $firstkey now is a string and contains def $secondkey = $_REQUEST["secondkey"]; //variable $secondkey now is a string and contains ghi ?>
Example
As you got the basics to work with HTTP requests and form data now, let's try a simple example containing the variables $_REQUEST and $_FILES. This example works as follows: the user fills in the form (two textfields and one file) and submits it. The script reads the data sent with the form and ouputs the values. See here how the example works: Request_example.php. Note: this script only reads the uploaded file and doesn't store it somewhere for further use. If you want to do this, you can use the function move_uploaded_file.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Request example</title>
</head>
<body>
<?php if(isset($_POST["submit_form"])){ //the submit button has been pressed ?>
<h3>Results</h3>
<table>
<tr>
<td>Your name:</td>
<td><?php echo $_POST["your_name"]; ?></td>
</tr>
<tr>
<td>Your age:</td>
<td><?php echo $_POST["your_age"]; ?></td>
</tr>
<tr>
<td valign="top">Your file:</td>
<td>
<?php
//read the file
$your_file = $_FILES["your_file"];
if(!$your_file){ //no file has been uploaded
echo "no file uploaded";
}else{ //a file has been uploaded
if($your_file["size"]>(1024*100)){ //check if the filesize is larger than 100KB
echo "file too large";
}else{ //filesize is ok
echo "Filename: {$your_file["name"]}<br />";
echo "Filetype: {$your_file["type"]}<br />";
//calculate bytes to kilobytes and format the number
echo "Filesize: ".number_format($your_file["size"]/1024,2,".",",")." kilobytes<br />";
}
}
?>
</td>
</tr>
</table>
<p><a href="Request_example.php">Click here to go back to the form.</a></p>
<?php }else{ //form has not been submitted ?>
<form method="post" action="Request_example.php" enctype="multipart/form-data">
<h3>Simple request test</h3>
<p>Fill in the form below. The file is limited to 100KB.</p>
<table>
<tr>
<td>Your name:</td>
<td><input type="text" name="your_name" value="" maxlength="255" size="20" /></td>
</tr>
<tr>
<td>Your age:</td>
<td><input type="text" name="your_age" value="" maxlength="255" size="20" /></td>
</tr>
<tr>
<td>Your file:</td>
<td><input type="file" name="your_file" value="" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit_form" value="Submit" /></td>
</tr>
</table>
</form>
<?php } ?>
</body>
</html>
See the resources links below for details.
Sessions allow you to keep information and data accross several requests. When a browser requests a website for the first time, the session is started with a unique id. All subsequent requests will use the same id. This way, the server knows which requests belong together and can keep data for each request.
This unique id, the so called session id, is stored locally on the client's computer in a cookie or as a parameter in the URL. The data kept in the session is stored on the server, so the user doesn't know which data is stored, he just sees the session id.
To start the user's session use the function session_start. This will create a new session with a unique session id or recreate an existing one. You can access the session data through the associative array $_SESSION. This is a superglobal reserved variable and is available in all functions and methods. If you need the session id (e.g. to pass it in the URL), you can get it with the function session_id.
When will a session be destroyed? Either when the user stays inactive for a longer time (approximately 20 minutes, depends on server configuration), when the user closes the browser, or when you destroy it manually by using the function session_destroy.
Here is a short example for the usage of sessions with PHP. You can try this example here: Session_example.php. More information about session handling can be found on PHP's official website at http://www.php.net/manual/en/intro.session.php.
<?php
session_start();
if(isset($_SESSION["created_on"])){ //session data already set?
//read session data
echo "your session was created at {$_SESSION["created_on"]}";
//destroy session
session_destroy();
echo "<br>session has been destroyed";
}else{ //session data not set
$_SESSION["created_on"] = date("H:m:s");
echo "session started";
}
?>
<br><a href="Session_example.php">reload</a>
It is possible to get server information from the superglobal associative array $_SERVER. This array contains information like the server name, the client's ip address or the filename of the currently executing file. Here is a table with some important keys (a full list is available at http://www.php.net/manual/en/reserved.variables.server.php, altough the real values depend on the webserver's configuration):
| Key | Description |
| PHP_SELF | Filename of the currently executing script. E.g. http://www.youdomain.abc/content/my_script.php?param1=abc¶m2=def will return /content/my_script.php. |
| SERVER_NAME | The name of the server which hosts the currently executing script. E.g. http://www.youdomain.abc/content/my_script.php?param1=abc¶m2=def will return www.youdomain.abc. |
| REQUEST_METHOD | The type of the mothod: GET, POST, HEAD or PUT. |
| REQUEST_TIME | The Unix timestamp when the request was sent. |
| QUERY_STRING | The parameters passed with the URL. E.g. http://www.youdomain.abc/content/my_script.php?param1=abc¶m2=def will return in param1=abc¶m2=def. |
| DOCUMENT_ROOT | The folder which is set in the webserver's configuration as document root. E.g. C:/apache/htdocs on Windows or /var/www/html on Linux |
| HTTP_USER_AGENT | The exact identification of the client's user-agent (browser). E.g. Mozilla Firefox 3.0.4 (US english version) will return Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4 |
| REMOTE_ADDR | The client's ip address. Mostly used for logging or to prevent multiple votes or guestbook entries. |
You can see the real ouputs of these keys in this example: Server_information_example.php.
Working with strings in PHP is propably easier than in many other programming languages. Each programming language has characters to combine strings, this is called a string concatenator. In PHP the string concatentor is a point. See the sample below:
$variable1 = "ghi"; $variable2 = "def".$variable1; //$variable2 now contains "defghi" echo "abc".$variable2.$variable1; //prints "abcdefghighi"
This is the normal way which works in nearly any programming language. PHP just makes it a bit easier: you can use variables inside strings:
$variable1 = "ghi"; $variable2 = "def$variable1"; //$variable2 now contains "defghi" echo "abc$variable2$variable1"; //prints "abcdefghighi"
This is possible with arrays too, but then you need to enclose the variable with curly brackets:
$my_array = array("abc","def","ghi");
echo "1: {$my_array[0]}, 2: {$my_array[1]}, 3: {$my_array[2]}"; //prints "1: abc, 2: def, 3: ghi"
One important thing to keep in mind is the difference between single and double quotes. Here are the pros and cons of the different quote types:
Double quotes
You must escape any double quotes and dollar signs but you can use variables.
Single quotes
You must escape any single quotes and concatenate variables.
Here is another example to see the difference:
$var1 = 5000; //doesn't work because of not-escaped double quotes //will result in unexpected T_STRING error echo "The car "Super Car" costs $ $var1."; //prints: The car "Super Car" costs $ 5000. echo "The car \"Super Car\" costs \$ $var1."; //prints: The car "Super Car" costs $ $var1. echo 'The car "Super Car" costs $ $var1.'; //prints: The car "Super Car" costs $ 5000. echo 'The car "Super Car" costs $ '.$var1.'.';
There is one more thing you should know about strings in PHP: the heredoc syntax. This syntax allows you to assign large strings with line breaks to a variable. You can see how this syntax works in the example below (the characters EOT can be replaced by any other characters which follow the PHP variable naming rules):
$my_variable = <<<EOT This is a large string with many line breaks. It even can contain HTML tags like <br /> EOT;
For details about string concatenation, using variables inside strings and the heredoc syntax see the resources list below.
The control structure foreach allows you to quickly loop through an array. There are two ways to use it, where the second one is just a little but handy extension as it gives you the key as well:
foreach($array as $value){
//statement
}
foreach($array as $key=>$value){
//statement
}
Of course you can also use while or for or other loops for the same iteration, but foreach is easily written and good to read. Remember that it can be used on arrays only. For further information read the online documentation on PHP's official website at http://www.php.net/manual/en/control-structures.foreach.php. Here is a short example (see the result here: Foreach_example.php):
$my_array = array("blue"=>"#0000FF","red"=>"#FF0000","green"=>"#00FF00");
foreach($my_array as $key=>$value){
echo "The hexadecimal code for $key is $value.<br />";
}
The ternary operator ?: gives you the possibility to handle conditions in one line. This makes programming even faster because of less code. Be aware if you use are nesting ternary operations. You should use brackets then, but it's not recommended anyway as the readability will be worse. See http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary for more information. Example (test here: Ternary_operator_example.php):
<?php //prints whether the current second is even or odd echo time()%2 ? "odd" : "even"; ?>
Sometimes it is useful to suppress error messages which are produced by statements. For example if you connect to a MySQL database and the connection fails, you might want to print a user-friendly error message. In this case you suppress the error message which is generated by mysql_connect and print your own message. Example:
<?php
//Following line would print a warning that host "anyhostname" is unknown
//Using @ suppresses this warning
$con = @mysql_connect("anyhostname:567","anyusername","anypassword");
//Instead we print our own message
if(!$con){
echo "MySQL connection failed";
}else{
//continue working with MySQL database
}
?>
You can test this example here: Suppressing_errors_example.php. More about suppressing errors can be found here: http://www.php.net/manual/en/language.operators.errorcontrol.php
PHP, tips, tricks, advice, guides
If you have a question or a problem and you're looking for a solution, please use the forum. Comments might not be answered.