1

我似乎无法使用 PHP 上传文件。据我所知,一切都结束了。我什至甚至去挖掘旧教科书并直接从文本中复制示例,但仍然没有成功。

起初,我认为这是保存文件的目录权限的问题,所以我将权限更改为 777,但仍然没有。如果有人有任何建议,我会全力以赴:/

这是代码(HTML):

  <form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file1">
        <br/>
    <input type="submit" value="Upload">
  </form>

PHP 文件:

<?php
$tmp_name = $_FILES['file1']['tmp_name'];
$path = getcwd() . DIRECTORY_SEPARATOR . 'images';
$name = $path . DIRECTORY_SEPARATOR . $_FILES['file1']['name'];
$success = move_uploaded_file($tmp_name, $name);
if($success) {
    $upload_message = $name . ' has been uploaded.';
    echo "$upload_message";
} else {
    echo "something went wrong :(";
}
?>
4

3 回答 3

2

您应该在尝试移动之前检查上传错误,然后您可以追踪问题: http ://www.php.net/manual/en/features.file-upload.errors.php

这是一个基本的例子:

<?php
error_reporting(-1);

$uploaddir = './images/';

// Check for upload attempt
if(isset($_FILES['file1'])){
    $uploadfile = $uploaddir.basename($_FILES['file1']['name']);

    // If no error
    if($_FILES['file1']['error'] == 0){
        //Attempt to move
        if (move_uploaded_file($_FILES['file1']['tmp_name'], $uploadfile)) {
            echo "File is valid, and was successfully uploaded.";
        }else{
            echo 'Error moving file.';
        }
    } else {
        // Has error
        $errors = array(0=>'OK',
                        1=>'UPLOAD_ERR_INI_SIZE',
                        2=>'UPLOAD_ERR_FORM_SIZE',
                        3=>'UPLOAD_ERR_PARTIAL',
                        6=>'UPLOAD_ERR_NO_TMP_DIR',
                        7=>'UPLOAD_ERR_CANT_WRITE',
                        8=>'UPLOAD_ERR_EXTENSION'
                        );
        echo "Error: ".$errors[$_FILES['file1']['error']];
    }
}

顺便提一句。对允许上传非常谨慎。

于 2012-09-18T01:25:41.670 回答
1

您需要确保您有权写入upload_tmp_dir,检查php.ini 中的post_max_size 和upload_max_filesize 限制是否大于您尝试上传的文件。还 $_FILES 包含错误信息,也转储它以获取有关未按预期发生的更多信息。

于 2012-09-18T00:55:09.880 回答
0

我不太确定这是否有效,还没有尝试过。

<?
$uploadpath = '../images/';

if ($_FILES["file1"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file1"]["error"] . "<br />";
    }

  else
    {
echo "Upload: " . $_FILES["file1"]["name"] . "<br />";
    echo "Type: " . $_FILES["file1"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file1"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file1"]["tmp_name"] . "<br />";
    }

    if (file_exists($uploadpath . $_FILES["file1"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      $uploadpath . $_FILES["file"]["name"]);
      echo "UPLOAD SUCCESS!";
      }

?>

来源:W3school

于 2012-09-18T02:39:48.893 回答