Search code examples
javascriptphphtmluploadmp3

Need to upload file and replace the existing one


I need to execute the following either in JS or PHP (and HTML):

Upload a file on the server via HTML form; then rename the file automatically to "main.mp3"; and if the file already exists (ofc it does), replace it.

That's it! Thank you :)


Solution

  • In your php send form code, you can check if files exist, if exist, unlink and upload the new file:

    <?php
    $directory_save = "example/directory/for/save/";
    $file_name = $_FILES["myupload"]["name"];
    $new_file_name = "main.mp3";
    
    if (file_exists($directory_save . $file_name)) {
        //if file exists in directory
        unlink($file);
    }
    
    //upload file with new name and check if uploaded
    if (move_uploaded_file($_FILES['myupload']['tmp_name'], $directory_save . $new_file_name)) {
        echo "file uploaded";
    } else {
        echo "error on upload";
    }
    ?>
    

    Remember that in $_FILES["myupload"], the "myupload" is the name of the input in the form.