【问题标题】:If file doesnt exist loop (PHP)如果文件不存在循环(PHP)
【发布时间】:2013-09-10 18:27:58
【问题描述】:

我希望人们在我的网站上上传照片,并将每张照片保存为随机文件名。我创建了上传表单。这是上传php函数:

if($_FILES['myprofilepicture']['type']!='image/jpeg' && $_FILES['photo']['type']!='image/jpg' && $_FILES['photo']['type']!='image/png'){header("location:wrongfile.php");}else{
$info = pathinfo($_FILES['photo']['name']);
$randomfile = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"),0,$length);
$target = 'picture/'.$randomfile; $now=time();
move_uploaded_file( $_FILES['myprofilepicture']['tmp_name'], $target);
mysql_query("Insert into photos(name,photo,date)values('$myname','$randomfile','$now')")or die('database error occured');
header("location:home.php");

问题是,如果之前上传过同名的图片,会被覆盖,我想改进一下代码 如果之前没有上传具有相同文件名的照片->保存照片 如果之前上传了同名的照片->生成另一个随机字符串并继续循环,直到之前没有上传过同名的照片,然后保存照片

有什么帮助吗?

【问题讨论】:

  • 请正确格式化您的代码
  • 学习使用段落。正确格式化您的代码,然后我们可以提供帮助。

标签: php mysql file loops


【解决方案1】:

使用file_exists()函数检查文件是否存在:

if($_FILES['myprofilepicture']['type'] != 'image/jpeg' && 
   $_FILES['photo']['type'] != 'image/jpg' && 
   $_FILES['photo']['type'] != 'image/png')
{
    header("location: wrongfile.php");
}
else
{    
    $info = pathinfo($_FILES['photo']['name']);     
    $randomfile = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"),0,$length);
    $target = 'picture/'.$randomfile; 

    if(!file_exists($target))  //if file doesn't exist
    {       
        $now = time();
        move_uploaded_file( $_FILES['myprofilepicture']['tmp_name'], $target);
        mysql_query("Insert into photos(name,photo,date)values('$myname','$randomfile','$now')")or die('database error occured');
        header("location:home.php");
    }

}

上面这段代码中的if条件语句会检查文件是否已经存在,如果不存在,则执行块中的语句。但是,如果您想重复该过程直到找到唯一的文件路径,您可以使用循环代替:

while(!file_exists($target))  
{       
    # code ...
}

附带说明:您当前正在将用户输入直接插入到 SQL 查询中。这是一种非常糟糕的做法,它会使您的查询容易受到SQL injection 的攻击。您应该停止使用已弃用的 mysql_* 函数并开始使用 PDO 或 MySQLi。

【讨论】:

    猜你喜欢
    • 2022-11-15
    • 2021-04-17
    • 2012-02-17
    • 2013-02-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 2012-12-07
    相关资源
    最近更新 更多