【问题标题】:How can I replace an existing image in php如何在php中替换现有图像
【发布时间】:2019-07-31 20:39:18
【问题描述】:

如何使用 php 替换文件夹中的现有图像? 当我单击上传按钮时,图像只是添加到我的文件夹中,而不是替换它。您能否添加或重新排列我的代码。提前致谢。

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(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"] > 500000000000) {
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.";
}
}
?>

【问题讨论】:

标签: php image replace upload


【解决方案1】:

目前你的代码没问题,它只是将图像添加到你的文件夹中,图像的名称与你的文件名相同。

正如我检查了你的代码,你已经为现有文件添加了条件,这意味着如果你上传同名文件,那么它会向你发送一个错误。

所以只需在下面的代码注释并尝试运行。

// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}

【讨论】:

  • 该代码不是必需的,这是一种验证
  • 好的,谢谢,但是图像仍然无法替换旧图像,先生,我可以添加什么代码?抱歉这些问题,我是初学者:
  • 如果第二个文件的文件名相同则自动替换
【解决方案2】:

只需评论或删除这段代码:

来自

// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}

// Check if file already exists
// if (file_exists($target_file)) {
// echo "Sorry, file already exists.";
// $uploadOk = 0;
// }

或从您的代码中删除它...

【讨论】:

    猜你喜欢
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    相关资源
    最近更新 更多