Possible Xamp or script error? - php

First time uploading image and getting this error. Image is .jpg. Script seems to be OK for me. So I think problem is with xamp server?
Warning: imagecreatefrompng(): 'C:\xampp\tmp\phpB42E.tmp' is not a
valid PNG file in C:\xampp\htdocs\phphph\check_image.php on line 66
The file you uploaded was not a supported filetype
I was searching on google and didnt find something usefull. So here is part of the script.
switch ($type){
case IMAGETYPE_GIF:
$image = imagecreatefromgif($_FILES['uploadfile']['tmp_name']) or
die ('The file you uploaded was not a supported filetype');
$ext = ' .gif';
break;
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($_FILES['uploadfile']['tmp_name']) or
die ('The file you uploaded was not a supported filetype');
$ext = ' .jpeg';
case IMAGETYPE_PNG:
$image = imagecreatefrompng($_FILES['uploadfile']['tmp_name']) or
die ('The file you uploaded was not a supported filetype');
$ext = ' .png';
break;
default:
die('The file you uploaded was not a supported filetype.');
}

Missing break:
$ext = ' .jpeg';
/// missing break here
case IMAGETYPE_PNG:
So you upload a jpg, and the code continues on into the PNG section, hence your error.
And so, no, it's not a problem with Xamp server... It's a PEBKAC error.

Related

I Keep getting error confirming Post is empty

I have been going round in circles with this image upload where when I submit with file selected it uploads and posts directory as expected to database,
but of course if I submit without image selected then I get an error.
So I then would would do a check so see if file input is empty however it then stops the upload even when a file is selected and if I remove it I get this error
Warning: getimagesize(): Filename cannot be empty in ....
On searching this issue and see different peoples solutions, they suggest to increase the Upload max file etc... on the wamp php.ini which I did so, and restarted and still the same issue. However there is no issue with the file size as 5.83kb and php.ini is 25mb nor is there an issue with the file type because it does upload if I remove my error check.
Either way I have been scratching my head as I can not get to confirm when empty and echo out the error that I have set and then when file is selected to post. It just gives me the above error when checking.
Below is a working version which posts as expected but displays the error if empty. I don't want it to display this error, I want to display my own error.
Any suggestions? It's driving me up the wall :(
<?php
//UPLOAD IMAGE
if(isset($_POST["UploadImage"])) {
if(is_array($_FILES)) {
$file = $_FILES['file']['tmp_name'];
$sourceProperties = getimagesize($file);
$fileNewName = time();
$folderPath = "../userImages/";
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$imageType = $sourceProperties[2];
$resized = "_resized";
$line = "_";
$original = "_original";
switch ($imageType) {
case IMAGETYPE_PNG:
$imageResourceId = imagecreatefrompng($file);
$targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
imagepng($targetLayer,$folderPath.$RegID.$line.$fileNewName.$resized. ".".$ext);
break;
case IMAGETYPE_GIF:
$imageResourceId = imagecreatefromgif($file);
$targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
imagegif($targetLayer,$folderPath.$RegID.$line.$fileNewName.$resized. ".".$ext);
break;
case IMAGETYPE_JPEG:
$imageResourceId = imagecreatefromjpeg($file);
$targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
imagejpeg($targetLayer,$folderPath.$RegID.$line.$fileNewName.$resized. ".".$ext);
break;
default:
$msg = "<div class=\"alert alert-danger\">Wrong File Format - Only JPG, PNG or GIF - Max 2 MB</div>";
exit;
break;
}
$file = #imagecreatefromjpeg($folderPath.$RegID.$line.$fileNewName.$resized. ".".$ext);
if (!$file)
{
$file= imagecreatefromstring(file_get_contents($folderPath.$RegID.$line.$fileNewName.$resized. ".".$ext));
}
echo "";
//If I want the Orignal image upload also then remove below comment
//move_uploaded_file($file, $folderPath.$RegID.$line.$fileNewName.$original. ".".$ext);
//POST TO DATABASE
$RegID;
$RegPhoto = $folderPath.$RegID.$line.$fileNewName.$resized. ".".$ext;
$sql = "UPDATE registered SET RegID = ?, RegPhoto = ? WHERE RegID = '$RegID'";
$stmt = $connect->prepare($sql);
$stmt->bind_param('is', $RegID, $RegPhoto );
$stmt->execute();
$msg = "<div class=\"alert alert-success\">Updated Profile Successfully</div>";
}
}
function imageResize($imageResourceId,$width,$height) {
$targetWidth =220;
$targetHeight =200;
$targetLayer=imagecreatetruecolor($targetWidth,$targetHeight);
imagecopyresampled($targetLayer,$imageResourceId,0,0,0,0,$targetWidth,$targetHeight, $width,$height);
return $targetLayer;
}
?>

Set the header( content-type: image/<ANY IMG FORMAT>)

The php file that handles the images I display only allows one image format, either .jpg, .png, .bmp, etc but not all. The imageName stores the file name of the image stored in the database including its format. this is my code, so far it doesn't work yet and I'm not sure if that's allowed. Can you help me fix it please?
$con = mysqli_connect("localhost","root","","tickets");
$ticket = 109;
$result = mysqli_query($con,"SELECT image, imageName FROM tix WHERE tktNum=$ticket");
while($row = mysqli_fetch_array($result))
{
$image = $row['image'];
$imageName = $row['imageName'];
$format = substr( $imageName, -3 ); //gets the last 3 chars of the file name, ex: "photo1.png" gets the ".png" part
header('content-type: image/' . $format);
}
I just used this, just indicating it's an image but without specifying image type.
header("Content-type: image");
It seems to be working just fine regardless of file type. I tested with IE, Firefox, Safari and the Android browser.
The solution is to read in the file and decide which kind of image it is and basednd on it send out the appropriate header.
$filename = basename($file);
$file_extension = strtolower(substr(strrchr($filename,"."),1));
switch( $file_extension ) {
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpeg"; break;
case "svg": $ctype="image/svg+xml"; break;
default:
}
header('Content-type: ' . $ctype);

Picture upload issue with php

I have some code that is supposed to allow the user to browse his machine for jpeg, gif, or png to upload.
My code works fine from my xampp localhost.
I have upload my code to Amazon Web Services where I have a Ubuntu 12.04 server that I installed a LAMP on. Once there the code does not work.
I have tracked down where I believe the code fails. It is at getimagesize($old_image_path) this returns a empty set.
$old_image_path = /var/www/ch23_ex1/images//leaf.gif when I select a pic from my desktop, not sure why this path shows but it worked with xampp.
Notice the echo statements that included for testing the output from these is:
allow_url_fopen = 1
/var/www/ch23_ex1/images//NChandler03.jpgbool(false) Image type = File must be a JPEG, GIF, or PNG image.
Here is the section of code where I believe the fail is:
function resize_image($old_image_path, $new_image_path,
$max_width, $max_height) {
echo "allow_url_fopen = " . ini_get("allow_url_fopen")."<br>";
// Get image type
echo $old_image_path;
//$image_info = file_get_contents($old_image_path);
$image_info = getimagesize($old_image_path);
$image_type = $image_info[2];
var_dump($image_info);
echo 'Image type = '.$image_type;
// Set up the function names
switch($image_type) {
case 2:
$image_from_file = 'imagecreatefromjpeg';
$image_to_file = 'imagejpeg';
break;
case 1:
$image_from_file = 'imagecreatefromgif';
$image_to_file = 'imagegif';
break;
case 3:
$image_from_file = 'imagecreatefrompng';
$image_to_file = 'imagepng';
break;
default:
echo $image_type;
echo 'File must be a JPEG, GIF, or PNG image.';
exit;
}
}
I found my answer posted on similar question. All I had to do was change the permissions on the images file by entering the following code into the server. This first command changes the directory to the file that holds my images file. The second command changes the permissions of the images file so that my code can write to it. I hope this helps someone else.
cd /var/www/ch23_ex1/
sudo chmod 775 images

How can find image type without extension in php? [duplicate]

This question already has answers here:
Automatic image format detection in PHP
(7 answers)
Closed 9 years ago.
I have image upload php class. This process uploaded Images(.png,jpeg,.gif).
I am using this function to find image type
function getImageType($image_name){
return end(explode('.',$mage_name));
}
if someone upload any file with fake extension . error will happen. How can i Check type of image without
checking extension?
You can use getimagesize to get the mime type, and switch on the type to create generate extension.
In code this could look like something like this:
$image_info = getImageSize($path);
switch ($image_info['mime']) {
case 'image/gif':
$extension = '.gif';
break;
case 'image/jpeg':
$extension = '.jpg';
break;
case 'image/png':
$extension = '.png';
break;
default:
// handle errors
break;
}

How to detect spoiled or crashed images after upload

How i can detect spoiled images after upload?
Im using some code like this:
$imageSize = getimagesize($tmp_name);
if(!$imageSize || !in_array($imageSize['mime'], $allowMimeType)){
$this->error = 'Bad Image';
#unlink($tmp_name);
return false;
}
$tn = imagecreatetruecolor(80, 80);
switch ($imageSize['mime']){
case 'image/jpeg':
$userphoto = imagecreatefromjpeg($tmp_name);// Error 1
break;
case 'image/png':
$userphoto = imagecreatefrompng($tmp_name);// Error 1
break;
case 'image/gif':
$userphoto = imagecreatefromgif($tmp_name);// Error 1
break;
case 'image/bmp':
$userphoto = imagecreatefromwbmp($tmp_name);// Error 1
break;
default:
$this->error = 'unknown image';
#unlink($tmp_name);
return false;
break;
}
imagecopyresampled($tn, $userphoto, 0, 0, 0, 0, 80, 80, $width, $height);// Error 2
imagejpeg($tn,'images/userphoto/'.$this->username.'.jpg',100);
chmod('images/userphoto/'.$this->username.'.jpg', 0777);
#unlink($tmp_name);
USERPROFILE::updatePhotoByUsersId($this->username.'.jpg', $this->users_id);
But some time i give 2 error tandem,
at lines that have comment // Error 1
imagecreatefromwbmp() [href='function.imagecreatefromwbmp'>function.imagecreatefromwbmp]: >'images/userphoto/4ff7db9800871.bmp' is not a valid WBMP file
imagecreatefromgif() [href='function.imagecreatefromgif'>function.imagecreatefromgif]: >'images/usersphoto/4fe70bb390758' is not a valid GIF file
at line of comment // Error 2
imagecopyresampled(): supplied argument is not a valid Image resource
I think its occurs because the file has damaged during uploading. If i'm right, how i can solve this problem? If not, What is the reason?
Before you do any further processing, you should check the return value of getimagesize() .
If getimagesize() returns a FALSE, that means it has failed and something is wrong with the file, so you should terminate. Once the image passes this check, you can continue with your processing.
As for why you are getting supplied argument is not a valid Image resource, the explaination is simple: Most likely, the image stored in $userphoto is actually FALSE because imagecreatefrompng() and other imagecreatefrom functions have failed, returning a FALSE.
Solution: Check that the uploaded image is valid with getimagesize() before continuing.
Some possible reasons as to why the uploads are failing:
Something is corrupting the images when they are written to the temp directory.
User is uploading corrupted files.
Regarding imagecreatefromwbmp() failing, it is because gd does not support BMP files. You need to convert the BMP into a format gd can work with. For example, you can use bmp2png.

Categories