Sam Sam -4 years ago 78
Javascript Question

PHP AJAX not receiving SESSION

I have an image upload script which saves the file to the directory and a copy of the link to mySql.

If I put the user id as "123" it saves a new entry in the database. However, if I put the user id as $_SESSION['unique_user_id']; it does not put a new entry in the database but continues to save the file.

I've included

session_start();
on both the PHP pages but not the attached javascript file.

JS:

function doodleSave() {

var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");

$.post('test.php', {data: canvasData}, function (response) {

var data = JSON.parse(response);

if (data.filename !== false) {

alert (data.filename);

} else {

alert('unable to upload');

}
});
}


PHP:

<?php
session_start();
$unique_user_id = $_SESSION['unique_user_id'];


$randomFolder = md5(uniqid(rand(), true));
$upload_dir = "images/external/doodles/".$randomFolder."/";

if (!file_exists($upload_dir)) {
mkdir($upload_dir, 0755, true);
}

$url = md5(uniqid(rand(), true));
$unique_user_id = $_POST['userid'];
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';

$img = $_POST['data'];
$img = substr($img,strpos($img,",")+1);
$data = base64_decode($img);
$file = $upload_dir . $url . ".png";
$success = file_put_contents($file, $data);

if(!$success) {

echo json_encode(['filename' => false]);
exit(); // Prints success and exit the script

} else {

require_once 'php/connect.php';

try
{
$stmt = $pdo->prepare("INSERT INTO posts (unique_user_id, unique_post_id, nature, image_url, timestamp) VALUE (:unique_user_id, :unique_post_id, :nature, :image_url, :timestamp)");
$stmt->bindParam(":unique_user_id",$unique_user_id);
$stmt->bindParam(":unique_post_id",$unique_post_id);
$stmt->bindParam(":nature",$nature);
$stmt->bindParam(":image_url",$imageUrl);
$stmt->bindParam(":timestamp",$timestamp);

if($stmt->execute())
{
echo json_encode(['filename' => "in database"]);
}
else
{
echo json_encode(['filename' => "not in database"]);
}
}
catch(PDOException $e)
{
$return_data = $e->getMessage();
}
exit();
}

?>

Answer Source

As I stated in comments; you're overwriting $unique_user_id.

You started off by declaring it in:

$unique_user_id = $_SESSION['unique_user_id'];

Then overwrote it with:

$unique_user_id = $_POST['userid'];

You could also assign the POST array to the session array instead and check to see if it is set/not empty. This conditional check should be done in every page.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download