简体   繁体   English

Canvas无法保存服务器端PHP

[英]Canvas will not save server side PHP

I have a canvas which I need to save to a directory and store the URL in a database. 我有一个画布,需要将其保存到目录并将URL存储在数据库中。

When I save the file without storing the URL in the database it works fine, and vice versa. 当我保存文件而不将URL存储在数据库中时,它可以正常工作,反之亦然。

However, when I put the two together and specify the PHP file through AJAX, for some reason it doesn't recognise the session variable? 但是,当我将两者放在一起并通过AJAX指定PHP文件时,由于某种原因它无法识别会话变量?

When I try to call the "success" on AJAX, nothing shows up. 当我尝试在AJAX上调用“成功”时,什么都没有显示。 I get no response. 我没有回应。

This could possibly be an easy fix! 这可能是一个简单的解决方法! I think I've been staring at this code for too long. 我想我盯着这段代码已经太久了。

JavaScript: JavaScript:

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

  $.ajax({
    url:'doodleupload.php', 
    type:'POST', 
    data:{ data:canvasData },
    success: function(response){
        alert(response);
        //echo what the server sent back...
    }
  });
}

PHP: PHP:

<?php
  session_start();

  /* AUTOMATED VARIABLES */
  $url             = md5(uniqid(rand(), true));
  $unique_user_id  = $_SESSION['unique_user_id'];
  $unique_post_id  = md5(uniqid(rand(), true));
  $timestamp       = time();
  $nature          = "doodle";
  $imageUrl        = $upload_dir.$url.'.png';

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

  echo $success ? $file : 'Unable to save the file.';

  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 "File in database";
    }
    else
    {
      echo "Not in database";
    }
  }
  catch(PDOException $e){
    echo $e->getMessage();
  }

?>

Move $upload_dir at the top, as you are calling it before you initialize it. 在初始化之前,将$upload_dir顶部,就像您在调用它一样。

$upload_dir = "images/external/doodles/";
$url             = md5(uniqid(rand(), true));
$unique_user_id  = $_SESSION['unique_user_id'];
$unique_post_id  = md5(uniqid(rand(), true));
$timestamp       = time();
$nature          = "doodle";
$imageUrl        = $upload_dir.$url.'.png';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM