验证ajax

时间:2018-09-06 16:47:13

标签: javascript php jquery ajax security

我有一个图像裁剪器,用于裁剪上载的图像,然后再使用PHP和AJAX将其发送到服务器。

这里是live fiddle,用于预览有效的裁剪示例,先上传图像,然后单击crop对其进行裁剪。

代码如下:

// Create cropped part.
function getRoundedCanvas(sourceCanvas) {
  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');
  var width = sourceCanvas.width;
  var height = sourceCanvas.height;
  canvas.width = width;
  canvas.height = height;
  context.imageSmoothingEnabled = true;
  context.drawImage(sourceCanvas, 0, 0, width, height);
  context.globalCompositeOperation = 'destination-in';
  context.beginPath();
  context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI, true);
  context.fill();
  return canvas;
}

// On uploading a file
$("#input").on("change", function(e) {
  var _URL = window.URL || window.webkitURL,
      file = this.files[0],                   
      image = new Image();
  image.src = _URL.createObjectURL(file);    
  image.onload = function(e) {
    var image = document.getElementById('image'),
        button = document.getElementById('button');
    $('#image').attr('src',  _URL.createObjectURL(file));
    $('#image').show();
    $('#button').show();
    var cropper = new Cropper(image, {
      aspectRatio: 1,
      movable: false,
      cropBoxResizable: true,
      dragMode: 'move',
      ready: function () {
        croppable = true;
        button.onclick = function () {
          var croppedCanvas;
          var roundedCanvas;
          var roundedImage;
          if (!croppable) {
            return;
          }
          // Crop
          croppedCanvas = cropper.getCroppedCanvas();
          cropper.getCroppedCanvas({
            fillColor: '#fff',
            imageSmoothingEnabled: true,
            imageSmoothingQuality: 'high',
          });
          // Round
          roundedCanvas = getRoundedCanvas(croppedCanvas);
          // Show
          roundedImage = document.createElement('img');
          roundedImage.src = roundedCanvas.toDataURL();
          result.innerHTML = '';
          result.appendChild(roundedImage);

        }
      }
    });
  }
}); 
#image,
#button{
  display:none
}
<!-- Cropper CSS -->
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.min.css">
 
 <!-- Cropper JS -->
 <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.min.js"></script>
 
 <!-- File input -->
 <input type="file" id="input" name="image">
 <!-- Selected image will be displayed here -->
 <img id="image" src="" alt="Picture">
 
 <!-- Button to scrop the image -->
 <button type="button" id="button">Crop</button>
 
 <!-- Preview cropped part -->
 <div id="result"></div>

然后,我使用以下代码使用Ajax将blob发送到PHP,以将图像保存在服务器上:

cropper.getCroppedCanvas().toBlob(function (blob) {
  var formData = new FormData();
  formData.append('avatar', blob);
  // Use `jQuery.ajax` method
  $.ajax('upload.php', {
    method: "POST",
    data: formData,
    processData: false,
    contentType: false,
    success: function (response) {
    },
    error: function () {
    }
  });
});

upload.php中:

if( isset($_FILES['avatar']) and !$_FILES['avatar']['error'] ){
  file_put_contents( "uploads/image.png", file_get_contents($_FILES['avatar']['tmp_name']) );
}

我应该对安全性进行检查还是对尺寸和大小进行检查?

1 个答案:

答案 0 :(得分:1)

这将是一个示例,该示例说明了如何以通常安全的方式处理通过ajax调用php脚本上传的图像文件的方式,并且还可以防止重复冲突。

您将需要想出自己的方式来跟踪图像名称(使用数据库等),这超出了问题的范围。

如果您的目录和php结构是:

/path/to/webroot/index.php
/path/to/webroot/upload.php
/path/to/webroot/uploads/(image files)

以下处理上传的PHP可以是这样:

upload.php

<?php
if ( isset($_FILES['avatar']) and empty($_FILES['avatar']['error']) ) {
    if ( is_uploaded_file($_FILES['avatar']['tmp_name']) ) { // safety check

        // validate that it is an accepted image format (and not some junk file)
        $imgdat = getimagesize($_FILES['avatar']['tmp_name']);
        $valid  = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP);

        if ( in_array($imgdat[2],$valid) ) {
             // create a unique filename for the image, using the extension result
             $imgname = com_create_guid() . image_type_to_extension($imgdat[2]);
             $result  = move_uploaded_file(
                            $_FILES['avatar']['tmp_name'],
                            __DIR__ .'/uploads/'. $imgname
                        ); // safely moves the upload to your final destination
        }

    }
}
else {
    // possible error return handler
}
?>

如果服务器上不存在com_create_guid(),则可以将其添加到配置中,或使用预构建的迷你功能来生成相同的内容:https://stackoverflow.com/a/18206984/2960971