How to pass values between the pages in PHP?

Learn: How to pass any value between pages in PHP? Here, is a tutorial about passing values from one page to another using PHP. By Abhishek Pathak Last updated : December 17, 2023

PHP is one of the most popular languages when it comes to Back-end. Even the CMS giant WordPress uses PHP at its core, so there's nothing more to add how important the language is.

Passing values between the pages

However, often new developers find it difficult to pass variables along the subsequent pages. They might even go for local Storage to make this work, but all of these hacks are not required when you can do this easily with session management.

The session is an activity period where visitor's data is stored and passed to following pages. We tell the PHP interpreter to start a session by defining session_start() at the beginning of every PHP file we want session to happen. Then we access the session variables using the $_SESSION['variable-name'] method which is a PHP Superglobal variable.

Example 1: PHP code to pass values between the pages

<?php session_start();
      //Put session start at the beginning of the file
?>

<!DOCTYPE html>
<html>
<head>
    <title>Session Example</title>
</head>
<body>

<?php if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $_SESSION['name'] = $_POST['name'];
        
        if($_SESSION['name']) {
            header('location: printName.php');
        }
    }
?>

    <form action="session.php" method="POST">
        <input type="text" name="Name">
        <input type="submit" value="submit">  
    </form>   


</body>
</html>

Explanation

In this example, we are taking a text input in the form of name and storing it in the name session variable. Note, this is the how the session variables are defined, $_SESSION['name']

Next, note that we have included session_start() at the beginning of each PHP file. This will ensure that we can safely access the variable defined in other page, by just using $_SESSION['name'].

Example 2: PHP code to pass values between the pages

<?php session_start();
      //Put session start at the beginning of the file
?>

<!DOCTYPE html>
<html>
<head>
    <title>Print Name</title>
</head>
<body>

<p>Your Name is: <?php echo $_SESSION['name']; ?></p>   


</body>
</html>

Explanation

In printName.php file, echoing the session name variable prints the name we have inputted from user in another page.

In the above example, we used the following PHP topics:

So, this is how you pass variables and values from one page to another in PHP. Share this with your friends/fellow learners so they don't have to struggle.

More PHP Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.