Reputation: 223
What's the differences between $_POST
and $_SESSION
? When should I use each of them? I've been searching on internet, but I still don't understand. Please give simple explanation and give an example. Thanks
Maybe, this link can help you to explain the difference
Upvotes: 1
Views: 15557
Reputation: 574
Sample usages
<?php
// Access the username field with $_POST
$username = $_POST['username'];
// Output the username value
echo $username;
// If GET uncomment this
// $username = $_GET['username'];
// echo $username;
// Or you can use $_REQUEST if you're in doubt about $_POST or $_GET
// $username = $_REQUEST['username'];
// echo $username;
?>
<form action="/" method="post"> <!-- You can change this as POST or GET -->
<input type="text" name="username" />
<input type="submit" value="Submit" />
</form>
By using $_POST
, the address will be
http://domain.com/login
By using $_GET
,
http://domain.com/login?username=somevalue
NOTE: $_GET
displays the submitted value while $_POST
don't
<?php
// You should call this first
session_start();
// Initialize the session value
$_SESSION['mysession'] = 'hello_world';
// Output the session value
echo $_SESSION['mysession'];
?>
Upvotes: 4
Reputation: 252
In a nutshell, $_POST is a special array that stores data received from an HTTP POST request to a particular webpage. When the script loads, the raw HTTP POST data string is parsed and added to the $_POST array, so that it's easier for developers to use for common tasks, like handling HTML form submissions.
Example:
Raw HTTP data string format:
key1=2&key2=3
$_POST array data format:
$_POST = array('key1' => '2', 'key2' => '3');
$_SESSION data is not dependent on a particular page or HTTP request; its data is persisted across pages and is typically used for things like keeping track of account data while a user is logged-in. $_SESSION data is often stored in files on the server (or in a distributed storage mechanism like Redis) until it is either manually cleared (e.g., session_destroy()), or until PHP's garbage collection runs and destroys it.
Upvotes: 2