PHP - upload and overwrite a file (or upload and rename it)?

元气小坏坏 提交于 2019-12-05 07:48:20

问题


I have searched far and wide on this one, but haven't really found a solution.

Got a client that wants music on their site (yea yea, I know..). The flash player grabs the single file called song.mp3 and plays it.

Well, I am trying to get functionality as to be able to have the client upload their own new song if they ever want to change it.

So basically, the script needs to allow them to upload the file, THEN overwrite the old file with the new one. Basically, making sure the filename of song.mp3 stays intact.

I am thinking I will need to use PHP to 1) upload the file 2) delete the original song.mp3 3) rename the new file upload to song.mp3

Does that seem right? Or is there a simpler way of doing this? Thanks in advance!


EDIT: I impimented UPLOADIFY and am able to use

'onAllComplete' : function(event,data) {
      alert(data.filesUploaded + ' files uploaded successfully!');
    }

I am just not sure how to point THAT to a PHP file....

 'onAllComplete' : function() {
      'aphpfile.php'
    }

???? lol


回答1:


a standard form will suffice for the upload just remember to include the mime in the form. then you can use $_FILES[''] to reference the file.

then you can check for the filename provided and see if it exists in the file system using file_exists() check for the file name OR if you don't need to keep the old file, you can use perofrm the file move and overwrite the old one with the new from the temporary directory

<?PHP
// this assumes that the upload form calls the form file field "myupload"
$name  = $_FILES['myupload']['name'];
$type  = $_FILES['myupload']['type'];
$size  = $_FILES['myupload']['size'];
$tmp   = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
    // echo "The file $filename exists";
    // This will overwrite even if the file exists
    move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way

?>



回答2:


try this piece of code for upload and replace file

if(file_exists($newfilename)){
        unlink($newfilename);
    }

 move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newfilename); 


来源:https://stackoverflow.com/questions/8919804/php-upload-and-overwrite-a-file-or-upload-and-rename-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!