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.
Currently, PHP displays the intended echo results, but the file isn't in /var/www/html/upload
, as it should be.
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";
}
?>
Checking upload/
, the directory is empty.
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;