php - 上传和覆盖已经存在的文件
问题描述
我已经创建了一个设置来上传一个文件,该文件根据产品 ID 命名文件,在此处提交的一些内容的帮助下,我设法使其正常工作。有时上传并不想覆盖我的文件。我的脚本中是否有任何明显的错误?
$dir = DIR . '/images/productthumbs/';
if (!is_dir($dir))
{
die(construct_phrase($vbphrase['invalid_directory'], $dir));
}
$ext = substr($file['name'], strrpos($file['name'], '.'));
$new_file = $dir . basename('thumbnail_product_' . $id . $ext);
print_dots_start($vbphrase['please_wait_while_upload']);
if(file_exists($new_file)) unlink($new_file);{
move_uploaded_file($new_file);
if (!move_uploaded_file($file['tmp_name'], $new_file))
{
print_dots_stop();
die(construct_phrase($vbphrase['error_upload'], $file['error']));
}
}
解决方案
If you upload file with same name of ex file, ex file will be removed and new file will be overwrited. Or before upload new file you can remove ex file and upload a new file. Some of your codes are wrong you should write true codes. As I understand you have to change code with :
<?php
$dir = DIR . '/images/productthumbs/';
if (!is_dir($dir))
{
die(construct_phrase($vbphrase['invalid_directory'], $dir));
}
$ext = substr($file['name'], strrpos($file['name'], '.'));
$new_file = $dir . basename('thumbnail_product_' . $id . $ext);
print_dots_start($vbphrase['please_wait_while_upload']);
$ex_file="same path of ex file"; // you have to remove ex file
if(file_exists($ex_file))
{
unlink($ex_file); // with this code you remove ex file
if (!move_uploaded_file($file['tmp_name'], $new_file))
{
print_dots_stop();
die(construct_phrase($vbphrase['error_upload'], $file['error']));
}
} ?>
Please be carefull about $ex_file. I dont know which variable has current old file. Some I renamed it for you to understand clearly.
推荐阅读
- javascript - 在 forEach 中等待执行(await)
- c# - WPF 非阻塞 UI 弹出窗口
- javascript - 在 javascript 中创建树的修剪副本
- java - 在 SQLite 中搜索会显示除我的搜索词之外的所有项目
- python - 在python中使用方法的方法
- sql - 我无法获得正确的值 (EBS ORACLE) - 地址
- macos - 如何在 Swift 中为 macOS 实现侧边栏?
- ruby - nil:NilClass (NoMethodError) 的未定义方法 `children'
- java - Rewriting RegEx to be used in Java
- c++ - c++中对象的生命周期