Harvey Donnelly Harvey Donnelly - 1 year ago 65
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:


// 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");
} else {
echo "Error: " . mysqli_error($conn);


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




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

Answer Source

Remove the spaces between "test=" + variable;

  var variable = "hello"; 
  document.cookie = "test="+variable; 

  $test = $_COOKIE["test"]; echo $test;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download