I am so confused with uploading files in PHP

好久不见. 提交于 2019-12-02 22:20:27

问题


I have tried reading multiple tutorials, the PHP documentation and have no idea what I am doing.

Here is my form

<form action="beta_upload.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="20971520" /><!-- 20 Meg -->
<input type="file" name="file[]" />
<input type="file" name="file[]" />
<input type="file" name="file[]" />
<input type="submit" value="submit" name="submit" />
</form>

Now when I send that through here:

<?php 
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$name = trim($_POST['name']);
$email = trim($_POST['email']);

$username = preg_replace('/[^(\x20-\x7F)]*/','', $username);
$password = preg_replace('/[^(\x20-\x7F)]*/','', $password);
$name = preg_replace('/[^(\x20-\x7F)]*/','', $name);
$email = preg_replace('/[^(\x20-\x7F)]*/','', $email);

$upload_dir = '/beta_images/';

print_r($_FILES);

foreach ($_FILES['files']['error'] as $key => $error) {

    if($error == UPLOAD_ERR_OK) {

    $check_name = $_FILES['files']['name'];

    $filetype = checkfiletype($check_name, 'jpg,jpeg');

        $temp_name = $_FILES['files']['tmp_name'][$key];
        $image_name = 'image_' . $name . '1';
        move_uploaded_file($tmp_name, $upload_dir . $image_name); 

    }

}

It brings back

Warning: Invalid argument supplied for foreach() in /blabla on line 18

I don't understand foreachs all too well, and when I print_r the array it dosen't help me one bit.

Would someone be so kind to help me out.

Thanks.


回答1:


You'd better follow this tutorial: http://www.w3schools.com/php/php_file_upload.asp

foreach ($_FILES['file'] as $file) {

    if($file['error'] == UPLOAD_ERR_OK) {

        $check_name = $file['name'];

        // I assume you have to use the file type here, not name
        $filetype = checkfiletype($file['type'], 'jpg,jpeg');

        $temp_name = $file['tmp_name'];
        $image_name = 'image_' . $file['name'] . '1';
        move_uploaded_file($tmp_name, $upload_dir . $image_name); 

    }

}

Your files are in $_FILES['files'] so using foreach you have to go over each element/file and take its data.



来源:https://stackoverflow.com/questions/4071282/i-am-so-confused-with-uploading-files-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!