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

时间:2015-03-28 18:53:45

标签: php html

我正在尝试使用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>

3 个答案:

答案 0 :(得分:7)

您的代码enctype="multiple/form-data"的这部分内容不正确。

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

另外,请确保您要上传的文件夹具有相应的写入权限。

上传与安全相关的链接:


error reporting添加到文件的顶部,这有助于查找错误。

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

旁注:错误报告应仅在暂存时完成,而不是生产。

答案 1 :(得分:1)

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

Multiupload.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 {}

    });
});

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

答案 2 :(得分:0)

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