Passing multiple variables to another page in url
There are several ways to pass variables from one PHP page to another:
- Using the
$_GET
superglobal array:
<?php
$name = 'John';
$age = 30;
// Pass variables in the URL
echo "<a href='page2.php?name=$name&age=$age'>Go to page 2</a>";
On page 2, you can access the variables like this:
<?php
$name = $_GET['name'];
$age = $_GET['age'];
Watch a video course
Learn object oriented PHP
- Using the $_POST superglobal array:
<?php
$name = 'John';
$age = 30;
// Use a form to pass variables to page2.php
echo "<form method='post' action='page2.php'>
<input type='hidden' name='name' value='$name'>
<input type='hidden' name='age' value='$age'>
<input type='submit' value='Go to page 2'>
</form>";
On page 2, you can access the variables like this:
<?php
$name = $_POST['name'];
$age = $_POST['age'];
- Using a session:
<?php
// Start the session on page 1
session_start();
$name = 'John';
$age = 30;
// Store variables in the session
$_SESSION['name'] = $name;
$_SESSION['age'] = $age;
// Redirect to page 2
header('Location: page2.php');
On page 2, you can access the variables like this:
<?php
// Start the session on page 2
session_start();
$name = $_SESSION['name'];
$age = $_SESSION['age'];