使用PHP脚本上传文件夹中的文件


Upload a file in folder using PHP script

我正在尝试使用PHP脚本上传和保存图像,但图像没有保存在指定的文件夹中。请帮助

这是我的代码:

  <?php
  if(isset($_POST['button'])){
  $name= "product_name.jpg";
  move_uploaded_file($_FILES["fileField"]["tmp_name"],"student_images/$name");
  header("location: tryupload.php");
  }
  ?>
  <html>
  <body>
  <form action="tryupload.php" enctype="multiple/form-data" name="myForm" id="myform" method="post">
  <table>
  <tr>
    <td align="right">Product Image</td>
    <td><label>
      <input type="file" name="fileField" id="fileField" />
    </label></td>
  </tr>      
  <tr>
    <td>&nbsp;</td>
    <td><label>
      <input type="submit" name="button" id="button"/>
    </label></td>
  </tr></table>
  </form>
  </body>
  </html>

代码enctype="multiple/form-data"的这一部分是不正确的。

它需要读作enctype="multipart/form-data"

还要确保你打算上传到的文件夹有适当的写入权限。

  • http://php.net/manual/en/features.file-upload.post-method.php

  • http://php.net/manual/en/function.chmod.php(设置文件夹/文件权限)。

上传安全相关链接:

  • https://security.stackexchange.com/questions/32852/risks-of-a-php-image-upload-form

  • 100%安全的照片上传脚本


错误报告添加到文件顶部,这将有助于查找错误。

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code

旁注:错误报告只能在临时阶段进行,而不能在生产阶段进行。

要上传您可以拥有的多个文件。

多上传.php

<? session_start()?>
<!DOCTYPE html>
<html>
    <head>
    <title>Blank</title>
    <!-------Including jQuery from google------>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script src="js/script.js"></script>

        <!-------Including CSS File------>
        <link rel="stylesheet" type="text/css" href="css/style.css">
    <link rel="stylesheet" type="text/css" href="css/main.css">
    <body>
            <div id="formdiv">
                    <h1 class="uploadH2">Upload Your Artwork</h1>
                <form enctype="multipart/form-data" action="" method="post">
                  Take a photo, upload your artwork, or choose an image from Facebook or Instagram

            <label for="file">
                    <div id="image" style="margin-top:5%;">
                    <img src="img/camera.png">    
                    </div>
                    </label>

                    <div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>

                    <input type="button" class="add_more" id="add_more" value="Add More Files"/>
                    <input type="submit" value="Upload File" name="submit" id="img_upload" class="show-page-loading-msg" data-theme="b" data-textonly="false" data-textvisible="false" data-msgtext="" data-icon="arrow-r" data-iconpos="right"/>
                </form>
                <br/>
                <br/>
                <!-------Including PHP Script here------>
                <?php include "uploadScript.php"; ?>
        </div>
    </body>
</html>

uploadScript.php

<?php
$dir_id = session_id(md5(uniqid()));
session_start($dir_id);
$path = "uploads/";
$dir = $path.$dir_id;
$path = $path.$dir_id."/";
if (file_exists($dir)) {
    system('/bin/rm -rf ' . escapeshellarg($dir));
} else {
mkdir($path);
chmod($path, 0722);  
}
$_SESSION["id"] = $dir_id;
$_SESSION["directory"] = "/" . $dir;
$_SESSION["path_name"] = $path;
?>
<?
if (isset($_POST['submit'])) {
    $j = 0; //Variable for indexing uploaded image
    $target_path = $path;
    for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
        $validextensions = array("jpeg", "jpg", "png", "gif");  //Extensions which are allowed
        $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) 
        $file_extension = end($ext); //store extensions in the variable
        $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
        $j = $j + 1;//increment the number of uploaded images according to the files in array       
      if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
                && in_array($file_extension, $validextensions)) {
            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
                echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
            } else {//if file was not moved.
                echo $j. ').<span id="error">Only JPG, JPEG, PNG and GIF files types allowed.</span><br/><br/>';
            }     
        } else {//if file size and file type was incorrect.
            echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
        }
    }
}
?>

此脚本只接受jpg、png、gif和jpeg。您不能上传或执行目录中的任何内容,除非您是所有者,并且文件大小不能超过10KB。

script.js

var abc = 0; //Declaring and defining global increement variable
$(document).ready(function() {
//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
    $('#add_more').click(function() {
        $(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
                $("<input/>", {name: 'file[]', type: 'file', id: 'file'}),        
                $("<br/><br/>")
                ));
    });
//following function will executes on change event of file input to select different file   
$('body').on('change', '#file', function(){
            if (this.files && this.files[0]) {
                 abc += 1; //increementing global variable by 1
                var z = abc - 1;
                var x = $(this).parent().find('#previewimg' + z).remove();
                $(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src='' style='width:40%; height:40%;'/></div>");
                var reader = new FileReader();
                reader.onload = imageIsLoaded;
                reader.readAsDataURL(this.files[0]);
                $(this).hide();
                $("#abcd"+ abc).append($("<img/>", {id: 'delete', src: 'x.png', alt: 'delete'}).click(function() {
                $(this).parent().parent().remove();
                }));
            }
        });
//To preview image     
    function imageIsLoaded(e) {
        $('#previewimg' + abc).attr('src', e.target.result);
    };
    $('#upload').click(function(e) {
        var name = $(":file").val();
        if (!name)
        {
            alert("First Image Must Be Selected");
            e.preventDefault();
        }
        else {}
    });
});

这将上传多个文件,在与上传表单相同的页面上预览图像,这将在服务器内部/上传一个目录,该目录与用户session_id()匹配。如果该目录存在,则该目录将被删除,如果不存在,则将创建该目录。然后,这些文件将被上传到服务器上的那个目录中。

表单的enctype不正确。请使用"multiple/form-data"而不是"multipart/form-data"