title: PHP: upload a canvas image to server and save image directory to database
body: <p>i am new in PHP and web development in general. I want to upload an image from an HTML canvas to server and save its location to my database, but for some reason that i could not point, it fails to do so. Uploading the image to server works just fine, but i am having a problem with saving its location.</p>
  
  <p>My  code:</p>
  
  <pre><code>    //javascript to pass canvas data to php
      &lt;script&gt;
          function uploadEx() {
              var canvas = document.getElementById("canvas");
              var dataURL = canvas.toDataURL("image/png");
              document.getElementById('hidden_data').value = dataURL;
              var fd = new FormData(document.forms["form1"]);
  
              var xhr = new XMLHttpRequest();
              xhr.open('POST', 'upload_data.php', true);
  
              xhr.upload.onprogress = function(e) {
                  if (e.lengthComputable) {
                      var percentComplete = (e.loaded / e.total) * 100;
                      console.log(percentComplete + '% uploaded');
                      alert('Succesfully uploaded');
                  }
              };
  
              xhr.onload = function() {
  
              };
              xhr.send(fd);
          };
      &lt;/script&gt;
  </code></pre>
  
  <p>PHP Code:</p>
  
  <pre><code>&lt;?php
  //upload image to server
  $upload_dir = "upload/";
  $img = $_POST['hidden_data'];
  $img = str_replace('data:image/png;base64,', '', $img);
  $img = str_replace(' ', '+', $img);
  $data = base64_decode($img);
  $file = $upload_dir . mktime() . ".png";
  $success = file_put_contents($file, $data);
  print $success ? $file : 'Unable to save the file.';
  echo "" . $file
  
  //save the location to database
  $servername = "localhost";
  $username = "root";
  $password = "";
  $dbname = "signatures";
  
  // Create connection
  $conn = new mysqli($servername, $username, $password, $dbname);
  $escapedString = mysqli_real_escape_string($conn,$file);
  // Check connection
  if ($conn-&gt;connect_error) {
  die("Connection failed: " . $conn-&gt;connect_error);
  } 
  
  $sql = "INSERT INTO signatures (imagePath)
  VALUES ('".$escapedString."')";
  
  if ($conn-&gt;query($sql) === TRUE) {
    echo "New record created successfully";
  } else {
    echo "Error: " . $sql . "&lt;br&gt;" . $conn-&gt;error;
  }
  
  $conn-&gt;close();
  ?&gt;
  </code></pre>
  
  <p>Is there something wrong with my code that i fail to see? Thanks in advance!</p>