Rubenxfd
Rubenxfd

Reputation: 464

PHP Cookie not working on redirect

I have rather frustration problem. I am trying to store a form variable into a cookie.

<form id = "vraagStellen" action = "shoutbox.php" method = "post" class = "col-lg-4 col-md-6 col-sm-12" role="form">
    <a name = "bottomOfPage"></a>
    <div class = "selectAfbeelding form-group">
        <label for "gamertag">Gamertag:</label>
        <input type = "text" id = "gamertag" name = "gamertag" class = "form-control" maxlength="30" value="<?php if(isset($_COOKIE['gamertag'])){echo $_COOKIE['gamertag'];} else {echo "";} ?>" placeholder="<?php if(isset($_COOKIE['gamertag'])){echo $_COOKIE['gamertag'];} else {echo "Hier typen";} ?>" required>
    </div>
    <div class = "selectVraag form-group">
        <label for "bericht">Bericht:</label>
        <textarea id = "bericht" onkeyup = "count()" name = "bericht" class = "form-control" maxlength="100" cols = "40" rows = "2" placeholder = "Hier typen" required></textarea>
        <div id = "countDiv"></div>
    </div>
    <div class = "form-group">
        <input type="submit" name = "verzend" value = "Verzenden" id = "verzenden">
        <input type="reset" name = "reset" value = "Leegmaken" id = "reset"> 
    </div>
</form> 

And php:

if (isset($_POST['gamertag']) && isset($_POST['bericht']) && !empty($_POST['gamertag']) && !empty($_POST['bericht'])){

$afbeelding_before = $_POST['gamertag'];
$vraag_before = $_POST['bericht'];

$cookie_var = $_POST['gamertag'];

$afbeelding = mysql_real_escape_string($afbeelding_before);
$vraag = mysql_real_escape_string($vraag_before);

setcookie("gamertag", $cookie_var, time() + (86400 * 30), "/",$_SERVER['SERVER_NAME']);

//echo $afbeelding . $vraag;

$sql3="INSERT INTO `shoutbox` (`id`, `gamertag`, `bericht`, `date`) VALUES (NULL, '$afbeelding', '$vraag', CURRENT_TIMESTAMP)";
mysql_query($sql3,$con);

echo "post gamertag ".$_POST['gamertag']."<BR>";
echo "cookie ". $_COOKIE['gamertag']."<BR>";

header('Location: http://link.nl#shoutbox');

}

else{
    echo 'Er ging iets fout...';
}

The cookie is not displaying in the form input called "gamertag" when redirected from the PHP code. But when I erase the #shoutbox from the link, it will display the cookie correctly. Navigating through different pages isn't a problem eighter. Only when redirecting from the PHP code it is not displayed.

I hope someone can help me!

Thanks!

Upvotes: 2

Views: 319

Answers (2)

maverabil
maverabil

Reputation: 103

Maybe you using invalid session id or PHPSESSID. Could you check PHPSESSID?

Upvotes: 1

Marol
Marol

Reputation: 36

Make sure that value in $_SERVER['SERVER_NAME'] is exactly link.nl and not www.link.nl. For browsers these are two different values so they create two different cookies.

Upvotes: 2

Related Questions