How can I turn $_FILES["fileToUpload"]["tmp_name"]
into a variable to be used in a move_uploaded_file?
This works:
$filename = compress_image(($_FILES["fileToUpload"]["tmp_name"]), $url, 30);
But I am trying to get something like this:
$filename = compress_image($images, $url, 30);
But, when do above it does not work.
One alternative I was starting on was:
file_put_contents($target_file , $image);
In that case, the image was named into directory properly, but the image was always broken.
To clarify:
Need to turn ($_FILES["fileToUpload"]["tmp_name"]) into a variable that is result of
ob_start(); echo imagejpeg($image,null,30);
$image =ob_get_clean();
ob_end_clean();
$image = addslashes($image);
I need to use $image to save to directory. $image has been successfully stored into mysql. I have tried encode, and decode on $image, still no luck.
Let me explain the problem step-by-step:
The mess starts at this line:
$image = imagecreatefromstring(file_get_contents($_FILES['fileToUpload']['tmp_name']));
Problems:
move_uploaded_file()
first file_get_contents()
is unnecessary; you can use imagecreatefromjpeg()
(and other formats, like GIF, PNG, etc) to replace the imagecreatefromstring(file_get_contents())
things Here is your compress_image()
function:
function compress_image($source_url, $destination_url, $quality) {
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source_url);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($source_url);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source_url);
}
imagejpeg($image, $destination_url, $quality);
return $destination_url;
}
Problems:
imagejpeg()
will fail (but you didn't cater it; always check the return value of function) $destination_url
is writable & exist or not Next, assumes the compress_image()
works well and returns $destination_url
with a valid JPEG created at the path, the following codes cause further problems:
$sql = "INSERT INTO fffdf (`user_id`,`imit`) VALUES ('9','$image')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Problems:
$image
directly into DB? It's a very bad practice to store image data in DB. Save the path instead whenever possible $image
is inaccessible here; the scope of the $image
stays in the function compress_image()
, thus $image
still contains the value before compress_image()
, unless you use global $image;
in the compress function (which is not suggested). Pass the $image
as function parameters by reference:
function compress_image(&$image, $destination_url, $quality)
you don't really need the $source_url
if you have the image data stored in $image
.
Hope the above helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.