【发布时间】:2015-12-04 17:26:14
【问题描述】:
我有以下脚本可以为我的文件名生成一个随机时间戳。
$newfilename = round(microtime(true)) . ".jpg";
但是上传到我的mySQL数据库的文件名和我的目录中记录的不同,导致图片无法显示。
例如,有一次,数据库中的图像记录为1441743610.jpg,而目录中的图像记录为1441743609.jpg。
这是我的代码:
session_start();
$username = $_SESSION['username'];
$file_dir = "userpictures/$username" ;
mkdir($file_dir, 0777, true);
// $_FILES["file"]["name'] is the file that is uploaded by her
$filePath = $_FILES["file"]["name"];
$image = imagecreatefrompng($filePath);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = 100; // 0 = worst / smaller file, 100 = better / bigger file
imagejpeg($bg, $filePath . ".jpg", $quality);
imagedestroy($bg);
// this chunk here converts the file to jpg
$newfilename = round(microtime(true)) . ".jpg";
// round(microtime) generates a randomized number.
// check format of image before uploading
$imageFileType = pathinfo($newfilename,PATHINFO_EXTENSION);
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" )
{
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
else
{
$uploadOk = 1;
}
// if any errors have occured (determined by $uploadOk), the critical "move_uploaded_files" php function is not activated
if ($uploadOk == 1)
{
$filename = $newfilename;
move_uploaded_file($_FILES["file"]["tmp_name"], "user_pictures/$username/" . $filename);
}
希望能就发生这种情况的原因提供建议。请注意,这种行为并不一致,它大部分时间都有效。,但这对我来说是不可接受的。
编辑:
这是我将$filename 上传到数据库(以及其他数据)的代码
$con = mysqli_connect("FARM.mysql.anyhost.com", "user", "password");
if (!$con) {
die("Something went wrong. Don't worry, just refresh the page"); }
mysqli_select_db($con, "FARM");
if (mysqli_select_db($con, "FARM") == false) {
die("Something went wrong. Don't worry, just refresh the page"); }
$username = $_SESSION['username'];
$post = mysqli_real_escape_string($con, $_POST['postdescription']);
$timestamp = date("jS \of F Y h:i:s A P");
$user_uploadposts = "INSERT INTO $username (PostingTime, Image, Description) VALUES ('$timestamp','$filename', '$post')";
mysqli_query($con, $user_uploadposts);
mysqli_close($con);
【问题讨论】: