1

我现在的目标不是完美,而是功能。我稍后会添加视觉效果和安全性,但现在我想做的只是将上传限制为 .mp3 文件,并在上传后生成文件的 URL。

目前,PHP 显示预期的回显结果,但文件不在 中/var/www/html/upload,因为它应该是。

HTML(至少有问题的部分。)

上传.html

<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file"><strong>File:</strong></label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="SUBMIT">
</form>

PHP(它的每一点。)

上传文件.php

<?php
if ($_FILES["file"]["type"] == "audio/mp3")
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

PHP 结果

检查upload/,目录为空。

Upload: hintro.mp3
Type: audio/mp3
Size: 390.0947265625 kB
Temp file: /tmp/phpnMYOou
Stored in: upload/hintro.mp3

任何和所有的帮助表示赞赏!

4

1 回答 1

0

假设您的目录结构如下所示

parent-folder/
    |-upload/
    |-upload.html
    |-upload_file.php

试试这个

<?php
// Remove these two lines when you've finished development
error_reporting(E_ALL);
ini_set('display_errors', 'On');

if (!($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['file']))) {
    throw new Exception('Only accepting file uploads via POST');
}

$file = $_FILES['file'];
if ($file['error'] > 0) {
    throw new Exception('File upload error', $file['error']);
}
if ($file['type'] != 'audio/mp3') {
    throw new Exception('Invalid file');
}

$dest = __DIR__ . '/upload/' . $file['name'];

if (file_exists($dest)) {
    throw new Exception(sprintf('%s already exists', basename($dest)));
}
if (!is_writable(dirname($dest))) {
    throw new Exception(sprintf('%s is not writable', dirname($dest)));
}

if (!move_uploaded_file($file['tmp_name'], $dest)) {
    throw new Exception(sprintf('Error moving uploaded file from %s to %s',
        $file['tmp_name'], $dest));
}

echo 'Upload: ',    $file['name'],     '<br>',
     'Type: ',      $file['type'],     '<br>',
     'Size: ',      $file['size'],     '<br>',
     'Temp file: ', $file['tmp_name'], '<br>',
     'Stored in: ', $dest;
于 2013-04-17T01:56:05.880 回答