Reputation: 8808
For some reason This php script won't echo my cookie variable:
<?php
require 'connection.php';
require 'variables.php';
$name = $_POST['name'];
$pass = $_POST['pass'];
if(($name == $admin_name) && ($pass == $admin_pass)){
setcookie($forum_url."name",$name,time()+604800);
setcookie($forum_url."pass",$pass,time()+604800);
}
else
echo 'Failed';
?>
heres the html that gets sent to admin_login.php
<form method=post action=admin_login.php>
<div id="formdiv">
<div class="fieldtext1">Name</div>
<div class="fieldtext1">Pass</div>
<input type="text" name=name size=25 />
<input type="password" name=pass size=25 />
</div>
<input type=submit value="Submit" id="submitbutton">
</form>
here is the index, where I want the info echoed
<?php echo $_COOKIE[$forum_url."name"]; ?>
What am I doing wrong?
Upvotes: 1
Views: 615
Reputation: 12472
Actually, I set up a quick test and found that when a cookie is stored it replaces periods with underscores. So if you have a domain like www.test.comname it becomes www_test_comname. So when referencing the cookie you would need to do something like this:
<?php
$forum_url = preg_replace('/\./','_',$forum_url);
echo $_COOKIE[$forum_url."name"];
?>
Is it possible that PHP is having a problem concatenating the $forum_url."name" and $forum_url."pass" in time for setcookie to work properly?
Try something like this:
<?php
require 'connection.php';
require 'variables.php';
$name = $_POST['name'];
$pass = $_POST['pass'];
$tmp_name_path = $forum_url."name";
$tmp_pass_path = $forum_url."pass"
if(($name == $admin_name) && ($pass == $admin_pass)){
setcookie($tmp_name_path,$name,time()+604800);
setcookie($tmp_pass_path,$pass,time()+604800);
}
else
echo 'Failed';
?>
Upvotes: 0
Reputation: 38252
Also check that the headers haven't already been sent when calling setcookie()
by asserting that headers_sent()
returns false
. Setting a cookie occurs within the HTTP header, so make sure you do so before any output is generated.
For instance:
<?php require 'connection.php'; require 'variables.php'; ?>
<h1>Hello world!</h1>
<?php setcookie($forum_url."name",$name,time()+604800); ?>
Will not work, because output has already been passed through to the HTTP body by the time setcookie()
is called.
Upvotes: 0
Reputation: 360672
Have you tried var_dump($_COOKIE)
at the point where you're trying to spit out a specific cookie value? Is it possible that $forum_url
hasn't been defined yet at the point where you're either setting the cookie, or trying to echo out its value? Perhaps the cookie's been set to name
and pass
because $forum_url
is blank.
Upvotes: 1
Reputation: 3707
Make sure you set the path for the cookie.
If you set cookie in the one path, but you are trying to get it from different path, it won't work.
Can you let me know the URL for the index and where you set cookie?
Upvotes: 0