Search code examples
phphttp-redirectcookiessetcookie

I want to change a cookies value when heading to another page?


In PHP i will set the cookie and give it a value that's a variable, when the user enters their name they will be taken to another page but when they get to that new page i need the value of that cookie changed to what name they entered, could someone show me how this would be done please?


Solution

  • in the first page (index.php) for example

    <?php
    //check if the form is submitted
    if($_POST['update_name']){
        if(!empty($_POST['name'])){
            //name filed is filled
    
            //define cookie expire time
            $expire = time()+60*60*24*30; #cookie will expire after a month
            //set the cookie
            setcookie("name", $_POST['name'], $expire);
            //take the user to another page
            header("location: page_two.php");
        }else{
        //form was submitted with empty name field
        //show error message
        echo "Name is required";
        }
    }
    ?>
    <form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
    <input type="text" name="name" />
    <input type="submit" name="update_name" value="Submit" />
    </form>
    

    in page_two.php

    <?php
    echo $_COOKIE["name"];
    ?>