我的目标不是现在完美,它的功能。我稍后会添加视觉效果和安全性,但是现在我想要做的就是限制上传到.mp3文件,并在上传后生成文件的URL。
目前,PHP显示预期的回显结果,但该文件不在/var/www/html/upload
中,因为它应该是。
upload.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>
upload_file.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";
}
?>
检查upload/
,目录为空。
Upload: hintro.mp3
Type: audio/mp3
Size: 390.0947265625 kB
Temp file: /tmp/phpnMYOou
Stored in: upload/hintro.mp3
感谢任何和所有帮助!
答案 0 :(得分: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;