Jump to content

Cookies and PHP.


dh526

Recommended Posts

Right, this is my second message on here because I'm a beginner to php. It is very interesting though and last time people were VERY helpful :)

 

This might be a very basic question but I'm not sure quite where I'm going wrong even though I kind of know it will be something silly I am doing wrong :S

 

This question relates to cookies...

 

I know how to set a cookie, with

setcookie('username', $username)

 

however I do not know how to set $username to be a value that is input by the user into a form. I am creating a login system for a website and this will make everything else fall into place (i hope) so any help would be much appreciated:)

 

 

So i want to do something like this:

 

User enters name into a text field in a form called 'username'

 

the value of 'username' is stored in the cookie.

 

then in another page this can be accessed and printed

 

 

Thank you so so much for your help :)

Link to comment
https://forums.phpfreaks.com/topic/158827-cookies-and-php/
Share on other sites

Thank you :) Still not 100% done though...

 

I have login.html

 


<html>
<head>
</head>
<body>


Please login
<br>



<form method="post" action="login1.php">

username:<input type="text" name= "username"/>


<br>

<input type="submit" />
</form>






</body>

</html>

 

and login1.php

 

<html>
<head>
</head>

<body>

<?


$username = $_POST ['username'];
setcookie('username', $username);
echo "<a href="login2.php">LINK</a>"; 

?>


</body>
</html>

 

and then i want to show the username in another page, called login2.php

 


<?

echo $_COOKIE['username'];


?>

 

again, I don't know why this isn't working :S

 

Sorry, I feel such a plonker while doing this sometimes ...

 

 

Link to comment
https://forums.phpfreaks.com/topic/158827-cookies-and-php/#findComment-837704
Share on other sites

login1.php

 

<?php
$username = $_POST ['username'];
setcookie('username', $username);
?>
<html>
<head>
</head>
<body>
<?php
echo "<a href="login2.php">LINK</a>"; 
?>
</body>
</html>

 

HTTP headers must be sent BEFORE any HTML (body of the response). And a cookie is a header. I moved your setcookie up in the code. You can also use ob_start output buffering to get around this restriction. http://us3.php.net/manual/en/function.ob-start.php . And you could instead store the value $_SESSION and it would be available in login2.php.

 

CR

Link to comment
https://forums.phpfreaks.com/topic/158827-cookies-and-php/#findComment-837775
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.