Q:

How to pass values between the pages in PHP?

belongs to collection: PHP Miscellaneous

0

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.

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

PHP code with HTML:

<?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>

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'].

<?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>

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

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP Miscellaneous

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to redirect to another page in PHP?... >>
<< Setting Cookies in PHP...