Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP Variables from External Sources
PHP can receive data from external sources like HTML forms, cookies, and image submit buttons. This data is automatically populated into PHP's superglobal variables for easy access in your scripts.
HTML Form Elements
When a web page submits data through an HTML form, PHP automatically makes it available through $_POST, $_GET, and $_REQUEST variables. Here's a typical HTML form ?
<form action="testscript.php" method="POST">
<input type="text" name="name">
<input type="text" name="age">
<input type="submit" value="submit">
</form>
The PHP script can access the submitted data through the $_POST associative array ?
<?php echo "Name: " . $_POST["name"] . "<br>"; echo "Age: " . $_POST["age"]; ?>
Name: John Age: 25
Using method="GET" in the HTML form causes data to be sent via URL parameters and populates the $_GET array instead. The $_REQUEST array contains data from $_GET, $_POST, and $_COOKIE combined.
Image Button Coordinates
HTML allows using images as submit buttons with the image input type ?
<input type="image" src="submit-button.png" name="sub">
When a user clicks on the image, the x and y coordinates of the click location are sent along with the form data and can be accessed as $_POST['sub_x'] and $_POST['sub_y'].
Cookie Variables
PHP supports storing and retrieving cookies − small pieces of data stored on the client's browser. Cookies are set using the setcookie() function and read through the $_COOKIE array ?
<?php
if (isset($_COOKIE['name']) && isset($_COOKIE['age'])) {
echo "Name: " . $_COOKIE['name'] . " Age: " . $_COOKIE['age'];
}
setcookie('name', 'John');
setcookie('age', '25');
?>
When this script runs for the first time, it sets the cookies. On subsequent requests, the cookies are available in the $_COOKIE array ?
Name: John Age: 25
Conclusion
PHP's superglobal variables automatically capture external data from forms, cookies, and user interactions. Always validate and sanitize external data before using it to ensure security and prevent malicious input.
