加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

在上传PHP Mysql期间重命名图像

发布时间:2020-12-13 17:45:19 所属栏目:PHP教程 来源:网络整理
导读:使用以下代码可以有人向我解释如何在上传过程中将图像文件重命名为misc名称? 这是我正在使用的. uploader.php ?phpinclude($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");$dataType = mysql_real_escape_string($_POST["dataType"]);$title =
使用以下代码可以有人向我解释如何在上传过程中将图像文件重命名为misc名称?

这是我正在使用的.

uploader.php

<?php
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
$dataType = mysql_real_escape_string($_POST["dataType"]);
$title = mysql_real_escape_string($_POST["title"]);
$fileName = basename($_FILES["image"]["name"]);
$target_path = ($_SERVER['DOCUMENT_ROOT'] . "/images/gallery/".$fileName);
if (file_exists($target_path))
{
    echo "An image with that file name already exists.";
}
elseif (move_uploaded_file($_FILES["image"]["tmp_name"],$target_path))
{
    // The file is in the images/gallery folder. Insert record into database by
    // executing the following query:
     $sql="INSERT INTO images (data_type,title,file_name)"."VALUES('$dataType','$title','$fileName')";
     $retval = mysql_query($sql);

    echo "The image was successfully uploaded and added to the gallery :) <a href='index.php'>Add another image</a>";


}
else
{
    echo "There was an error uploading the file,please try again!";
}
?>

然后,这是我将图像上传到图库的代码.

<form enctype="multipart/form-data" action="uploader.php" method="POST">


        Category: <select class="text" name="dataType">
        <option value="treeremoval" selected="selected">treeremoval</option>
        <option value="treetrimming" >treetrimming</option>
        <option value="treebracing" >treebracing</option>
        <option value="stumpgrinding" >stumpgrinding</option>
        <option value="firewood" >firewood</option>
        <option value="cleanup" >cleanup</option>
        </select><br />
<br />




    Caption: <input type="text" name="title"><br />
<br />

    Image to upload: <input type="file" name="image"><br />
<br />




    <input type="submit" value="Upload">
</form>

我是非常新的使用PHP和MySQL,所以任何帮助将不胜感激.我也有其他一些问题,但我想我应该一次问一个问题. =)

谢谢!

解决方法

我会尝试这样的事情,你将创建一个唯一的id并将文件的扩展名附加到它,如果你存在该名称,直到你有一个不存在,然后你移动文件.

<?php
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");

$dataType = mysql_real_escape_string($_POST["dataType"]);
$title = mysql_real_escape_string($_POST["title"]);

$fileData = pathinfo(basename($_FILES["image"]["name"]));

$fileName = uniqid() . '.' . $fileData['extension'];

$target_path = ($_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $fileName);

while(file_exists($target_path))
{
    $fileName = uniqid() . '.' . $fileData['extension'];
    $target_path = ($_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $fileName);
}

if (move_uploaded_file($_FILES["image"]["tmp_name"],please try again!";
}

?>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读