PHP GET and POST Functions

PHP GET and POST are predefined global and associated array variables used for retrieving user submitted information passed using HTTP GET and HTTP POST methods. They are mostly used with PHP web form applications where you need to interact with your user input. This tutorial is a complete guide to using PHP GET and POST functions with illustrative examples and security considerations.

Understanding the $_POST

Let’s start with $_POST. Ideally you should use $_POST when:

  1. You need to pass the values submitted by a user in your web form to a server side script.
  2. You need the form submitted to be hidden and not to be shown in the URL (in the browser address bar).
  3. You are using the HTTP POST method when submitting the web form. The value passed by HTTP POST will appear in the headers.
  4. You need to submit a large amount of information (such as text) to the server for processing.

In their most basic form, PHP web forms take two elements. The first is the HTML web form asking for  user input. The second is the processing script that retrieves the posted values to the server. This is where you will be using $_POST to retrieve these values.

Basic code example:

This is the web form HTML code (basicpost.php):

<html>
<head>
<title>Basic Application for PHP $_POST</title>
</head>
<body>
<form action="processor.php" method="post">
Please enter your name: <input name="yourname" type="text" />
<input type="submit" name="submit" value="Submit your name">
</form>
</body>
</html>

The web form code above states that when the form is submitted, the processing of the web form posted values will be done by a script named “processor.php”. It also shows that the method of form submission is using the HTTP POST method. This is the code of processor.php:

<?php
//This is the script of processor.php

//retrieve name from the web form which is submitted using HTTP POST Method
$name= $_POST['yourname'];

//Output the name back to the browser
echo "Your name is $name.";

?>

By placing both files (basicpost.php and processor.php) in the same folder of your test server, you can actually run this form. First, it asks for your name. After typing your name and pressing the “Submit your name” button the value of the “yourname” textbox will be submitted to processor.php. Since webform.php is using HTTP POST, it should  be retrieved using $_POST variable, example:

$name= $_POST['yourname'];

Echo command will display it back to the browser (ie; “Your name is Codex M”). You might observe that after form submission, you will no longer see your name displayed in the URL.

IMPORTANT: DO NOT USE THE ABOVE SAMPLE CODE IN YOUR PHP APPLICATIONS. The purpose is just to show an entry/beginner level example on the use of $_POST in a web form. The primary reason is that the above script is NOT SECURE for practical use. Security when using these variables will be discussed later in this tutorial.

Why is $_POST a global variable? A global variable is one that you can use and re-use throughout your PHP script even inside a function. For example:

<?php
$x = 1;
function testing()
{
echo $x;
}
testing();
?>

In the above example, $x is NOT a global variable. When used inside function testing(), it won’t carry its value, which is 1. When the above code runs, it won’t output 1 to the browser. To make the above variable attain a global scope. You need to declare it as “global”:

<?php
$x = 1;
function testing()
{
//Define $x to be a global variable
global $x;
echo $x;
}
testing();
?>

The above code now outputs 1, because $x value can be used and re-used throughout the script, it’s now a global variable. $_POST is a global variable. There is no need to define $_POST as global. This makes it very convenient for programmers to retrieve the value $_POST anywhere in the script as needed. However since it’s global it also introduces a lot of security related issues. More of this will be discussed later.

Why is $_POST an associated array variable? If you are familiar with an array variable then you might know that to retrieve the value of the array, you should use square brackets such as:

<?php
//Define array and assign value to it
$this_is_an_array = array("Codex Meridian"=> "DevShed.com");

//Dump the values contained in the associative array

var_dump($this_is_an_array);

//Retrieved the associated pair value for Codex Meridian and output to browser

echo $this_is_an_array['Codex Meridian'];
?>

The browser output of this var_dump is:

array(1) {
["Codex Meridian"]=> string(11) "DevShed.com"
}

This means that “Codex Meridian” has a pair value of “DevShed.com”. Now when this is accessed using:

echo $this_is_an_array['Codex Meridian'];

The output is “DevShed.com” in the browser. Same thing with $_POST. Supposing you will dump the output of the above basic $_POST example:

<?php
$name= $_POST['yourname'];
//Dump the value of $_POST variable
var_dump($_POST);
?>

This is the output of the var_dump (supposing you will enter “John Doe” as name:

array(2) {
["yourname"]=>string(8) "John Doe"
["submit"]=>string(16) "Submit your name"
}

The above var_dump of $_POST shows that it is indeed an associative array variable.

{mospagebreak title=Understanding $_GET in PHP}

PHP $_GET works similarly to $_POST. It is used when:

  1. The web form is using HTTP GET Method.
  2. You need to pass the value in the query string variable of URL. This makes the submitted value visible to the users.
  3. You need to make the URL available for future use such as the ability to be bookmarked.
  4. You only need to pass a limited amount of characters. Since the value of $_GET gets appended in the URL as a value of the query string variable, the limitation depends on the URL limit which is around 2083 characters: http://support.microsoft.com/kb/208427.

Like $_POST, $_GET is also a predefined associated array variable with global scope.

Basic Example (basicget.php):

<html>
<head>
<body>
<title>Basic Application for PHP $_GET</title>
</head>
<form action="processor.php" method="get">
Please enter your favorite food: <input name="favoritefood" type="text" />
<input type="submit" name="submit" value="Submit this form">
</form>
</body>
</html>

The PHP script(form handler/processor):

<?php
//retrieve favorite food from the web form which is submitted using HTTP GET Method
$favoritefood= $_GET['favoritefood'];

//Output user favorite food back to the browser
echo $favoritefood;
?>

When the sample code is run, the passed value of the form will be appended in the URL:

http://localhost/processor.php?favoritefood=italian+pasta&submit=Submit+this+form

In the above URL, the query string variable is “favoritefood” with the submitted value  of “italian pasta” using the HTTP GET method.  You can re-use this URL by bookmarking because the submitted value is appended in the URL.

Warning: Do not use the above sample code for practical applications because it is not secure. See last section of this tutorial.

{mospagebreak title=Best PHP Practices and Security Considerations}

Below are some of the best practices for implementing $_POST and $_GET:

1.) Do not use $_GET when submitting sensitive information to the web server. This includes usernames and passwords. However sensitive information sent using $_POST is still not perfectly safe from eavesdropping if it travels in an unsecured channel. This is where you will need to use SSL (https) in sensitive pages such as login forms. This will encrypt the traffic sent using $_POST.

2.) For most web form applications that require users to submit text information. $_POST method is the most reliable method because it allows users to submit large amounts of information and will not complicate the resulting URL.

3.) Combine the web form and processing script as one PHP file, this is easier to maintain and efficient. In a basic example the web form (e.g. basicpost.php or basicget.php) and the processing script (processor.php) are separated. You can use the code below (e.g. you named it as “combined.php”):

<html>
<head>
<title>Combined form and processor using PHP $_POST</title>
</head>
<body>
<?php
if (!isset($_POST['yourname']))
{
//Web form is not submitted, show the HTML Form
?>
<form action="<?php echo $SERVER['PHP_SELF']; ?>" method="post">
Please enter your name: <input name="yourname" type="text" />
<input type="submit" name="submit" value="Submit this form">
</form>
<?php
}
else
{
//Form submitted
//Process the form, retrieve name from the web form which is submitted using HTTP POST Method
$name= $_POST['yourname'];
//Output the name back to the browser
echo "Your name is $name.";
}
?>
</body>
</html>

Warning: The above code does not contain any validation measures. Do not use it for practical applications.

4.) A more server-load efficient, user-friendly application is using AJAX, you can see a sample application here: http://www.php-developer.org/ajaxrecaptcha/

5.) Validate ALL external/user inputs when using $_GET or $_POST. This prevents your site from being hacked using cross site scripting, MySQL injection and other hacking methods. Read the next section.

Securing and Sanitizing $_POST / $_GET input

It is recommended that even if you are a beginner at using $_POST and $_GET, you need to put strong importance on security. Below is a sample code that sanitizes $_POST and $_GET input with the following assumptions:

  • You are only accepting plain text/string input.
  • You are inserting strings to a MySQL database.
  • You are not accepting HTML input and PHP input from your users.

<head>
<title>PHP Form template using sanitized $_POST</title>
</head>
<body>
<?php
if (!isset($_POST['yourname']))
{
?>
<form action="<?php echo $SERVER['PHP_SELF']; ?>" method="post">
Please enter your name: <input name="yourname" type="text" />
<input type="submit" name="submit" value="Submit this form">
</form>
<?php
}
else
{
//Form submitted
//Connect to MySQL database
include ‘databaseconnect.php’;

//Define the sanitize inputs function

function sanitizeinputs($input) {
//Retrieve values from HTTP POST and remove any possibility of user injecting HTML and PHP tags as input using strip tags function

$input= strip_tags(trim($input));

//Convert newline characters to <br /> to any possibility of cross site scripting using newline characters

$input = nl2br($input);

//Entity quote remaining dangerous characters

$input= htmlspecialchars($input);

//Sanitize in preparation to any database queries
$input = mysql_real_escape_string($input);
return $input;
}
$name= sanitizeinputs($_POST['yourname']);
echo "Your name is $name.";
}
?>
</body>
</html>

Notes:

1.) For $_GET, simply replace the above $_POST with $_GET and the validation is fairly similar. You might also need to check if the form originates from your own website and not from other malicious sites (preventing cross site request forgery). You can do this using a combination of nonce/token key as well as sessions. Supposing you need to check that the moderator is deleting a post that originates from your own site.

Source/Credits: Rob Miller http://php.robm.me.uk/

<?php

//Start PHP session
session_start();

//Check if post_id is not empty
if(!empty($_POST['post_id']) {

 //Post_id is not empty, check if the user is the moderator
 if( !user->is_a_moderator )

 //Not a moderator, end the script execution
 die;

 //Check if token is empty OR token is not equal to the correct token defined in the session variable. If the form originates from outside your site, it cannot obtain correct token.
 if( empty($_POST['token']) || $_POST['token'] != $_SESSION['token'])
 die;

// All validation is OK, proceed to delete the post.
delete_post(intval($_POST['post_id']));

// Unset the token, so that it cannot be used again.
unset($_SESSION['token']);
}

//Generate token
$token = md5(uniqid(rand(), true));
$_SESSION['token'] = $token;
?>
//Show web form pass token in hidden field
<form method="post">
<p>Post ID to delete:</p>
<p><input type="text" name="post_id" /></p>
<input type="hidden" name="token" value="<?php echo $token; ?>" />
</form>

2.) For $_GET retrieving id from the URL (very common), one way to sanitize against MySQL injection is using intval function:

<?php

$query_id= $_GET['id'];
$id=intval($query_id);

mysql_query(‘SELECT * FROM members WHERE id=’.$id);

?>

So a malicious input of 1 or 1=1 will become 1 only.

Final remarks: There is no general validation/sanitization code (one sanitizing function fits all). Each PHP web application is unique should have its own unique set of validation/sanitizing procedures. For example if a PHP variable is used to execute a command shell then it must be sanitized with escapeshellarg() function to make it safe if the variable value originates from a user-input.

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan