PHP Variables from External Sources

PHPServer Side ProgrammingProgramming


PHP's variable namespace is populated by external sources such as HTML form elements, cookies and screen coordinates of image submit button

HTML form elements

When a web page submits data in its HTML form to a PHP script, it is automatically made available to the script in the form of $_POST, $_GET and $_REQUEST variables. Following is a typical HTML form

<form action="testscript.php" method="POST">
   <input type="text" name="name">
   <input type="text" name="age">
   <input type ="submit" valaue="submit">

Data entered by user is populated as $_POST associative array in PHP script

echo "Name : " . $_POST["name"] . "<br>";
echo "Age : " . $_POST["age"];

Place HTML page in document root along with testscript.php. Open it in browser and enter data

Name : xyz
Age : 20

Using method='GET' in HTML form causes URL in action attribute to be requested using HTTP GET method. Data in the form is populated in $_GET array. The $_REQUEST array provides contents of $_GET, $_POST and $_COOKIE predefined variables. For example, data in form element named 'age' will be available as $_GET['age'] and $_REQUEST['age']

Imaage button coordinates

In standard submit button, HTML allows any image to be used as button with image input type

<input type="image" src="image.gif" name="sub" />

In this case, when user clicks on the image x and y coordinates of screen dimensions are also sent as request and can be accessed as $_POST['sub_x'] and $_POST['sub_y']

Cookie variables

PHP supports mechanism of storage and retrieval of cookies. Cookie is a data stored by the server in client's computer while sending response. Every subsequent request by the client sends back the cookies along with requested parameters such as HTML form elements. PHP uses Setcookie() function to store cookie. Cookies are read in $_COOKIE array. Following is a simple example


if (isset($_COOKIE['name']) && isset($_COOKIE['age'])) {
   echo "Name:" .$_COOKIE['name'] . " age:" .$_COOKIE['age'];
setcookie('name', 'XYZ');
setcookie('age', 20);

When above script is called from browser for first time, cookies name and age are set. Subsequently, they are transmitted to the server in $_COOKIE array and they are displayed as under


Name:XYZ age:20
Published on 19-Sep-2020 18:35:20