refresh image on upload - php

I have a script which uploads an image to the server under the id of the user. To change teh picture the first gets overwritten. The problem is that the old picture, with the dimensions of the new one, shows for a while until they refresh their browser. How can I prevent this from happening?
Script:
function uploadProfilePicture($memberID,$extension)
{
##### FIND ERRORS #####
$error = "";
// check if larger than 5mb
$avatar = $_FILES['uploadedAvatar'];
if( $avatar["size"] > 5000000 ){ //5mb
$error = SETTINGSphoto_less_5meg;
}
//check if member selected a photo
if( $avatar['name'] == "" ){
$error = SETTINGSphoto_no_upload;
}
//check if photo is of allowed formats
if( $avatar["type"] != "image/png" ){
if( $avatar["type"] != "image/gif" ){
if( $avatar["type"] != "image/jpg" ){
if( $avatar["type"] != "image/jpeg" ){
if( $avatar["type"] != "image/pjpeg" ){
$error = SETTINGSphoto_file_type;
}
}
}
}
}
#### END FIND ERRORS #####
##### DISPLAYS ERRORS ######
if( $error != ""){
echo '<span style="background-color:#E05641;" class="pint2">'.$error.'</span>';
##### END DISPLAYS ERRORS ######
##### PROCESS THUMBNAIL AND UPLOAD PICTURE #####
}else{
$ext = substr($avatar["name"], -4); //take off extention.
$fileName = $memberID.$extension.$ext; // rename picture with member's ID.w
unlink("photos/".$memberID.$extension.".jpg");
unlink("photos/".$memberID.$extension."Thumb.jpg");
copy($avatar['tmp_name'], "photos/".$fileName); //upload temp
//create virual image
if(preg_match('/[.](jpg)$/',strtolower($avatar["name"]))) {
$im = imagecreatefromjpeg("photos/".$fileName);
} else if (preg_match('/[.](gif)$/', strtolower($avatar["name"]))) {
$im = imagecreatefromgif("photos/".$fileName);
} else if (preg_match('/[.](png)$/', strtolower($avatar["name"]))) {
$im = imagecreatefrompng("photos/".$fileName);
} else if (preg_match('/[.](jpeg)$/',strtolower($avatar["name"]))) {
$im = imagecreatefromjpeg("photos/".$fileName);
}else{
$im = imagecreatefromjpeg("photos/".$fileName);
}
//get height and width
$ox = imagesx($im); $oy = imagesy($im);
$final_width_of_image = 200;
$final_height_of_image = 200;
//$ratio = $final_width_of_image / $ox; //find ratio to apply to height
//$nx = $final_width_of_image; $ny = $oy * $ratio;
if( $ox < $oy ){
$nx = 200;
$ny = floor($oy * (200 / $ox));
}else{
$ny = 200;
$nx = floor($ox * (200 / $oy));
}
//$nm = imagecreatetruecolor($nx, $ny);
//imagecopyresampled($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy); //create new pic
$nm = imagecreatetruecolor($nx, $ny);
imagecopyresampled($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
unlink("photos/".$fileName); //delete temp image
imagejpeg($nm, "photos/".$memberID.$extension.".jpg",100); //save image // 100 = quality
$im = imagecreatefromjpeg("photos/".$memberID.$extension.".jpg");
$nm = imagecreatetruecolor(200, 200);
imagecopyresampled($nm, $im,0,0,0,0,200,200,200,200);
imagejpeg($nm, "photos/".$memberID.$extension."Thumb.jpg",100);
$sql = "UPDATE exchange SET photo = 1 WHERE id = '$memberID'"; //update db
$mysql = new mysql();
$mysql->query($sql);
##### END PROCESS THUMBNAIL AND UPLOAD PICTURE #####
echo '<span class="pint2">'.SETTINGSphoto_chage_success.' <a style="color:#ffffff" href="'.$_ENV['rootURL'].'/'.( in_array($_GET['lang'],$_ENV['supportedLanguages']) ? $_GET['lang']."/" : $nothing).HEADlanguage_exchange.'/id/'.$memberID.'">'.SETTINGSphoto_view_profile.'</a></span>';
}
}

The problem is that the old picture, with the dimensions of the new one, shows for a while until they refresh their browser. How can I prevent this from happening?
You can solve this by telling the user she should clear the browser cache.
If that is not an option, you want to actually prevent the user to cache the image.
So you need to make a difference between each revision of the image. Add a integer field to your database you store the revision number of the image. Then each time you output the user's image, fetch the actual revision number from the database as well. Add it as the query-info-part of the image URL:
<img src="avatars/user/929292/photo.jpg?revision">
^^^^^^^^
The browser will still cache profile pictures but you make him aware of the revision, so a specific revision is cached.
Old avatar picture:
<img src="avatars/user/929292/photo.jpg?1">
Then the user uploads a new image, you increment the revision field, the new avatar image is:
<img src="avatars/user/929292/photo.jpg?2">
If the revision changes, the browser notices that and will pick the image from the server.

You could give the new image a slightly different filename, so the browser loads the new image rather than using the old cached one.

In your PHP code for the image source you can append a timestamp to force the photo to always appear as a new photo. Throw some logic in to only do this for updated records and you'll be more cache friendly.
<img src="your_profile_url.jpg?<?= time(); ?>"/>

Related

PHP Upload and Resize Image copyresample issue. Image saves all BLACK

Image upload seems to be working, however the end result file is all black area. No image.
The size seems correct, but the new image is just blank.
Any input greatly appreciated. This may be something simple that I am overlooking, I just need a second set of eyes.
/***** IMAGE UPLOAD VARIABLES *****/
// Destination
$main_dest = "../test_img/";
$thumb_dest = "../test_img/thumb/";
// Main Image Width
$new_img_width = "650";
// Thumb Image Width
$new_img_thumb_width = "100";
// Allowed Filesize (5mb)
$allowed_img_size = "5000000";
// Define Error Message
$error = "";
/***** EVENT EXISTING IMAGE INFO *****/
// Get image count
$get = "SELECT * FROM `tbl_event_imgs` WHERE `event_id` = '".$event_id."'";
$result = mysqli_query($database_link, $get);
$count = mysqli_num_rows($result);
// Main Setting
if ($count == 0) { $main = 1; } else { $main = 0; }
/***** IMAGE INFORMATION *****/
// Get image temporary name
$img_tmp = $_FILES['event_image']['tmp_name'];
// Get image name (original)
$img_name = basename($_FILES['event_image']['name']);
// Get image extension
$img_ext = pathinfo($img_name, PATHINFO_EXTENSION);
// Get image size
$img_size = $_FILES['event_image']['size'];
// Final image destination
$final_main_dest = $main_dest.$img_name;
/***** IMAGE VALIDATION *****/
// Validate Image Type (jpg, jpeg, gif, png)
if (($img_ext !== "jpg") && ($img_ext !== "jpeg") && ($img_ext !== "gif") && ($img_ext !== "png")) {
$upload_error = 1;
$error .= "filetype";
}
// Validate Image Size (5mb Allowed)
if ($img_size > $allowed_img_size) {
$upload_error = 1;
$error .= "filesize";
}
/**** BEGIN UPLOAD *****/
// Set src image (by ext)
if (($img_ext == "jpg" ) || ($img_ext == "jpeg")) {
$src_img = imagecreatefromjpeg($img_tmp);
} elseif ($img_ext == "png") {
$src_img = imagecreatefrompng($img_tmp);
} elseif ($img_ext == "gif") {
$src_img = imagecreatefromgif($img_tmp);
}
// Get src image height and width
$src_img_width = imagesx($src_img);
$src_img_height = imagesy($src_img);
// Set "desired" height
$new_img_height = floor($src_img_height * ($new_img_width / $src_img_width));
// Create Virtual Images
$virtual_main_img = imagecreatetruecolor($new_img_width, $new_img_height);
// Resize source image
imagecopyresampled($virtual_main_image, $src_img, 0, 0, 0, 0, $new_img_width, $new_img_height, $src_img_width, $src_img_height);
// Save final images
imagejpeg($virtual_main_img, $final_main_dest);
Ended up being simple:
$virtual_main_img was defined variable.
I inadvertently used "$virtual_main_image".
Works.

PHP EXIF Process IFD TAG Remote Integer Overflow

Background:
I have been working on an issue whereby a file upload form will only accept certain images, it is not a problem with image size(dimensions) or with size(filesize) but I think i've found it's to do with image bit depth, as the PHP script resizes the image and applies a static (semi-transparant) watermark file to the image and saves the result.
I have gone through a long process today and yesterday working with this as the error that occurs is the server stating "Connection reset by server" . Which I think I've narrowed down to the server not having enough free memory to complete the image resource manipulations.
Issue:
Then, after all that, this error comes up on file upload submission:
IPS detected for "WEB PHP EXIF Process IFD TAG Remote Integer Overflow -2 (CVE-20/Buffer Over Flow"
Some googling only tells me that it's a securty vulnerabiliy for PHP < 4.2 or so, and doesn't relate to actually what's going on.
I have looked through my code and am very sure that
My query is to try and shed some light on what this error statement means (and how I can go about correcting it)?
Notes:
PHP 5.6.16
No PHP EXIF functions run on the page.
I can't see anywhere on the page that would cause an integer overflow (running to infinity, I guess)
Page does use imagecopy, imagealphablending and imagesavealpha But this error notice seems to appear before the script runs on the uploaded file.
This error only occurs on some uploaded images and not on others.
I have found no Apache error logs relating to this
I have no PHP errors recorded.
Code:
As I think the issue may occur somehow before the page loads I'm not sure how useful this code block will be but, take a look:
(also please note that I am aware this page is 5 years old and isn't the smartest programming, i have fixed it up in parts but am aware it can probably be further tidied)
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
///first set out variables.
$goodImage = 0;
$maxfilesize = (int)$_POST['MAX_FILE_SIZE'];
$gallery = (int)$_POST['galfolderid']
if (empty($gallery)) {
$_SESSION['message'] = $gallery . "<br/>Gallery Value has not been set.";
}
elseif (!is_numeric($gallery)) {
$_SESSION['message'] = $gallery . "<br/>Gallery Value is not a numeric value.";
}
elseif (!is_dir($_SERVER['DOCUMENT_ROOT']."/images/gallery/" . $gallery )) {
$_SESSION['message'] = $gallery . "<br/>Gallery Value, while being a number, is not a valid numeric value.";
}
if(!empty($_SESSION['message'])) {
header("Location:editgallery.php?gallery=".$galleryid);
exit;
}
for($count=0;$count<5;$count++) {
if ($_FILES['image']['error'][$count] == 0) {
clearstatcache();
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$imageType = finfo_file($finfo, $_FILES['image']['tmp_name'][$count]);
finfo_close($finfo);
unset($finfo);
if (strtolower($imageType) == "image/png") {
$imgtype = "PNG";
$original = imagecreatefrompng($_FILES['image']['tmp_name'][$count]);
} elseif (strtolower($imageType) == "image/jpeg" || strtolower($imageType) == "image/jpg") {
$imgtype = "JPG";
$original = imagecreatefromjpeg($_FILES['image']['tmp_name'][$count]);
} else {
//not a JPG or PNG type... set error.
$_SESSION['message'] = "Image " . ($count+1) . " does not appear to be a valid .JPG or .PNG file. ";
error_log($_SESSION['message']);
header("Location:editgallery.php");
exit;
}
unlink($_FILES['image']['tmp_name'][$count]);
$edgePadding = (int)$_POST['WMedge'][$count]; //integer
$watermarkScale = $_POST['WMscale'][$count]; //float
$h_position = $_POST['Hpos'][$count]; //text array
$v_position = $_POST['Vpos'][$count]; //text array
$Hoz = $h_position[0];
$Vez = $v_position[0];
if (!isset($watermarkScale) || empty($watermarkScale) || !is_numeric($watermarkScale)) {
$watermarkScale = 1.0;
}
elseif($watermarkScale > 2.0) {
$watermarkScale = 2.0;
}
elseif($watermarkScale < 0.5) {
$watermarkScale = 0.5;
}
if ((!isset($edgePadding) || empty($edgePadding) || !is_numeric($edgePadding)) && $edgePadding !== "0") {
$edgePadding = 5;
}
// be sure that the other options we need have some kind of value
if ($_FILES['image']['size'][$count] > $maxfilesize) {
$_SESSION['message'] .= "Image file ".($count+1)." appears to be too big. There is a limit of 2Mb on the
size of the image you can upload. Please click 'Back' on your browser and resubmit a valid image.";
error_log($_SESSION['message']);
//file too big.
}
//target name is the number of images in the LARGE gallery,
///cycle through imagenames to find the first "clear" image number.
$newimagename = 1;
clearstatcache();
/***
NOTE: Only possible place an integer oveflow might occur I think
***/
while (file_exists($_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $gallery . "/S/" . $newimagename . ".jpg")) {
$newimagename++;
}
///newimagename is the new filename of the image.
$target_name = $newimagename . ".jpg";
$target = $_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $gallery . "/L/" . $target_name;
$targetSmall = $_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $gallery . "/S/" . $target_name;
//targetSM is used below to make the thumbnail image. for the SMALL gallery.
//full target directory and name.
// file upload success
// now file need resizing before the watermark is applied.
// resize new dimensions (Large- 800px)
$originalImageSize[0] = imagesx($original);
$originalImageSize[1] = imagesy($original);
/***
* Resize new dimensions for small thumbnail.
***/
if ($originalImageSize[0] > 133) {
$percent = 133 / $originalImageSize[0];
} else {
$percent = 1;
}
$newThumbHeight = $originalImageSize[1] * $percent;
$newThumbWidth = $originalImageSize[0] * $percent;
// Resample
$imageThumbFinal = imagecreatetruecolor($newThumbWidth, $newThumbHeight);
imagecopyresampled($imageThumbFinal, $original, 0, 0, 0, 0, $newThumbWidth, $newThumbHeight, $originalImageSize[0], $originalImageSize[1]);
// Output
imagejpeg($imageThumbFinal, $targetSmall, 80);
imagedestroy($imageThumbFinal);
unset($imageThumbFinal, $percent,$newThumbWidth,$newThumbHeight);
/***
* End Thumbnail generation.
*/
/***
* Resize main sized image (max 800px wide)
***/
if ($originalImageSize[0] > 800) {
$percent = 800 / $originalImageSize[0];
} else {
$percent = 1;
}
$newPictureHeight = $originalImageSize[1] * $percent;
$newPictureWidth = $originalImageSize[0] * $percent;
// Resample main image to reduce max size.
$imageCleanFinal = imagecreatetruecolor($newPictureWidth, $newPictureHeight);
imagecopyresampled($imageCleanFinal, $original, 0, 0, 0, 0, $newPictureWidth, $newPictureHeight, $originalImageSize[0], $originalImageSize[1]);
/***
* Now resize the watermark and save onto the final image.
***/
//full target directory and name.
$watermark = $_SERVER['DOCUMENT_ROOT'] . "/images/watermark2.png";
$wmTarget = substr($watermark, 0, -3) . "tmp"; //image/watermark2.tmp is resized.
$sourceWaterImage = imagecreatefrompng($watermark);
$waterMarkWidth = imagesx($sourceWaterImage);
$waterMarkHeight = imagesy($sourceWaterImage);
$destinationHeight = $waterMarkHeight * $watermarkScale;
$destinationWidth = $waterMarkWidth * $watermarkScale;
$destinationHeight = floor($destinationHeight);
$destinationWidth = floor($destinationWidth);
$destinationWatermarkImage = imagecreatetruecolor($destinationWidth, $destinationHeight);
imagealphablending($destinationWatermarkImage, FALSE);
imagesavealpha($destinationWatermarkImage, TRUE);
imagecopyresampled($destinationWatermarkImage, $sourceWaterImage, 0, 0, 0, 0, $destinationWidth,
$destinationHeight, $waterMarkWidth, $waterMarkHeight);
imagedestroy($sourceWaterImage);
unset($sourceWaterImage);
clearstatcache();
/***
* Set watermark location on final image.
***/
$differenceX = $newPictureWidth - $destinationWidth;
$differenceY = $newPictureHeight - $destinationHeight;
switch ($Hoz) {
// find the X coord for placement
case 'left':
$placementX = $edgePadding;
break;
case 'center':
$placementX = round($differenceX / 2);
break;
case 'right':
$placementX = $newPictureWidth - ($destinationWidth + $edgePadding);
break;
default:
$placementX = 0;
break;
}
switch ($Vez) {
// find the Y coord for placement
case 'top':
$placementY = $edgePadding;
break;
case 'middle':
$placementY = round($differenceY / 2);
break;
case 'bottom':
$placementY = $newPictureHeight - ($destinationHeight + $edgePadding);
break;
default:
$placementY = 0;
break;
}
/***
* Finish set Watermark location
***/
imagecopy($imageCleanFinal,
$destinationWatermarkImage,
$placementX,
$placementY,
0,
0,
$destinationWidth,
$destinationHeight);
imagejpeg($imageCleanFinal, $target, 80);
/***
* Image final save
***/
// Output
imagejpeg($imageCleanFinal, $target, 80);
imagedestroy($imageCleanFinal);
imagedestroy($destinationWatermarkImage);
unset($imageCleanFinal, $percent);
unlink($wmTarget);
$output[$goodImage]['targetName'] = $target_name;
$output[$goodImage]['targetAddr'] = $target;
$goodImage++;
} elseif (!isset($_FILES['image']['name'][$count]) || ($_FILES['image']['error'][$count] != 0 && $_FILES['image']['error'][$count] != 4)) {
//error in file upload.
$_SESSION['message'] .= " There is a file upload error number " . $_FILES['image']['error'][$count] . ". for image ".($count+1).".
Please try resubmitting a valid image.";
error_log($_SESSION['message']);
}
}
if (empty($_SESSION['message'])){
$_SESSION['message'] = $goodImage." New Image(s) Uploaded";
}
// display resulting image for download
header("Location:editgallery.php?special=yes&gallery=".$galleryid);
exit;
Server Details:
Apache 2.4
WebHostManger & CPanel (combined) version 54.0.19
PHP 5.6 using Mod suPHP 0.7.2
2 core 2.2GHz (so x2) intel with
1896Mb/2097Mb physical memory (used/available)
+4095Mb memory Swap File. (~6010Mb total)

I'm getting Forbidden error

I have a board_directors.php page,
When I update my page from admin panel, It' showing
Forbidden
You don't have permission to access /new/admin/board_directors.php on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
Here has 6 form fields and 2 textarea field.
and my code is:
if(isset($_REQUEST['submitted']) && $_GET['edit'] == "yes"){
$id = $_GET['id'];
$yes = $_GET['edit'];
$dir_sl = $_POST['dir_sl'];
$dir_name = $_POST['dir_name'];
$dir_position = $_POST['dir_position'];
$dir_email = $_POST['dir_email'];
$dir_mobile = $_POST['dir_mobile'];
$dir_details = $_POST['dir_details'];
$file2 = $_FILES['file']['name'];
if(!empty($file2)){
$file = $_FILES['file']['name'];
// Uploade Image Directory start
$add="board_directors_images/".$_FILES['file']['name']; // the path with the file name where the file will be stored, upload is the directory name.
//echo $add;
if(move_uploaded_file ($_FILES['file']['tmp_name'],$add)){
//echo "Successfully uploaded the image";
chmod("$add",0777);
}
///////// Start the thumbnail generation//////////////
$n_width=100; // Fix the width of the thumb nail images
$n_height=140; // Fix the height of the thumb nail imaage
////////////////////////////////////////////
$tsrc="board_directors_images/thumb/".$_FILES['file']['name']; // Path where thumb nail image will be stored
/////////////////////////////////////////////// Starting of png thumb nail creation///////////
if (#$_FILES['file']['type']=="image/png")
{
$im=ImageCreateFrompng($add);
$width=ImageSx($im); // Original picture width is stored
$height=ImageSy($im); // Original picture height is stored
$n_height=($n_width/$width) * $height; // Add this line to maintain aspect ratio
$newimage=imagecreatetruecolor($n_width,$n_height);
imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
if (function_exists("imagepng")) {
Header("Content-type: image/png");
Imagepng($newimage,$tsrc);
}
elseif (function_exists("imagejpeg")) {
Header("Content-type: image/jpeg");
ImageJPEG($newimage,$tsrc);
}
chmod("$tsrc",0777);
}////////// end of png file thumb nail creation//////////
////////////// starting of JPG thumb nail creation//////////
if($_FILES['file']['type']=="image/jpeg"){
$im=ImageCreateFromJPEG($add);
$width=ImageSx($im); // Original picture width is stored
$height=ImageSy($im); // Original picture height is stored
$n_height=($n_width/$width) * $height; // Add this line to maintain aspect ratio
$newimage=imagecreatetruecolor($n_width,$n_height);
imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
ImageJpeg($newimage,$tsrc);
//chmod("$tsrc",0777);
}
} else {
$sql1 = "SELECT * FROM tbl_board_directors WHERE fld_id =' ".$_GET['id']."' limit 1";
$result1 = mysql_query($sql1);
$test = mysql_fetch_array($result1);
$file = $test['fld_pic'];
$file = $file;
}
// End upload image direcotory
$sql = mysql_query("update tbl_board_directors set fld_sl_no = '".$dir_sl."', fld_name = '".$dir_name."', fld_post = '".$dir_position."', fld_email = '".$dir_email."', fld_mobile = '".$dir_mobile."', fld_details = '".$dir_details."', fld_pic = '".$file."' where fld_id = '".$id."' ");
if($sql){
//echo "<strong style='color:green; font-size:14px;'>Board of directors Updated!</strong>";
header("Location: board_directors.php?id=".$id."&edit=".$yes."&confirm=Content Updated!");
}
}

Why is my image rotating when resizing uploaded image in PHP? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php resizing image on upload rotates the image when i don't want it to
I have created my first ever upload code and was testing it, the image resizes and uploads fine. The only issue I have is that it rotates.
Here is the code:
$errors = array();
$message = "";
if(isset($_POST["test"])){
$name = rand(1,999999) . $_FILES["uploadfile"]["name"];
$temp_name = $_FILES["uploadfile"]["tmp_name"];
$size = $_FILES["uploadfile"]["size"];
$extension = strtolower(end(explode('.', $_FILES['uploadfile']['name'])));
$path = "testupload/" . $name;
$info = getimagesize($temp_name);
$originalwidth = $info[0];
$originalheight = $info[1];
$mime = $info["mime"];
$acceptedHeight = 750;
$acceptedWidth = 0;
$acceptedMimes = array('image/jpeg','image/png','image/gif');
$acceptedfileSize = 4102314;
$acceptedExtensions = array('jpg','jpeg','gif','png');
echo $size;
// check mimetype
if(!in_array($mime, $acceptedMimes)){$errors[] = "mime type not allowed - The file you have just uploaded was a: " . $extension . " file!";}
if(!$errors){if($size > $acceptedfileSize){$errors[] = "filesize is to big - Your file size of this file is: " . $size;}}
if(!$errors){if(!in_array($extension, $acceptedExtensions)){$errors[] = "File extension not allowed - The file you have just uploaded was a: " . $extension . " file!";}}
if(!$errors){
// create the image from the temp file.
if ($extension === 'png'){
$orig = imagecreatefrompng($temp_name);
}elseif ($extension === 'jpeg'){
$orig = imagecreatefromjpeg($temp_name);
}elseif ($extension === 'jpg'){
$orig = imagecreatefromjpeg($temp_name);
}elseif ($extension === 'gif'){
$orig = imagecreatefromgif($temp_name);
}
// work out the new dimensions.
if ($acceptedHeight === 0){
$newWidth = $acceptedWidth;
$newHeight = ($originalheight / $originalwidth) * $acceptedWidth;
}else if ($acceptedWidth === 0){
$newWidth = ($originalwidth / $originalheight) * $acceptedHeight;
$newHeight = $acceptedHeight;
}else{
$newWidth = $acceptedWidth;
$newHeight = $acceptedHeight;
}
$originalwidth = imagesx($orig);
$originalheight = imagesy($orig);
// make ssure they are valid.
if ($newWidth < 1){ $newWidth = 1; }else{ $newWidth = round($newWidth ); }
if ($newHeight < 1){ $newHeight = 1; }else{ $newHeight = round($newHeight); }
// don't bother copying the image if its alreay the right size.
if ($originalwidth!== $newWidth || $originalheight !== $newHeight){
// create a new image and copy the origional on to it at the new size.
$new = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($new, $orig, 0,0,0,0, $newWidth, $newHeight, $originalwidth, $originalheight);
}else{
// phps copy on write means this won't cause any harm.
$new = $orig;
}
// save the image.
if ($extension === 'jpeg' || $extension === 'jpg'){
imagejpeg($new, $path, 100);
}else if ($save_ext === 'gif'){
imagegif($new, $path);
}else{
imagepng($new, $path, round(9 - (100 / (100 / 9))));
}
$message = $path;
Can someone please let me know what is going on?
Check the original image is actually in the orientation you expect. I work with images all day and the majority of the time it's Windows Photo Viewer showing the image in a certain orientation (reading an orientation change in the EXIF) but if you open it up in Photoshop it's different.
I tested your code with two images: one was landscape (width > height), the other was portrait (height > width). The code works.
The problem seems to be what #Tavocado said: newer cameras have a sensor to detect the orientation of the camera when the photo was taken, and they store that info in the photo. Also, newer photo viewing software reads that info back from the photo and rotates it before displaying the image. So you all the time see the image with the right orientation (sky up, earth down). However PHP functions (and the rest of the world) don't use that information and display the image as is was taken. That means that you will have to rotate yourself portrait images.
Just load your images in the browser (drag the file on the address bar) you you will see how the image is really stored in the file, without any automatic rotation.
The problem is that the image has embedded EXIF data, probably from the device that took the photo.
Investigate whether your images have embedded rotation information, using exif_read_data, and then auto-correct the rotation with a function like this.

how to modify this php script to handle png and gif uploads

I have the following script (it looks long, but well commented). Problem is, i get errors when i try to upload a png or gif image. What can i do to adjust this (easy if possible) so that it can either work with png's and gif's or convert them before trying to work with them.
This is the error that i recieve
Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error
Aparently the first part of the script is working, saving the original upload, but how should i go about this?
$idir = "images/"; // Path To Images Directory
$tdir = "images/"; // Path To Thumbnails Directory
$twidth = "125"; // Maximum Width For Thumbnail Images
$theight = "100"; // Maximum Height For Thumbnail Images
$url = $_FILES['imagefile']['name']; // Set $url To Equal The Filename For Later Use
if ($_FILES['imagefile']['type'] == "image/jpg" || $_FILES['imagefile']['type'] == "image/jpeg" || $_FILES['imagefile']['type'] == "image/pjpeg" || $_FILES['imagefile']['type'] == "image/png" || $_FILES['imagefile']['type'] == "image/gif") {
$file_ext = strrchr($_FILES['imagefile']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php
$fdate = date( 'ssU' );
$copy = copy($_FILES['imagefile']['tmp_name'], "$idir" . $fdate . "$file_ext"); // Move Image From Temporary Location To Permanent Location
if ($copy) { // If The Script Was Able To Copy The Image To It's Permanent Location
print 'Image uploaded successfully.<br />'; // Was Able To Successfully Upload Image
$simg = imagecreatefromjpeg("$idir" . "$fdate" . "$file_ext"); // Make A New Temporary Image To Create The Thumbanil From
$currwidth = imagesx($simg); // Current Image Width
$currheight = imagesy($simg); // Current Image Height
if ($currheight > $currwidth) { // If Height Is Greater Than Width
$zoom = $twidth / $currheight; // Length Ratio For Width
$newheight = $theight; // Height Is Equal To Max Height
$newwidth = $currwidth * $zoom; // Creates The New Width
} else { // Otherwise, Assume Width Is Greater Than Height (Will Produce Same Result If Width Is Equal To Height)
$zoom = $twidth / $currwidth; // Length Ratio For Height
$newwidth = $twidth; // Width Is Equal To Max Width
$newheight = $currheight * $zoom; // Creates The New Height
}
$dimg = imagecreate($newwidth, $newheight); // Make New Image For Thumbnail
imagetruecolortopalette($simg, false, 256); // Create New Color Pallete
$palsize = ImageColorsTotal($simg);
for ($i = 0; $i < $palsize; $i++) { // Counting Colors In The Image
$colors = ImageColorsForIndex($simg, $i); // Number Of Colors Used
ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']); // Tell The Server What Colors This Image Will Use
}
imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight); // Copy Resized Image To The New Image (So We Can Save It)
$fdate = date( 'ssU' );
imagejpeg($dimg, "$tdir" . "thumb_" . $fdate . "$file_ext"); // Saving The Image
$full = "$fdate" . "$file_ext";
$thumb = "thumb_" . $fdate . "$file_ext";
imagedestroy($simg); // Destroying The Temporary Image
imagedestroy($dimg); // Destroying The Other Temporary Image
print 'Image thumbnail created successfully.'; // Resize successful
} else {
print '<font color="#FF0000">ERROR: Unable to upload image.</font>'; // Error Message If Upload Failed
}
} else {
print '<font color="#FF0000">ERROR: Wrong filetype (has to be a .jpg or .jpeg. Yours is '; // Error Message If Filetype Is Wrong
print $file_ext; // Show The Invalid File's Extention
print '.</font>';
}
Any guidance here is greatly appreciated.
Well, imagecreatefromjpeg() can only create images from... jpegs. There are sister functions for creating images from other file types, namely imagecreatefrompng() and imagecreatefromgif().
I've added to your code. Give it a try. Make sure you see the changes, as I put a die() in there in case of an invalid image, which may not be what you want:
$url = $_FILES['imagefile']['name']; // Set $url To Equal The Filename For Later Use
if ($_FILES['imagefile']['type'] == "image/jpg" || $_FILES['imagefile']['type'] == "image/jpeg" || $_FILES['imagefile']['type'] == "image/pjpeg" || $_FILES['imagefile']['type'] == "image/png" || $_FILES['imagefile']['type'] == "image/gif") {
$file_ext = strrchr($_FILES['imagefile']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php
$fdate = date( 'ssU' );
$copy = copy($_FILES['imagefile']['tmp_name'], "$idir" . $fdate . "$file_ext"); // Move Image From Temporary Location To Permanent Location
if ($copy) { // If The Script Was Able To Copy The Image To It's Permanent Location
print 'Image uploaded successfully.<br />'; // Was Able To Successfully Upload Image
$cfunction = 'imagecreatefromjpeg';
if ($_FILES['imagefile']['type'] == "image/png") {
$cfunction = 'imagecreatefrompng';
} else if ($_FILES['imagefile']['type'] == "image/gif") {
$cfunction = 'imagecreatefromgif';
} else {
die("Invalid image format.");
}
$simg = $cfunction("$idir" . "$fdate" . "$file_ext"); // Make A New Temporary Image To Create The Thumbanil From
$currwidth = imagesx($simg); // Current Image Width
$currheight = imagesy($simg); // Current Image Height
if ($currheight > $currwidth) { // If Height Is Greater Than Width
$zoom = $twidth / $currheight; // Length Ratio For Width
$newheight = $theight; // Height Is Equal To Max Height
$newwidth = $currwidth * $zoom; // Creates The New Width
} else { // Otherwise, Assume Width Is Greater Than Height (Will Produce Same Result If Width Is Equal To Height)
$zoom = $twidth / $currwidth; // Length Ratio For Height
$newwidth = $twidth; // Width Is Equal To Max Width
$newheight = $currheight * $zoom; // Creates The New Height
}
$dimg = imagecreate($newwidth, $newheight); // Make New Image For Thumbnail
imagetruecolortopalette($simg, false, 256); // Create New Color Pallete
$palsize = ImageColorsTotal($simg);
for ($i = 0; $i < $palsize; $i++) { // Counting Colors In The Image
$colors = ImageColorsForIndex($simg, $i); // Number Of Colors Used
ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']); // Tell The Server What Colors This Image Will Use
}
imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight); // Copy Resized Image To The New Image (So We Can Save It)
$fdate = date( 'ssU' );
imagejpeg($dimg, "$tdir" . "thumb_" . $fdate . "$file_ext"); // Saving The Image
$full = "$fdate" . "$file_ext";
$thumb = "thumb_" . $fdate . "$file_ext";
imagedestroy($simg); // Destroying The Temporary Image
imagedestroy($dimg); // Destroying The Other Temporary Image
print 'Image thumbnail created successfully.'; // Resize successful
} else {
print '<font color="#FF0000">ERROR: Unable to upload image.</font>'; // Error Message If Upload Failed
}
} else {
print '<font color="#FF0000">ERROR: Wrong filetype (has to be a .jpg or .jpeg. Yours is '; // Error Message If Filetype Is Wrong
print $file_ext; // Show The Invalid File's Extention
print '.</font>';
}

Categories