bluzazkapturem bluzazkapturem - 20 days ago 8
PHP Question

How can i remember data given by user

I want to write a code which would be remember name given by user and on next visit will welcome him with this given name. I don't really understand cookies and session yet so I would be thankful for any help. I wrote something like this:

File: 1.php

<?php
session_start();
?>
<html>
<form action="2.php" method="post">
Name:<input type="text" name="name"/></br>
<input type="submit" value="send"/>
</form>
</html>
<?php
$name=$_POST['name'];
setcookie('name',$name,time()+3600*24);
$_SESSION['name']=$name;
?>


File: 2.php

//2.php
<?php
session_start();
if(isset($_COOKIE['name']))
echo "Hello".$_SESSION['name'];
else
echo "Cookie doesnt exist";
?>

Answer

In the example below, 1.php is just used for submitting to 2.php so no PHP code is being used.

1.php

<html>
<form action="2.php" method="post">
 Name:<input type="text" name="name"/><br>
 <input type="submit" name="submit" value="send"/>
</form>
</html>

I've shown both instances of this below on how to set a cookie and session. You can refresh just 2.php and the cookie output should still show the value of $_COOKIE['name'].

2.php

 <?php

session_start();


if (isset($_POST['name'])) {

    $_SESSION['username'] = $_POST['name'];

    setcookie('name',$_SESSION['username'],time()+3600*24);

}


//Session Value will show in first instance
echo "Session Name: " . $_SESSION['username'] . "<br>";


//Cookie Value will not how until you refresh page
echo "Cookie Name: "  . $_COOKIE['name'] . "<br>";


?>

Edit: Variables will not be overwritten when the page is refreshed.