Harvey Donnelly Harvey Donnelly - 21 days ago 7
Javascript Question

Cannot access cookie created by js using php

I have only just began to learn how to use cookies and so I'm sorry if the answer is really simple.
I am attempting to create a MYSQL database with the name as a JS variable. To do this, I am attempting to save the variable as a cookie:

document.cookie = "test=" + variable;


I then try to get the cookie and save it as a PHP variable to then be executed:

<?php

// Define set variables

$servername = "localhost";
$username = "root";
$password = "";

// Get input variables

$test = $_COOKIE["test"];

// Create connection

$conn = mysqli_connect($servername, $username, $password);

// Check connection

if (!$conn) {
die("Error: " . mysqli_connect_error());
}

// sql to create table

$sql = "CREATE DATABASE `$test`";

if (mysqli_query($conn, $sql)) {
header("Location: index.html");
exit;
} else {
echo "Error: " . mysqli_error($conn);
}

mysqli_close($conn);
?>


I have tried creating a cookie via PHP for testing purposes:

<?php

setcookie("test","variable");

?>


When I try to access the cookie created by the JS it clains the index is undefined but it runs perfectly when I create the cookie with PHP
Thanks

Answer

Remove the spaces between "test=" + variable;

<Script> 
  var variable = "hello"; 
  document.cookie = "test="+variable; 
</script> 

<?php 
  $test = $_COOKIE["test"]; echo $test;
?>
Comments