在AJAX调用中检索时,为什么PHP Session变量会更改为不相关的内容?

时间:2017-09-28 01:54:50

标签: javascript php jquery ajax session

我在example.com/add-results.php有一个大页面的页面,其中一个“字段”是人们可以上传图像的下方区域。使用“选择图像”按钮的标准行为,然后在您选择时,会出现“上传”按钮。然后单击该按钮,将显示现在上传的服务器图像的预览,并显示“删除/更改”按钮。

重要说明预览图像的默认src如何是“no-image.png”(稍后会发布)......

<label class="caption" for="">Pool Image </label> (OPTIONAL - You can add one later if you don't have one now)<br>                
    <span>for testing: <?php echo $_SESSION['poolid'];?></span>
    <div id="preview"><img id="image" src="no-image.png" /></div>
    <label for="uploadImage" id="custom-file-upload">
        Choose Image
    </label>
    <span id="file-selected"></span>
    <input id="uploadImage" type="file" accept="image/*" name="image" />
    <input id="button" type="button" value="Upload" class="displaynone webkit">
    <input id="remove-image" class="displaynone" type="button" value="Remove/Change">
    <div id="err"></div>

add-results.php页面上还包含此javascript文件,该文件进行AJAX调用...

$(document).ready(function () {
    $("input:file").change(function (){
      $( "#button" ).show();
     });

 $('#uploadImage').bind('change', function() { var fileName = ''; fileName = $(this).val(); $('#file-selected').html(fileName); });

 $("#button").click(function(){
    var imageData = new FormData();
    imageData.append('image', $('#uploadImage')[0].files[0]);

    //Make ajax call here:
    $.ajax({
          url: "/upload-image-results-ajax.php",
          type: 'POST',
          processData: false, // important
          contentType: false, // important
          data: imageData,
          beforeSend : function()  {
            $("#err").fadeOut();
           },
       success: function(result) {
            if(result=='invalid file') {
             // invalid file format.
             $("#err").html("Invalid File !").fadeIn();
            } else {

             // view uploaded file.
             $("#image").attr('src', '/'+result);
            /* $("#preview").html(data).fadeIn();*/
            /* $("#form")[0].reset(); */
             //show the remove image button
             $('#file-selected').empty();
             $( "#remove-image" ).show();
             $( "#custom-file-upload" ).hide();
             $( "#uploadImage" ).hide();
             $( "#button" ).hide();
            }
          },
         error: function(result)  {
              $("#err").html("errorcity").fadeIn();
          }      
     });
   });

  $("#remove-image").click(function(){
    //Make ajax call here:
    $.ajax({
          url: "/remove-image-results.php",
          type: 'POST',
          processData: false, // important
          contentType: false, // important
       success: function(result) {
            if(result=='gone') {
             $("#image").attr('src', '/images/no-image.png');
             $('#file-selected').empty();
             $( "#custom-file-upload" ).show();
             $( "#remove-image" ).hide();
             $( "#uploadImage" ).hide();
             $( "#button" ).hide();
            } else {
            }
          },
         error: function(result)  {
              $("#err").html("error").fadeIn();
          }      
     });
   });

 //deleting uploaded image (if one exists) if user cancel's out of Add Results screen
 $("#cancel-and-remove-image").click(function(){
    //Make ajax call here:
    $.ajax({
          url: "/remove-image-results.php",
          type: 'POST',
          processData: false, // important
          contentType: false, // important
          success: function(result) {
          },
          error: function(result)  {

          }      
     });
   });

  });

最后,这是一个名为upload-image-results-ajax.php的页面,它执行上面AJAX调用调用的实际上传任务...

<?php
require_once("includes/session.php");
$poolid=$_SESSION['poolid']; //lowercase it first so we get exact matches
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions

if(isset($_FILES['image'])) {
    $img = $_FILES['image']['name'];
    $tmp = $_FILES['image']['tmp_name'];

    // get uploaded file's extension
    $ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));

    //checking if image exists for this pool and removing if so, before adding new image in its place
    if(file_exists("uploads/results/".$poolid.".png")) {
     unlink("uploads/results/".$poolid.".png");
    }

    // checks valid format
    if(in_array($ext, $valid_extensions))  { 
    //re-size the image and make it a PNG before sending to server
    $final_image = $poolid . ".png";
    $path = "uploads/results/".strtolower($final_image); 
    $size = getimagesize($tmp);
    $ratio = $size[0]/$size[1]; // width/height
    if( $ratio > 1) {
        $width = 200;
        $height = 200/$ratio;
    }
    else {
        $width = 200*$ratio;
        $height = 200;
    }
    $src = imagecreatefromstring(file_get_contents($tmp));
    $dst = imagecreatetruecolor($width,$height);
    imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]);
    imagedestroy($src);
    imagepng($dst, $path); // adjust format as needed
    imagedestroy($dst);

    echo $path ."?".rand(1,32000); 
    } else {
      echo 'invalid file';
    }
}
?>

注意它是怎么说的“$ poolid = $ _ SESSION ['poolid'];”。这是所有这一切的关键。这个会话ID肯定是在带有实际poolid的add-results.php页面上设置的,比如p0902ftel7

快点:因为我知道有人会问,让我们把它弄清楚。会话肯定是在add-results.php的顶部开始,也是在上面的页面顶部使用session.php的包含,其中包含简单的:

<?php
    session_start();
?>

最终图片位置/网址格式应为“example.com/uploads/results/(poolid).png”

所以使用实际的poolid的例子是:“example.com/uploads/results/p0902ftel7.png”

因此只要设置$ _SESSION ['poolid'](同样如此),将设置poolid并且图像的URL将更正。

现在,当我上传图像时,它会将图像上传到服务器,但不是命名为“p0902fte17.png”,而是命名为“no-image.png”。因此,上传图片的完整网址如下:example.com/uploads/results/no-image.png.png?22555

仅供参考,“?22555”只是一个随机数,用于在预览图像时帮助解决缓存图像问题。

我对这种行为感到非常困惑,并祈祷有人知道可能会发生什么。我现在已经失去了大约8个小时。我无法理解$ _SESSION ['poolid']的值如何从实际id(如p0902fte17)变为“no-image.png”(src的默认图像add-results.php)。

有什么想法吗?

0 个答案:

没有答案