【问题标题】:php fileuploader basenamphp文件上传basename
【发布时间】:2012-10-20 15:24:56
【问题描述】:

嘿,伙计们,我已经创建了 jquery ajax 文件上传器,但我有一个问题,那就是服务器端,它会覆盖任何具有相同名称的文件并且我将生成一个随机数,它应该是与另一个不同,但我的上传器的代码是

<?php
$target_path = "/var/www/vhosts/grubber.co.nz/httpdocs/developer/_social_development/uploads/blog/";
$target_path = $target_path . basename( $_FILES['img']['name']); 


if (file_exists($target_path)) {
    echo "The file $filename exists";
    $target_path = "/var/www/vhosts/grubber.co.nz/httpdocs/developer/_social_development/uploads/blog/" . basename( $_FILES['img']['name']); 
} else {
    echo "The file $filename does not exist";
}


if(move_uploaded_file($_FILES['img']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['img']['name']). 
    " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
}
?>

问题,我希望它检查文件是否存在,是否生成随机数并将其添加到名称中? if not just continue 并写入文件。

【问题讨论】:

    标签: php


    【解决方案1】:

    一种解决方案是在文件名前添加一些唯一编号。

    您可以使用 uniqid() 函数。 http://php.net/manual/en/function.uniqid.php

    <?php
    $target_path = "/var/www/vhosts/grubber.co.nz/httpdocs/developer/_social_development/uploads/blog/";
    $target_path = $target_path . basename( $_FILES['img']['name']); 
    
    
    if (file_exists($target_path)) {
        echo "The file $filename exists";
        $target_path = "/var/www/vhosts/grubber.co.nz/httpdocs/developer/_social_development/uploads/blog/" .uniqid().basename( $_FILES['img']['name']); 
    } else {
        echo "The file $filename does not exist";
    }
    
    
    if(move_uploaded_file($_FILES['img']['tmp_name'], $target_path)) {
        echo "The file ".basename( $_FILES['img']['name']). 
        " has been uploaded";
    } else{
        echo "There was an error uploading the file, please try again!";
    }
    ?>
    

    【讨论】:

    • 这不起作用它只是弹出一个错误“文件存在致命错误:调用/var/www/vhosts/grubber.co.nz/httpdocs/developer中的未定义函数uniqueid() /_social_development/json/uploadblog.php 第 8 行"
    猜你喜欢
    • 1970-01-01
    • 2014-07-14
    • 2011-01-26
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多