PHP for Beginners – Part 4

by  
Share:
PHP for Beginners

Hey Guys! This is the last second part of the tutorial series. In this part you will be learning how to use super global variables, submit forms and receive its values, storing session values and cookies. But before get going I suggest you get a basic knowledge of HTML, 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 2 and PHP for Beginners – Part 3.

We are going to look at superglobal variables. There is a difference between local variable, global variable and superglobal variable.

Local variable is a basic variable that access limit is just valid to the block that it is defined. These are used almost every time.

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.

<?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

function localTest() {
  // $k is a local variable to localTest function
  // and its visibility will be just for this function only
 $k = 123; 
}
?>

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

Let’s have a closer look at these superglobal variable.

$_SERVER

$_SERVER is an array that contains information related to servers such as paths, script location, headers etc.

<?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.

<?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 have only 2000 characters.

<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
<?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 to POST in the form field and paste the code at the top of the script.
<?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 -->
<form name=”simpleForm” action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>” method=”get”>

The predefined $_REQUEST variable contains the contents of $_GET, $_POST, and $_COOKIE. The $_REQUEST variable can be used to collect form data sent with both the GET and POST methods.

<?php
if (isset($_REQUEST["sub"])) {
	echo "My name is ". $_REQUEST["uname"] . " and password is ". $_REQUEST["pass"];
}
?>

Demonstration of all form field .
<!-- 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> &nbsp; 
    <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> &nbsp; 
        <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
<?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, administrator and the visitors (buys 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.

<!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.
<?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>&nbsp; <a href="logout.php">Logout</a>

To destroy or end the session just unset the session variable
<?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");
?>

This section is very crucial before moving on to the next tutorial. As you will be creating an assignment in the next tutorial but the basics will be based on this tutorial only.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.