Php上传脚本

时间:2014-12-24 11:14:48

标签: php image file-upload upload

我在这里有这个php上传脚本:

<?php include_once 'sessions.php';
include_once 'connect.php';
if (isset($_POST['submit-post'])) {
$j = 0;     // Variable for indexing uploaded image.
$target_path = "../photos/";     // Declaring Path for uploaded images.

for ($i = 0; $i < count($_FILES['file']['name']); $i++) {   // Loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png");      // Extensions which are allowed.
$ext = explode('.', basename($_FILES['file']['name'][$i]));   // Explode file name from dot(.)
$file_extension = strtolower(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] < 2000000)){     // Approx. 1mb files can be uploaded.

if (in_array($file_extension, $validextensions)) {

    if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) { // If file moved to uploads folder.
        $_SESSION['upload-message'] = $j. "&nbsp; &nbsp; File(s) successfully uploaded :)";
        header("Location: ../index");
        exit;
    } else {     //  If File Was Not Moved.
        $_SESSION['upload-message'] = $j. "&nbsp; &nbsp; Files couldn't be uploaded. Please try again.";
        header("Location: ../index");
        exit;
    }
 } else {     //   If File Type Was Incorrect.
    $_SESSION['upload-message'] = $j. "&nbsp; &nbsp; Invalid file type. Only jpg, jpeg or png.";
    header("Location: ../index");
    exit;
}
} else {    // If File Size was exceeded
$_SESSION['upload-message'] = $j. "&nbsp; &nbsp; Invalid file size. Maximum size = 1 mb";
header("Location: ../index");
exit;
}
}
}
?>

我的HTML位看起来像这样:

<form action="includes/new-post.php" class="dropzone" enctype="multipart/form-data" method="post" id="photo-form">
<input id="file" type="file" class="post-photo" name="file[]" multiple="" style="display: none"/>
</form>
....
<input type="submit" name="submit-post" value="post" class="create-new-post" form="photo-form">

表单会保存多个这样的文件,但上传脚本只上传一张照片而不是数组。

我的循环有问题吗?

感谢您的帮助

干杯克里斯

1 个答案:

答案 0 :(得分:1)

move_uploaded_file()功能之后检查你是否正在设置会话和重定向。所以只要上传第一张图片,它就会重定向。

你可以访问Refrence site