I can't figure out what is missing in my PHP-based upload program

41 Views Asked by At

I've successfully uploaded the mp3 file to the server (local), and I'm trying to move the file to the destination folder which is located in the /opt/lampp/htdocs folder and folder name is songs. But the file is not being moved to the folder.

This is my html code for uploading file (I'm trying to move an mp3 file):

<form method="post" action="../scripts/saveAudio.php" accept-charset="utf-8" enctype="multipart/form-data">
    <input type="file" name="song"><br></br>
    <div class="uploadbtn" align="center"><input type="submit" name="upload" value="Upload"></div>
</form>

And this is php code:

<?php

if(isset($_POST['upload'])){
if (($_FILES['song']['type'] == "audio/mpeg"))
{
    $tempName = $_FILES['song']['tmp_name'][$key];
    $desPath = "../songs/" . $_FILES['song']['name'];
    
    if ($_FILES['song']['error'] > 0)
    {
        header('Location: ../src/uploadSongs.html');
        exit();
    }
    
    if (file_exists("../songs/" . $_FILES['song']['name']))
        {
            echo $_FILES['file']['name'] . " already exists. ";
        }
    if(!move_uploaded_file($tempName, $desPath))
        {
            echo "File can't be uploaded";
        }
}

else
{
    echo "Please Upload MP3 files only";
}
}

?>
1

There are 1 best solutions below

2
D. Dimopoulos On

Before you apply the following code, make sure that you have increasesed "upload_max_filesize" in php.ini. If you don't change this value, you will get errors.

The location of php.ini is in "/etc/php/7.X/apache2/php.ini". Just replace 7.X with your php version.

The structure of my project is the following:

- fileUpload.php // upload file and store it in folder songs
- songs          // folder to store uploaded files

And the code (it can be used for multiple files with some modifications):

if(isset($_POST['upload'])){

    $numberOfFiles = sizeof($_FILES["song"]["name"]);
    echo "<br>Number of selected files: ".$numberOfFiles.'<br>';

    $counter = 0; // get the first file from a list of files
    $tempName = $_FILES['song']['tmp_name'][$counter];
    $desPath = realpath(dirname(__FILE__))."/songs/" . $_FILES['song']['name'][$counter];



    if (file_exists(realpath(dirname(__FILE__))."/songs/" . $_FILES['song']['name'][$counter]))
    {
        echo $_FILES['file']['name'] . " already exists. ";
    }
    if(!move_uploaded_file($tempName, $desPath))
    {
        echo "File can't be uploaded";
    }

}

?>

<form method="post" action="<?php echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>" enctype="multipart/form-data">
    <input type="file" multiple="multiple" name="song[]" accept="audio/mpeg3"><br></br>
    <div class="uploadbtn" align="center">
    <input type="submit" name="upload" value="Upload"></div>
</form>

I hope it helps.