PHP for Beginners – Part 4
Hey Folks ! In this part we will be learning how to use super global variables,submit forms and receive its values, storing session values and cookies. Before we get going I suggest you get a basic knowledge of HTML and forms from W3schools, as I will be concentrating on the PHP part rather than HTML.
Before we start building forms and play with data, let’s just have a sneak peek at the variables we are gonna use. I guess you guys already know about variables, data types, and creating functions which is discussed in the “PHP for Beginners – Part 3”. Now we are going to look at superglobal variables. Now there is a difference between normal variable or local variable, global variable and superglobal variable. Lets us first see global variable.
A global variable is like any variable that is declared at the top or top-level of the script and used within a function using global keyword.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php $t = 10; function test1(){ echo $t; // var_dump($t); } test1(); // prints nothing, variable is NULL function test2(){ global $t; echo ++$t; } test2(); // prints 11 $p = 20; function fun() { // this variable is different from the top variable $p echo ++$p; } echo $p; // returns 20 ?> |
Superglobal Variables are arrays that are built in with PHP. So you can access then anywhere within the scope of the script.
Have a look at the list of superglobal variable provided by the PHP.
Array | Desciption |
$_SERVER | Variables made available by the server |
$GLOBALS | Contains all global variables associated with the current script |
$_COOKIE | Contains keys and values set as browser cookies |
$_GET | Contains keys and values submitted to the script using the HTTP get method |
$_POST | Contains keys and values submitted to the script using the HTTP post method |
$_REQUEST | A combined array containing values from the $_GET, $_POST, and $_COOKIES superglobal arrays |
$_FILES | Contains information about uploaded files |
Now lets have a closer look at the superglobal variable.
$_SERVER
$_SERVER is an array that contains information related to servers such as paths, script location, headers etc.
1 2 3 4 5 6 7 8 9 10 |
<?php // most commonly used echo $_SERVER['HTTP_USER_AGENT']; // returns the browser information echo $_SERVER['PHP_SELF']; // returns the path of the executing script or page echo $_SERVER['REMOTE_ADDR'] // returns the ip address of the machine echo $_SERVER['SERVER_NAME'] // returns the server name echo $_SERVER['QUERY_STRING'] // retuns the query string for a URL // see all server related information provided PHP print_r($_SERVER); ?> |
$_COOKIE
A cookie is a small piece of information created at server side stored on the user’s browser, Each time the user visit a site/webpage it will send cookie too. Cookie can store a maximum of 4kb of information. Cookies are used where you want to identify the user visiting a website or remembering the password when submitting a form. It is less secure as you can check the values from the browser.
1 2 3 4 5 6 7 8 9 |
<?php // cookie set, will expires in 2 hours setcookie("club_name", "Manchester United" , time()+7200 ); echo $_COOKIE["club_name"]; // prints Manchester United // cookie unset setcookie("club_name", "Manchester United" , time()-7200 ); // prints all active cookies print_r( $_COOKIE); ?> |
$_GET, $_POST, $_REQUEST
How do we handle data when we submit form?
$_GET is used where the level of security on the variable is low as because information send via this method is visible to everyone. It’s mainly used in search forms or where information send to a page has less security priority. $_GET can only 2000 characters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<form name="simpleForm" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get"> <table> <tr> <td colspan="2" ><h1>Simple Form</h1></td> </tr> <tr> <td>First Name: </td> <td><input type="text" name="fname" value="" /></td> </tr> <tr> <td></td> <td><input type="submit" name="sub" value="Save" /></td> </tr> </table> </form> |
Here’s the PHP code to see your data when you submit the form
1 2 3 4 5 6 |
<?php // this block only executes if the form is submitted if (isset($_GET["sub"])) { echo "My name is ". $_GET["fname"]; } ?> |
$_POST basically do the same as $_GET, but it is more secured as because variable passed under this method is hidden. We use this method submitting highly sensitive data such as password, confidential files and data of similar concern. Just change the method tag to post in the form field and paste the code at the top of the script.
1 2 3 4 5 6 7 |
<?php if (isset($_POST["sub"])) { echo "My name is ". $_POST["uname"] . " and password is ". $_POST["pass"]; } ?> <!--just change the action of form tag to post --> |
1 2 3 4 5 |
<?php if (isset($_REQUEST["sub"])) { echo "My name is ". $_REQUEST["uname"] . " and password is ". $_REQUEST["pass"]; } ?> |
Demonstration of all form field .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
<!-- When uploading file remember to give enctype="multipart/form-data" else file will not be uploaded to the server --> <form name="simpleForm" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data"> <table> <tr> <td colspan="2" ><h1>Simple Form with everything in it</h1></td> </tr> <tr> <td>Name: </td> <td><input type="text" name="uname" value="" /></td> </tr> <tr> <td>Password: </td> <td><input type="password" name="pass" value="" /></td> </tr> <tr> <td>Sex: </td> <td><label><input type="radio" name="sex" value="M" checked /> M</label> <label><input type="radio" name="sex" value="F" /> F</label></td> </tr> <tr> <td>Fav color: </td> <td><label><input type="checkbox" name="fav_color[]" value="red" /> Red</label> <label><input type="checkbox" name="fav_color[]" value="blue" checked /> Blue</label> <label><input type="checkbox" name="fav_color[]" value="green" /> Green</label> <label><input type="checkbox" name="fav_color[]" value="pink" /> Pink</label> </td> </tr> <tr> <td>Nationality: </td> <td> <select name="nationality" > <option value="USA">USA</option> <option value="India" selected>India</option> <option value="Pakistan" >Pakistan</option> <option value="Nigeria" >Nigeria</option> <option value="South Africa" >South Africa</option> <option value="Sri Lanka" >Sri Lanka</option> <option value="West Indies" >West Indies</option> <option value="England" >England</option> </select> </td> </tr> <tr> <td>Fav Clubs: </td> <td> <select name="clubs[]" multiple size="4"> <option value="Real Madrid">Real Madrid</option> <option value="Manchester United">Manchester United</option> <option value="Barcelona" >Barcelona</option> <option value="AC Milan">AC Milan</option> <option value="Bayern Munich">Bayern Munich</option> <option value="Arsenal">Arsenal</option> <option value="Liverpool">Liverpool</option> <option value="Chelsea">Chelsea</option> <option value="Inter Milan">Inter Milan</option> </select> </td> </tr> <tr> <td>Attachment: </td> <td><input type="file" name="photo" /></td> </tr> <tr> <td></td> <td><input type="submit" name="sub" value="Save" /></td> </tr> </table> </form> |
The PHP script that will be executed when the form is submitted
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<?php if (isset($_REQUEST["sub"])) { // uncomment to see all post data //print_r($_POST); $name = $_POST["uname"]; $password = $_POST["pass"]; $sex = $_POST["sex"]; $fav_color = $_POST["fav_color"]; $nationality = $_POST["nationality"]; $clubs = $_POST["clubs"]; if(count($fav_color) > 0 ) { // we have some color selected $fav_color = implode(", ", $fav_color); } if(count($clubs) > 0 ) { // we have some clubs selected $clubs = implode(", ", $clubs); } echo "<h1>Your form is submitted</h1>"; echo "<h3>Name: $name</h3>"; echo "<h3>Password: $password</h3>"; echo "<h3>Sex: $sex</h3>"; echo "<h3>nationality: $nationality</h3>"; echo "<h3>Fav Color: ". $fav_color ."</h3>"; echo "<h3>Clubs: ". $clubs ."</h3>"; // uploading a file to server // un comment to see all file uploaded // print_r($_FILES); if ( is_uploaded_file($_FILES["photo"]["tmp_name"])) { //$fileName = $_FILES["photo"]["name"]; // set an unique name every time the file gets uploaded //$folderName = 'upload/'; // if you wat to upload in the folder $fileName = $folderName . time().'_'.$_FILES["photo"]["name"]; move_uploaded_file($_FILES["photo"]["tmp_name"], $fileName); } // similarly you can use copy function too //but use only one between move_uploaded_file and copy /* if ( is_uploaded_file($_FILES["photo"]["tmp_name"])) { copy($_FILES["photo"]["tmp_name"], $_FILES["photo"]["name"]); } */ die; } ?> |
$_SESSION
Suppose you have a web store where there are access for two types of users, one the administrator and the visitors and buys your products. So how do you verify the identity of the current user. To solve this issue we use session. Its a super global variable as we have read just before but the main ability of $_SESSION is that stores a state of the user. Every time a visitor logs in it will maintain a separate state for the user. Just treat session as another superglobal variable, the main thing you have to remember is to start the session every time you want to use session. Have a look at the snippet below. Add value to the session variable just like adding value to a normal variable. Look at a sample snippet below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<!DOCTYPE htm> <html> <head> <title>Session Test</title> </head> <body> <h1>Set your user type</h1> <form method="post" action="2.php" name="sess"> <label>Enter your Name <input type="text" name="uname" /></label> <label> Choose type: <select name="userType"> <option value="admin">Admin</option> <option value="buyer">Buyer</option> </select> </label> <input type="submit" name="sub" value="Set" /> </form> <br> <a href="show_value.php">Show session value</a> </body> </html> |
See your value after your submit form, At the same type run the script with different browser, and login as different user.
1 2 3 4 5 6 7 8 9 10 |
<?php session_start(); if (isset($_REQUEST["sub"])) { $_SESSION["user"] = $_POST["uname"]; $_SESSION["user_type"] = $_POST["userType"]; } echo "<h1>User Name: ". $_SESSION["user"] . "</h1>"; echo "<h1>User Type: ". $_SESSION["user_type"] . "</h1>"; ?> <a href="index.php">Back to Home Page</a> <a href="logout.php">Logout</a> |
To destroy or end the session just unset the session variable
1 2 3 4 5 6 7 8 |
<?php session_start(); unset($_SESSION["user"]); unset($_SESSION["user_type"]); session_destroy(); // after we destroy the variable, redirect it back to the login page header("location: index.php"); ?> |
and Thats all.. Hope you guys enjoyed the post. 🙂