A PHP variable is a symbol or name that’s equivalent to value. It is being used to store values such as values, numbers, characters or memory addresses so they can be utilized in any part of the program. A simple variable can be used in any part of the program, but it’s not accessible outside of it unless, it’s being passed using a
POST through HTML form,
Using GET and POST through HTML Form
HTML form is one of the most powerful features of PHP. Any form element will automatically be available to the
action destination of the form.
<form action="nextPage.php" method="POST"> <input type="text" name="email"> <input type="text" name="username"> <input type="submit" name="submit"> </form>
Fetching data to
$username = isset($_POST['username']) ? $_POST['username'] : ""; $email = isset($_POST['email']) ? $_POST['email'] : ""; echo "Username: ".$username; echo "Email: ".$email;
The sample output of the script may be:
Username: johndoe Email: firstname.lastname@example.org
The example above shows how to pass a variable using
POST through an HTML form. The form element needs to have the
method attribute. The
action contains the next page, in this case, it’s
nextPage.php. The method can be a
GET. You can then access the elements in the
nextPage.php using a
<?php $phpVariable = "Dog"; ?> <a href="nextPage.php?data=<?=$phpVariable?>">Bring me to nextPage</a>
This example will create a
GET variable and can be accessed on
echo $phpVariable = $_GET['phpVariable']; //output: Dog
The GET can be accessed using
Another way is to add a hidden element in an HTML form that submits to the next page.
<form action="nextPage.php" method="POST"> <input type="hidden" name="phpVariable" value="Dog"> <input type="submit" name="submit"> </form>
//Using POST $phpVariable = $_POST['phpVariable']; //Using GET $phpVariable = $_GET['phpVariable']; //Using GET, POST or COOKIE; $phpVariable = $_REQUEST['phpVariable'];
You can change the method from
GET to use the
GET are bot insecure, but
GETis easier to hack since it’s available through the front-end.
$_REQUEST can both accept
COOKIE. It’s good to use
$_REQUEST on self-referential forms for validations.
cookie are easier to use, but the
session is far more secure than the cookies, but not completely secure.
//page 1 $phpVariable = "Dog"; $_SESSION['animal'] = $phpVariable; //page 2 $value = $_SESSION['animal'];
Note: When using the
session, always remember to add
session_start() on both pages before accessing the
//page 1 $phpVariable = "Dog"; $_COOKIE['animal'] = $phpVariable; //page 2 $value = $_COOKIE['animal'];
The most obvious difference between
session is that that
session will be stored on the server-side while the
cookies will have the client side as the storage.