我一直在处理图片上传,我想知道为什么这不能正常工作?如果文件已经存在,它不会使用新名称移动/上传文件。
if(isset($_REQUEST['submit'])){
$filename= $_FILES["imgfile"]["name"];
if ((($_FILES["imgfile"]["type"] == "image/gif")|| ($_FILES["imgfile"]["type"] == "image/jpeg") || ($_FILES["imgfile"]["type"] == "image/png") || ($_FILES["imgfile"]["type"] == "image/pjpeg")) && ($_FILES["imgfile"]["size"] < 20000000)){
$loc = "userpics/$filename";
if(file_exists($loc)){
$increment = 0;
list($name, $ext) = explode('.', $loc);
while(file_exists($loc)) {
$increment++;
$loc = $name. $increment . '.' . $ext;
$filename = $name. $increment . '.' . $ext;
}
move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$loc");
}
else{
move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$filename");
}
}
else{
echo "invalid file.";
}
}
答案 0 :(得分:3)
您已在$loc
中添加了文件夹路径,然后尝试将文件移至userpics/$loc
,这可能不正确。见评论:
$filename = "example.jpg";
$loc = "userpics/$filename";
if(file_exists($loc)){
$increment = 0;
list($name, $ext) = explode('.', $loc);
while(file_exists($loc)) {
$increment++;
// $loc is now "userpics/example1.jpg"
$loc = $name. $increment . '.' . $ext;
$filename = $name. $increment . '.' . $ext;
}
// Now you're trying to move the uploaded file to "userpics/$loc"
// which expands to "userpics/userpics/example1.jpg"
move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$loc");
} else {
// ...
作为一般调试提示,始终检查函数的返回值以查看它是否成功。其次,如果函数的输入值失败,则显示该函数的输入值。它将使调试事项变得更加容易。
答案 1 :(得分:0)
试试这个:
$fullpath = 'images/1086_002.jpg';
$additional = '1';
while (file_exists($fullpath)) {
$info = pathinfo($fullpath);
$fullpath = $info['dirname'] . '/'
. $info['filename'] . $additional
. '.' . $info['extension'];
}
感谢此处:Clickie!!