首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用PHP重命名图像名称

用PHP重命名图像名称
EN

Stack Overflow用户
提问于 2015-01-19 18:33:02
回答 5查看 2.3K关注 0票数 0

所以我刚刚开始使用PHP,我从网上提取了一个脚本。它的设置方式是,如果文件已经存在,它将不会上传它。我想要能够重命名文件,以便它接受所有的照片。

以下是守则:

代码语言:javascript
运行
复制
    <?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

有一个if值处理先前存在的文件。我假设我会将其改为不同的If值来更改名称?谢谢你的帮忙!

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2015-01-19 18:52:55

如果上载的文件已经存在,可以重命名文件。

代码语言:javascript
运行
复制
if (file_exists($target_file)) {
    $target_file=$target_file."2";//Rename file by concating any other string
    $uploadOk = 1;
}
票数 1
EN

Stack Overflow用户

发布于 2015-01-19 18:46:09

更改这一行:

代码语言:javascript
运行
复制
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

至:

代码语言:javascript
运行
复制
$target_file = $target_dir . 'this_is_my_new_name_whooah.txt';
票数 1
EN

Stack Overflow用户

发布于 2015-01-19 19:02:15

这就是我们如何处理相同命名的图像。

代码语言:javascript
运行
复制
$fileCount = count (glob ("uploads/*.jpg"));
$name = ( $fileCount + 1) . '.jpg';
$newName = "uploads/" . $name;
$tf = fopen($newName, 'w');
fclose($tf);
move_uploaded_file($_FILES['fileField']['tmp_name'], $newName); 

希望这能帮到你!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28031324

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档