2

I am currently trying to have one set cookie and the value of the cookie gets overwritten by PHP effectively when a user logs in, but it just creates a separate cookie, here is a snippet of code which am setting the cookie value

    <?php
include("db_connect.php");

$input_game = $_POST['game'];
$input_user = $_POST['email'];

$sql = "UPDATE users_table SET Pref_Game = '" . $input_game . "' WHERE Email='" . $input_user . "'";
if ($conn->query($sql) === TRUE) {
$cookie_name2 = "content";

$sql="SELECT Pref_Game FROM users_table WHERE Email='$input_user'";
$result = $conn->query($sql);
$row = $result->fetch_object();
setcookie($cookie_name2,$row->Pref_Game, time() + (86400 * 30), "/"); // 86400 = 1 day
} else {
    //Error
}
?>

Below is the JQuery cookie code just for clarity:

$("#test-cookie").click(function() {
    $.cookie('content', 'test');
    location.reload();
});

Is there anyway that PHP can update/overwrite the cookie value created by JQuery?

Studento919
  • 625
  • 2
  • 15
  • 44
  • 1
    PHP will overwrite jQuery's cookie if it has the exact same name, path, and domain. What path has the jQuery cookie been written for? Look at it in your browsers development console. If it was within a directory when set, you may need to use an expression like `$.cookie('name', 'value', { expires: 7, path: '/' });` to set it for `/` as the PHP cookie has done. https://github.com/carhartl/jquery-cookie – Michael Berkowski Apr 29 '15 at 16:43
  • 1
    It's important and so I must point out that this code is vulnerable to SQL injection in its current form, where `$input_user, $input_game` are passed into the query. This would benefit from using `prepare()/bind_param()/execute()`. See [How can I prevent SQL injection in PHP](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) for examples. – Michael Berkowski Apr 29 '15 at 16:46
  • @MichaelBerkowski Just a reminder that the latest version can be found in the new repo URL: https://github.com/js-cookie/js-cookie/tree/v1.5.1 – Fagner Brack May 02 '15 at 05:23

1 Answers1

1

PHP will overwrite jQuery's cookie if it has the exact same name, path, and domain. What path has the jQuery cookie been written for? Look at it in your browsers development console. If it was within a directory when set, you may need to use an expression like $.cookie('name', 'value', { expires: 7, path: '/' }); to set it for / as the PHP cookie has done.

This answered my Question thank you:

    $("#test-cookie").click(function() {
    $.cookie('content', 'test', { expires: 7, path: '/' });
    location.reload();
});
Studento919
  • 625
  • 2
  • 15
  • 44