2017-05-20 10 views
1

ファイルをディレクトリに保存する画像アップロードスクリプトと、mySqlへのリンクのコピーがあります。PHP AJAXがセッションを受信して​​いません

ユーザIDを「123」とすると、データベースに新しいエントリが保存されます。しかし、ユーザーIDを$ _SESSION ['unique_user_id']とすると、データベースに新しいエントリを追加しませんが、ファイルを保存し続けます。

私は両方のPHPページにsession_start();を添付しましたが、添付されたjavascriptファイルには含まれていません。

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(); 
} 

?> 
+0

あなたは '$ unique_user_id'を上書きしています。 –

+0

@ Fred-ii-私はとても盲目です!それを指摘していただきありがとうございます。今すぐうまくいく – Sam

答えて

1

$unique_user_idを上書きしています。

あなたはそれを宣言することによって始まった:あなたはまた、代わりにセッションアレイにPOST配列を割り当て、それがあるかどうかを確認することができ

$unique_user_id = $_POST['userid']; 

:とそれを上書きその後

$unique_user_id = $_SESSION['unique_user_id']; 

セット/空ではない。この条件付きチェックは、すべてのページで実行する必要があります。

関連する問題