[英]Rudimentary PHP upload script not producing desired result
My goal isn't perfection right now, it's functionality. 我的目标不是功能,而是完美。 I'll add visuals and security later, but for now all I'd like to be able to do is restrict uploads to .mp3 files, and product a URL to the file after the upload.
稍后,我将添加视觉效果和安全性,但是现在,我想要做的就是将上传内容限制为.mp3文件,并在上传后为该文件提供一个URL。
Currently, PHP displays the intended echo results, but the file isn't in /var/www/html/upload
, as it should be. 当前,PHP显示了预期的回显结果,但是该文件不在
/var/www/html/upload
中。
upload.html 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 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";
}
?>
Checking upload/
, the directory is empty. 检查
upload/
,目录为空。
Upload: hintro.mp3
Type: audio/mp3
Size: 390.0947265625 kB
Temp file: /tmp/phpnMYOou
Stored in: upload/hintro.mp3
Any and all help is appreciated! 任何和所有帮助表示赞赏!
Assuming your directory structure looks like this 假设您的目录结构如下所示
parent-folder/
|-upload/
|-upload.html
|-upload_file.php
try this 尝试这个
<?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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.