PHP文件上传和覆盖同名文件

标签 php file-upload

我正在制作一个应用程序,允许用户通过 PHP 上传目录中的文件。

我遇到了问题,因为它不允许我覆盖具有相同名称的文件。 例如,我有一个名为 text.php 的文件并上传了它,现在当我返回并更改文件 text.php 的内容并再次将其上传到服务器时,我仍然拥有未经编辑的版本。但是,如果我上传另一个文件,它就可以工作。所以我不能覆盖文件。

if ($_POST["greg"]=='true'){
// Set local PHP vars from the POST vars sent from our form using the array
// of data that the $_FILES global variable contains for this uploaded file
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true

// Specific Error Handling if you need to run error checking
if (!$fileTmpLoc) { // if file not chosen
    echo "ERROR: Please browse for a file before clicking the upload button.";
    exit();
} else if($fileSize > 90000000000000) { // if file is larger than we want to allow
    echo "ERROR: Your file was larger than 50kb in file size.";
    unlink($fileTmpLoc);
    exit();
} else if (!preg_match("/.(doc|docx|xls)$/i", $fileName) ) {
     // This condition is only if you wish to allow uploading of specific file types    
     echo "ERROR: Your file is not the right format contact the master of the page for clarification.";
     unlink($fileTmpLoc);
     exit();
}
// Place it into your "uploads" folder mow using the move_uploaded_file() function
move_uploaded_file($fileTmpLoc, "documenti/$fileName");
// Check to make sure the uploaded file is in place where you want it
if (!file_exists("documenti/$fileName")) {
    echo "ERROR: File not uploaded<br /><br />";
    echo "Check folder permissions on the target uploads folder is 0755 or looser.<br /><br />";
    echo "Check that your php.ini settings are set to allow over 2 MB files, they are 2MB by default.";
    exit();
}
// Display things to the page so you can see what is happening for testing purposes
echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />";
echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />";
echo "It is a <strong>$fileType</strong> type of file.<br /><br />";
echo "The Error Message output for this upload is: <br />$fileErrorMsg";

}

如何更改此代码,以便在我上传同名文件时覆盖现有文件?

最佳答案

试试这个(在上传文件之前把它)

//checking if file exsists
if(file_exists("documenti/$fileName")) unlink("documenti/$fileName");

//Place it into your "uploads" folder mow using the move_uploaded_file() function
move_uploaded_file($fileTmpLoc, "documenti/$fileName");

关于PHP文件上传和覆盖同名文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8064618/

相关文章:

javascript - AngularJS 可以在没有任何服务器端技术的情况下将文件保存/写入到服务器吗?

javascript - setFilesToUpload 操作对我不起作用

php - 用PHP在MySQL数据库中插入JSON数据

PHP插入错误没有解释

php - 如何将路由返回到 laravel 中的 View

java - 使用 playframework 上传文件时的附加信息

php - 如何创建尽可能短的 URL-able unique id?

PHP 对象生命周期

rest - 失眠者同时上传图片和发布数据

javascript - 禁用 jQuery 文件上传的拖放功能