dongwang788787 2014-10-09 08:30
浏览 53

PHP返回上传的文件名进行验证

I just need someone to point me into a direction to do the following.

Once I successfully upload a file to /uploads on my server; the PHP iteratively changes the filename by adding a number if the same file exists (basic override protection). After the file is successfully uploaded, I need a PHP function that can return that filename AND THEN (this is the hard part) to the very page that triggered the PHP uploader script. I will then capture the filename as a variable and pass it to the next page via a cookie (this latter 2 things I already know how to do).

code PHP script:

<?php
$allowedExts = array("zip", "rar"/*, "bmp", "jpg", "png", "tiff"*/);
$temp = explode(".", $_FILES["file"]["name"]);
$name = pathinfo($_FILES["file"]["name"], PATHINFO_FILENAME);
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$i = '';

if ((($_FILES["file"]["type"] == "application/zip")
|| ($_FILES["file"]["type"] == "application/x-zip")
|| ($_FILES["file"]["type"] == "application/octet-stream")
|| ($_FILES["file"]["type"] == "application/x-zip-compressed")
|| ($_FILES["file"]["type"] == "application/x-rar-compressed")
/*|| ($_FILES["file"]["type"] == "image/bmp")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/tiff")*/)
&& ($_FILES["file"]["size"] < 50000000)
&& in_array($extension, $allowedExts))
{
  if ($_FILES["file"]["error"] > 0) 
  {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
  } else
    {
      if (file_exists("upload/" . $name . $i . '.' . $extension)) 
      {
        while(file_exists("upload/" . $name . $i . '.' . $extension)) {
          $i++;
        }

        $basename = $name . $i . '.' . $extension;
        move_uploaded_file($_FILES["file"]["tmp_name"],
        "upload/" . $basename);
      } else
        {
          move_uploaded_file($_FILES["file"]["tmp_name"],
          "upload/" . $_FILES["file"]["name"]);
      }
  }
} else
  {
    echo "Invalid file";
}
?>

HTML5 Upload:

<!DOCTYPE html>
<!-- saved from url=(0044)http://html5demos.com/dnd-upload#view-source -->
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>HTML5 Demo: Drag and drop, automatic upload</title>
<body>
<section id="wrapper">
    <header>
      <h4>Drag and drop</h4>
    </header>

<style>
#holder { border: 1px dashed lightgrey; width: 300px; min-height: 300px; margin: 20px auto;}
#holder.hover { border: 1px dashed #FFCC00; }
#holder img { display: block; margin: 10px auto; }
#holder p { margin: 10px; font-size: 14px; }
progress { width: 50%; }
progress:after { content: ''; }
.fail { background: #c00; padding: 2px; color: #fff; }
.hidden { display: none !important;}
</style>
<article>
  <div id="holder">
  </div> 
  <p id="upload" class="hidden"><label>Drag &amp; drop not supported, but you can still upload via this input field:<br><input type="file"></label></p>
  <p id="filereader" class="hidden">File API &amp; FileReader API not supported</p>
  <p id="formdata" class="hidden">XHR2's FormData is not supported</p>
  <p id="progress" class="hidden">XHR2's upload progress isn't supported</p>
  <p>Upload progress: <progress id="uploadprogress" min="0" max="100" value="0">0</progress></p>
</article>
<script>
var holder = document.getElementById('holder'),
    tests = {
      filereader: typeof FileReader != 'undefined',
      dnd: 'draggable' in document.createElement('span'),
      formdata: !!window.FormData,
      progress: "upload" in new XMLHttpRequest
    }, 
    support = {
      filereader: document.getElementById('filereader'),
      formdata: document.getElementById('formdata'),
      progress: document.getElementById('progress')
    },
    acceptedTypes = {
      //'image/bmp': true
      //'image/jpg': true,
      //'image/png': true,
    },
    progress = document.getElementById('uploadprogress'),
    fileupload = document.getElementById('upload');

"filereader formdata progress".split(' ').forEach(function (api) {
  if (tests[api] === false) {
    support[api].className = 'fail';
  } else {
    // FFS. I could have done el.hidden = true, but IE doesn't support
    // hidden, so I tried to create a polyfill that would extend the
    // Element.prototype, but then IE10 doesn't even give me access
    // to the Element object. Brilliant.
    support[api].className = 'hidden';
  }
});

function previewfile(file) {
  /*if (tests.filereader === true && acceptedTypes[file.type] === true) {
    var reader = new FileReader();
    reader.onload = function (event) {
      var image = new Image();
      image.src = event.target.result;
      image.width = 250; // a fake resize
      holder.appendChild(image);
    };

    reader.readAsDataURL(file);
  }  else {*/
    holder.innerHTML += '<p>Uploaded ' + file.name + ' ' + (file.size ? (file.size/1024|0) + 'K' : '');
    console.log(file);
  /*}*/
}

function readfiles(files) {
    //debugger;
    var formData = tests.formdata ? new FormData() : null;
    for (var i = 0; i < files.length; i++) {
      if (tests.formdata) formData.append('file', files[i]);
      previewfile(files[i]);
    }

    // now post a new XHR request
    if (tests.formdata) {
      var xhr = new XMLHttpRequest();
      xhr.open('POST', 'upload_artwork.php');
      xhr.onload = function() {
        progress.value = progress.innerHTML = 100;
      };

      if (tests.progress) {
        xhr.upload.onprogress = function (event) {
          if (event.lengthComputable) {
            var complete = (event.loaded / event.total * 100 | 0);
            progress.value = progress.innerHTML = complete;
          }
        }
      }

      xhr.send(formData);
    }
}

if (tests.dnd) { 
  holder.ondragover = function () { this.className = 'hover'; return false; };
  holder.ondragend = function () { this.className = ''; return false; };
  holder.ondrop = function (e) {
    this.className = '';
    e.preventDefault();
    readfiles(e.dataTransfer.files);
  }
} else {
  fileupload.className = 'hidden';
  fileupload.querySelector('input').onchange = function () {
    readfiles(this.files);
  };
}
</script>
</body></html>

</div>
  • 写回答

2条回答 默认 最新

  • duanjiagu0655 2014-10-09 09:06
    关注

    Submit the form with ajax form submit which will return the values of the file path . Hope this help's you..

    <?php
    if($_FILES["file"]["name"] != '')
        {
            $output_dir="uploads/";
            if(move_uploaded_file($_FILES["file"]["tmp_name"],$output_dir.$_FILES["file"]["name"]))
            {
                chmod($output_dir.$_FILES["file"]["name"],0777);
                echo $_FILES["file"]["name"];
                exit;
            }
    
        }
    ?>
    <html> 
    <head> 
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
        <script src="http://malsup.github.com/jquery.form.js"></script> 
    
        <script> 
            // wait for the DOM to be loaded 
            $(document).ready(function() { 
            var jvar="";
                // bind 'myForm' and provide a simple callback function 
                $('#myForm').ajaxForm({ 
            clearForm: 'true',
                success: function(data){
            if(data != '')
            {
                jvar=data;
                window.location.href="test.php?path="+jvar;
    
                //Assign the to a variable and pass to another file
            }
    
            }
    
                }); 
    
            }); 
        </script> 
    </head> 
    <form id="myForm" action="test.php" method="post"> 
       <input type="file" name="file"> 
        <input type="submit" value="Submit Comment" /> 
    </form>
    
    评论

报告相同问题?