PHP Superglobals Variables
-
Some predefined variables in PHP are "superglobals", which means
that they are always accessible, regardless of scope -
and you can access them from any function, class or file without having to do anything special.
The PHP superglobal variables are:
1-PHP $GLOBALS
-
$GLOBALS is a PHP super global variable which is used to access
global variables from anywhere in the PHP script (also from within
functions or methods).
PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.
example :$x = 75; $y = 25; function addition() { $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; } addition(); echo $z;
2-PHP $_SERVER
-
$_SERVER is a PHP super global variable which holds information
about headers, paths, and script locations.
example :echo $_SERVER['PHP_SELF']; echo $_SERVER['SERVER_NAME']; echo $_SERVER['HTTP_HOST']; echo $_SERVER['HTTP_REFERER']; echo $_SERVER['HTTP_USER_AGENT']; echo $_SERVER['SCRIPT_NAME']; echo $_SERVER['REQUEST_METHOD'];
3-PHP $_REQUEST
-
PHP $_REQUEST is a PHP super global variable which is used to
collect data after submitting an HTML form.
example :
4-PHP $_POST
-
PHP $_POST is a PHP super global variable which is used to collect
form data after submitting an HTML form with method="post". $_POST
is also widely used to pass variables.
example :
5-PHP $_GET
-
PHP $_GET is a PHP super global variable which is used to collect
form data after submitting an HTML form with method="get". $_GET
can also collect data sent in the URL. Assume we have an HTML page
that contains a hyperlink with parameters:
Test $GET When a user clicks on the link "Test $GET", the parameters "subject" and "web" are sent to "test_get.php", and you can then access their values in "test_get.php" with $_GET.
example :
PHP Forms
- When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.
-
To display the submitted data you could simply echo all the
variables
Welcome output // Welcome John Your email address is john.doe@example.com - The same result could also be achieved using the HTTP GET method
| GET | POST |
|---|---|
|
Information sent from a form with the GET method is visible to
everyone (all variable names and values are displayed in the
URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. GET may be used for sending non-sensitive data. Note: GET should NEVER be used for sending passwords or other sensitive information! |
Information sent from a form with the POST method is invisible
to others (all names/values are embedded within the body of
the HTTP request) and has no limits on the amount of
information to send. Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server. However, because the variables are not displayed in the URL, it is not possible to bookmark the page. |
PHP Form Validation
$_SERVER["PHP_SELF"]
- The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the currently executing script.
- the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of jumping to a different page. This way, the user will get error messages on the same page as the form.
-
$_SERVER["PHP_SELF"] exploits can be avoided by using the
htmlspecialchars() function.
example :
- Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP trim() function)
- Remove backslashes (\) from the user input data (with the PHP stripslashes() function)
- The next step is to create a function that will do all the checking for us
-
We will name the function test_input()
// define variables and set to empty values $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = test_input($_POST["name"]); $email = test_input($_POST["email"]); $website = test_input($_POST["website"]); $comment = test_input($_POST["comment"]); $gender = test_input($_POST["gender"]); } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; }
PHP Forms - Required Fields
- we have added some new variables: $nameErr, $emailErr, $genderErr, and $websiteErr. These error variables will hold error messages for the required fields.
- We have also added an if else statement for each $_POST variable. This checks if the $_POST variable is empty (with the PHP empty() function).
- If it is empty, an error message is stored in the different error variables, and if it is not empty.
-
it sends the user input data through the test_input() function
// define variables and set to empty values $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = test_input($_POST["name"]); } if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = test_input($_POST["email"]); } if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); } if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderErr = "Gender is required"; } else { $gender = test_input($_POST["gender"]); } }
PHP - Validate Name
-
to validate name :
$name = test_input($_POST["name"]); if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; }
PHP - Validate E-mail
-
to validate E-mail :
$email = test_input($_POST["email"]); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; }
PHP - Validate URL
-
to validate URL :
$website = test_input($_POST["website"]); if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "Invalid URL"; }
PHP Filters
Why Use Filters?- PHP filters are used to validate and sanitize external input.
-
Many web applications receive external input. External input/data
can be :
- User input from a form
- Cookies
- Web services data
- Server variables
- Database query results
PHP filter_var() Function
- The filter_var() function both validate and sanitize data.
-
The filter_var() function filters a single variable with a
specified filter. It takes two pieces of data :
- The variable you want to check
- The type of check to use
Sanitize a String
-
the filter_var() function uses to remove all HTML tags from a
string
$str = " Hello World!
"; $newstr = filter_var($str, FILTER_SANITIZE_STRING); echo $newstr;
Validate an Integer
- the filter_var() function to check if the variable $int is an integer
- f $int is an integer, the output of the code below will be: "Integer is valid".
-
If $int is not an integer, the output will be: "Integer is not
valid"
$int = 100; if (!filter_var($int, FILTER_VALIDATE_INT) === false) { echo("Integer is valid"); } else { echo("Integer is not valid"); }
Problem With zero
-
if $int was set to 0, the function above will return "Integer is
not valid". To solve this problem
$int = 0; if (filter_var($int, FILTER_VALIDATE_INT) === 0 || !filter_var($int, FILTER_VALIDATE_INT) === false) { echo("Integer is valid"); } else { echo("Integer is not valid"); }
Validate an IP Address
-
the filter_var() function to check if the variable $ip is a valid
IP address
$ip = "127.0.0.1"; if (!filter_var($ip, FILTER_VALIDATE_IP) === false) { echo("$ip is a valid IP address"); } else { echo("$ip is not a valid IP address"); }
Sanitize and Validate an Email Address
-
the filter_var() function uses to first remove all illegal
characters from the $email variable, then check if it is a valid
email address
$email = "john.doe@example.com"; // Remove all illegal characters from email $email = filter_var($email, FILTER_SANITIZE_EMAIL); // Validate e-mail if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) { echo("$email is a valid email address"); } else { echo("$email is not a valid email address"); }
Sanitize and Validate a URL
-
the filter_var() function uses to first remove all illegal
characters from a URL, then check if $url is a valid URL
$url = "https://www.facebook.com/MasterC0de"; // Remove all illegal characters from a url $url = filter_var($url, FILTER_SANITIZE_URL); // Validate url if (!filter_var($url, FILTER_VALIDATE_URL) === false) { echo("$url is a valid URL"); } else { echo("$url is not a valid URL"); }
PHP File Handling
-
File handling is an important part of any web application. You
often need to open and process a file for different tasks.
Function Description Example readfile() The readfile() function reads a file and writes it to the output buffer. echo readfile("webdictionary.txt");fopen() The first parameter of fopen() contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened. $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); echo fread($myfile,filesize("webdictionary.txt")); fclose($myfile);fread() The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read. fread($myfile,filesize("webdictionary.txt"));fclose() The fclose() requires the name of the file (or a variable that holds the filename) we want to close $myfile = fopen("webdictionary.txt", "r"); // some code to be executed.... fclose($myfile);fgets() The fgets() function is used to read a single line from a file. $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); echo fgets($myfile); fclose($myfile);feof() The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); // Output one line until end-of-file while(!feof($myfile)) { echo fgets($myfile) ; } fclose($myfile);fgetc() The fgetc() function is used to read a single character from a file. $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); // Output one character until end-of-file while(!feof($myfile)) { echo fgetc($myfile); } fclose($myfile);fopen() The fopen() function is also used to create a file.
If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).$myfile = fopen("testfile.txt", "w")fwrite() The fwrite() function is used to write to a file.
The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.$myfile = fopen("newfile.txt", "w") or die("Unable to open file!"); $txt = "John Doe\n"; fwrite($myfile, $txt); $txt = "Jane Doe\n"; fwrite($myfile, $txt); fclose($myfile);
PHP File Upload
- Configure The "php.ini" File
-
In your "php.ini" file, search for the file_uploads directive, and
set it to On
file_uploads = On
Create The HTML Form
- Make sure that the form uses method="post"
- The form also needs the following attribute: enctype="multipart/form-data". It specifies which content-type to use when submitting the form
- The form above sends data to a file called "upload.php"
-
The type="file" attribute of the "input" tag shows the input field
as a file-select control, with a "Browse" button next to the input
control
Create The Upload File
- The "upload.php" file contains the code for uploading a file
- $target_dir = "uploads/" - specifies the directory where the file is going to be placed
- $target_file specifies the path of the file to be uploaded
- $imageFileType holds the file extension of the file (in lower case)
- check if the image file is an actual image or a fake image
- You will need to create a new directory called "uploads" in the directory where "upload.php" file resides. The uploaded files will be saved there.
-
$target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } }
Check if File Already Exists
-
we will check if the file already exists in the "uploads" folder.
If it does, an error message is displayed
// Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; }
Limit File Size
-
we want to check the size of the file. If the file is larger than
500KB, an error message is displayed
// Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; }
Limit File Type
-
only allows users to upload JPG, JPEG, PNG, and GIF files. All
other file types gives an error message
// Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; }
Complete Upload File PHP Script
-
The complete "upload.php" file now looks like this
$target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } }
PHP Sessions
- Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.
Start a PHP Session
- A session is started with the session_start() function.
- Session variables are set with the PHP global variable: $_SESSION.
- The session_start() function must be the very first thing in your document. Before any HTML tags.
Get PHP Session Variable Values
- Session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page (session_start()).
- All session variable values are stored in the global $_SESSION variable
Modify a PHP Session Variable
- To change a session variable, just overwrite it
Destroy a PHP Session
- To remove all global session variables and destroy the session, use session_unset() and session_destroy()