我有这个代码用于上传图像和存储在数据库中 我想首先将其重命名为随机名称,然后上传并存储在数据库中 我应该如何更改我的代码? 请帮我! 这是我的PHP代码:
$imageFile=$_FILES['image'];
$file_name = $imageFile['name'];
$target_path = "images/news/".$file_name;
if(move_uploaded_file($imageFile['tmp_name'], $target_path)) {
echo "<div id=\"news\">";
echo "Image : "."<br>".$file_name;
echo "<br>";
echo "Successfuly Uploaded!";
echo "<br>";
$newstitle = $_POST['title'];
$newscontent = $_POST['content'];
$newsimage = "images/news/".$file_name;
$sql="insert into news (news_title,news_content,news_image,news_date) values ('$newstitle', '$newscontent','$newsimage',' $newsdate')";
if ($conn->query($sql) === TRUE)
{
echo "Image Stored in DB!</div>";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
答案 0 :(得分:1)
试试这个
使用$random = md5(uniqid("") . time());
以下是重命名文件的工作代码
$imageFile = $_FILES['image'];
$file_name = $imageFile['name'];
$random = md5(uniqid("") . time());
$target_path = "images/news/" . $random.$file_name;
if (move_uploaded_file($imageFile['tmp_name'], $target_path)) {
echo "<div id=\"news\">";
echo "Image : " . "<br>". $random . $file_name;
echo "<br>";
echo "Successfuly Uploaded!";
echo "<br>";
$newstitle = $_POST['title'];
$newscontent = $_POST['content'];
$newsimage = "images/news/" . $random. $file_name;
$sql = "insert into news (news_title,news_content,news_image,news_date) values ('$newstitle', '$newscontent','$newsimage',' $newsdate')";
if ($conn->query($sql) === TRUE) {
echo "Image Stored in DB!</div>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
随时准备帮助你