fileinfo function PHP - php

Can someone give me an example of how to use fileinfo, to replace a snippet of code such as:
($_FILES["fileToUpload"]["type"] == "image/gif"
|| $_FILES["fileToUpload"]["type"] == "image/jpeg"
|| $_FILES["fileToUpload"]["type"] == "image/png")

Using this:
$finfo = new finfo();
$fileinfo = $finfo->file($file, FILEINFO_MIME);
$fileinfo should contain the correct MIME type which you would be able to use in a snippet like that, or in a switch statement like:
switch($fileinfo) {
case "image/gif":
case "image/jpeg":
case "image/png":
// Code
break;
}

$objInfo = new finfo(FILEINFO_MIME);
list($strImageType, $strCharset) = $objInfo->file($_FILES['fileToUpload']['tmp_name']);
//then use the variable $strImageType in your conditional
if ($strImageType == "image/gif" || $strImageType == "image/jpeg" || $strImageType == "image/png") {
//code
}

Use FILEINFO_MIME_TYPE
$filename = 'example.jpeg';
// Get file info
$finfo = new finfo();
$fileinfo = $finfo->file($filename); // return JPEG image data, JFIF standard 1.01, resolution (DPI), density 72x72, segment length 16, progressive, precision 8, 875x350, frames 3
$info = $finfo->file($filename, FILEINFO_MIME); // return 'image/jpeg; charset=binary'
$type = $finfo->file($filename, FILEINFO_MIME_TYPE); // return 'image/jpeg'
switch($type)
{
case 'image/jpg':
case 'image/jpeg':
// code...
break;
case 'image/gif':
// code...
break;
case 'image/png':
// code...
default:
// error...
break;
}

Related

Convert jpg to webp using imagewebp

I'm having trouble using imagewebp to convert an image to webp.
I use this code:
$filename = dirname(__FILE__) .'/example.jpg';
$im = imagecreatefromjpeg($filename);
$webp =imagewebp($im, str_replace('jpg', 'webp', $filename));
imagedestroy($im);
var_dump($webp);
$webp returns true but when I try to view the webp-image in Chrome it just shows blank, but with the correct size. If I instead load the image and set headers with PHP (see below) it shows up, but with wrong colors (too much yellow).
$im = imagecreatefromwebp('example.webp');
header('Content-Type: image/webp');
imagewebp($im);
imagedestroy($im);
If I convert the same image with command line it works as expected.
cwebp -q 100 example.jpg -o example.webp
I'm testing this on Ubuntu 14, Apache 2.4.7 and PHP 5.5.9-1ubuntu4.4.
It works:
$jpg=imagecreatefromjpeg('filename.jpg');
$w=imagesx($jpg);
$h=imagesy($jpg);
$webp=imagecreatetruecolor($w,$h);
imagecopy($webp,$jpg,0,0,0,0,$w,$h);
imagewebp($webp, 'filename.webp', 80);
imagedestroy($jpg);
imagedestroy($webp);
I had same problem, my solution is:
$file='hnbrnocz.jpg';
$image= imagecreatefromjpeg($file);
ob_start();
imagejpeg($image,NULL,100);
$cont= ob_get_contents();
ob_end_clean();
imagedestroy($image);
$content = imagecreatefromstring($cont);
imagewebp($content,'images/hnbrnocz.webp');
imagedestroy($content);
I user this
function webpConvert2($file, $compression_quality = 80)
{
// check if file exists
if (!file_exists($file)) {
return false;
}
$file_type = exif_imagetype($file);
//https://www.php.net/manual/en/function.exif-imagetype.php
//exif_imagetype($file);
// 1 IMAGETYPE_GIF
// 2 IMAGETYPE_JPEG
// 3 IMAGETYPE_PNG
// 6 IMAGETYPE_BMP
// 15 IMAGETYPE_WBMP
// 16 IMAGETYPE_XBM
$output_file = $file . '.webp';
if (file_exists($output_file)) {
return $output_file;
}
if (function_exists('imagewebp')) {
switch ($file_type) {
case '1': //IMAGETYPE_GIF
$image = imagecreatefromgif($file);
break;
case '2': //IMAGETYPE_JPEG
$image = imagecreatefromjpeg($file);
break;
case '3': //IMAGETYPE_PNG
$image = imagecreatefrompng($file);
imagepalettetotruecolor($image);
imagealphablending($image, true);
imagesavealpha($image, true);
break;
case '6': // IMAGETYPE_BMP
$image = imagecreatefrombmp($file);
break;
case '15': //IMAGETYPE_Webp
return false;
break;
case '16': //IMAGETYPE_XBM
$image = imagecreatefromxbm($file);
break;
default:
return false;
}
// Save the image
$result = imagewebp($image, $output_file, $compression_quality);
if (false === $result) {
return false;
}
// Free up memory
imagedestroy($image);
return $output_file;
} elseif (class_exists('Imagick')) {
$image = new Imagick();
$image->readImage($file);
if ($file_type === "3") {
$image->setImageFormat('webp');
$image->setImageCompressionQuality($compression_quality);
$image->setOption('webp:lossless', 'true');
}
$image->writeImage($output_file);
return $output_file;
}
return false;
}

PHP+Image type detection

I have a email script that sends file trough attachment from server. The email is sent using phpmailer and the attached file is attached in code like this:
$_img = (object) ($img);
if (!empty($_img->src)) {
$ext = substr($_img->src, -3);
$imginfo_array = getimagesize($_img->src);
$mime_type = $imginfo_array['mime'];
switch($mime_type) {
case "image/jpeg":
$type = "image/jpeg";
break;
case "image/png":
$type = "image/png";
break;
case "image/gif":
$type = "image/gif";
break;
}
$string = file_get_contents($_img->src);
$mail->AddStringAttachment($string, $i . '.' . $ext, 'base64', $type);
}
The problem occurs when a image is not properly saved before adding it to server. If one user decides that the file 'test.jpg' shoul be 'test.png' the attached file will not be visible via email.
The $_img->src is a file saved on server.
I am trying to check for mime type but still with no success.
I want to be able to tell the script that the correct file type is the one auto detected not determined by the extension.
Could someone give me a clue about how this could be done?
$_img = (object) ($img);
if (!empty($_img->src)) {
//$ext = substr($_img->src, -3);
// better solution for get file extension (with variable length: "jpeg" or "jpeg")
$ext = pathinfo($_img->src, PATHINFO_EXTENSION);
$imginfo_array = getimagesize($_img->src);
$mime_type = $imginfo_array['mime'];
switch($mime_type) {
case "image/jpeg":
$type = "image/jpeg";
$ext = 'jpg';
break;
case "image/png":
$type = "image/png";
$ext = 'png';
break;
case "image/gif":
$type = "image/gif";
$ext = 'gif';
break;
// fix for others mime type
default:
$type = "application/octet-stream";
}
// for binary file use AddAttachment()
//$string = file_get_contents($_img->src);
//$mail->AddStringAttachment($string, $i . '.' . $ext, 'base64', $type);
// I hope that the variable $i is set from previous code
$mail->AddAttachment($_img->src, $i . '.' . $ext, 'base64', $type)
}
You can detect the type of the image with the IMAGETYPE_XXX constants at index 2 of the returned imginfo_array. The returned mime field you are using is much less reliable.
See documentation:
http://php.net/manual/en/function.getimagesize.php
Type contants:
http://php.net/manual/en/image.constants.php

Not able store docx,pdf,csv files in GridFs

I'm have using Php, MongoDb and GridFs to store and retrieve files. It works fine for images, but I want to store files with docx, pdf, csv and etc. extensions. Here is my code:
$ext = $this->getFileExt($_FILES["news_attachment"]["name"]);
switch ($ext) {
case 'pdf':
$mimeType = 'application/pdf';
break;
case 'doc':
$mimeType = 'application/msword';
break;
case 'docx':
$mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
break;
case 'xls':
$mimeType = 'application/vnd.ms-excel';
break;
case 'xlsx':
$mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
break;
case 'ppt':
$mimeType = 'application/x-mspowerpoint';
break;
case 'pptx':
$mimeType = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
break;
case 'csv':
$mimeType = 'text/csv';
break;
case 'txt':
$mimeType = 'text/plain';
break;
default:
$mimeType='application/pdf';
}
$gridFs = $this->getGridFs();
$fileData = array(
"filename" => microtime(true) . "." . $ext,
"contentType" => $mimeType);
$_id = $gridFs->storeUpload("news_attachment", $fileData);
But I get the same error message Message: error setting up file: . I've checked the file size is 78kb, $fileData is ok also. So, my question is - What else can caused this error?
Would you not be supplying the same argument when trying to upload:
$gridFs->storeUpload($_FILES["news_attachment"]["name"],
or possibly
$gridFs->storeUpload($_FILES["news_attachment"]["tmp_name"],
I just need to add check for error if(!empty($_FILES["news_attachment"]) && $_FILES["news_attachment"]["error"] == 0){ save file}

code works fine in localhost but not in server

I need to submit form to databse,my form and its php code for submission into database working correctlyn in localserver,but when i upload it in main server after submission an empty php file is shown,no error messages ,data also not entered into database,
when i include the php code for uploaded image this problem arises else other details in form getting submitted successfully.....
As a learner all kind of suggestion is appreciable....Thanks in advance
<?php
error_reporting(E_ALL);
$name = $_POST['name'];
$date = $_POST['year']."-". $_POST['month']."-".$_POST['date'];
$date = mysql_real_escape_string($date);
if (isset($_POST['gender'])){
$gender = $_POST['gender'];
}
if (isset($_POST['maritalstatus'])){
$maritalstatus = $_POST['maritalstatus'];
}
$registerby =$_POST['registerby'];
$livingplace =$_POST['livingplace'];
$qualification =$_POST['quali'];
$occupation =$_POST['occupation'];
$income = $_POST['income'];
$contactno =$_POST['mobno'];
$caste =$_POST['caste'];
$email =$_POST['email'];
if(isset($_POST['submit']))
{
//Assign the paths needed to variables for use in the script
$filePathFull = "/public_html/www.****.com/icons/".$_FILES["imagefile"] ["name"];
$filePathThumb = "/public_html/www.*****.com/icons/";
//Assign the files TMP name and TYPE to variable for use in the script
$tmpName = $_FILES["imagefile"]["tmp_name"];
$imageType = $_FILES["imagefile"]["type"];
//Use a switch statement to check the extension of the file type. If file type is not valid echo an error
switch ($imageType) {
case $imageType == "image/gif":
move_uploaded_file($tmpName,$filePathFull);
break;
case $imageType == "image/jpeg":
move_uploaded_file($tmpName,$filePathFull);
break;
case $imageType == "image/pjpeg":
move_uploaded_file($tmpName,$filePathFull);
break;
case $imageType == "image/png":
move_uploaded_file($tmpName,$filePathFull);
break;
case $imageType == "image/x-png":
move_uploaded_file($tmpName,$filePathFull);
break;
default:
echo 'Wrong image type selected. Only JPG, PNG or GIF formats accepted!.';
}
// Get information about the image
list($srcWidth, $srcHeight, $type, $attr) = getimagesize($filePathFull);
$origRatio = $srcWidth/$srcHeight;
//Create the correct file type based on imagetype
switch($type) {
case IMAGETYPE_JPEG:
$startImage = imagecreatefromjpeg($filePathFull);
break;
case IMAGETYPE_PNG:
$startImage = imagecreatefrompng($filePathFull);
break;
case IMAGETYPE_GIF:
$startImage = imagecreatefromgif($filePathFull);
break;
default:
return false;
}
//Get the image to create thumbnail from
$startImage;
$width = 150;
$height = 150;
if ($width/$height > $origRatio) {
$width = $height*$origRatio;
}else{
$height = $width/$origRatio;
}
//Create the thumbnail with true colours
$thumbImage = imagecreatetruecolor($width, $height);
//Generate the resized image image
imagecopyresampled($thumbImage, $startImage, 0,0,0,0, $width, $height, $srcWidth, $srcHeight);
//Generate a random number to append the filename.
$ran = "thumb_".rand () ;
$thumb2 = $ran.".jpg";
//global $thumb_Add_thumb;
//Create the path to store the thumbnail in.
$thumb_Add_thumb = $filePathThumb;
$thumb_Add_thumb .= $thumb2;
//Create the new image and put it into the thumbnails folder.
imagejpeg($thumbImage, "" .$filePathThumb. "$thumb2");
}
if(isset($_POST['submit']))
{
$connection = mysql_connect("localhost","user", "pass");
if(! $connection) { die('Connection Failed: ' . mysql_error()) ;}
mysql_select_db("database") or die (error.mysql_error());
$sql = "INSERT INTO quickregister(Name,Gender,Dateofbirth,Maritalstatus,Qualification,Income,Livingplace,Caste,Contactno,Emailaddress,Registerby,picture,filePathThumb,Occupation)VALUES('".$name."','".$gender."','".$date."','".$maritalstatus."','".$qualification."','".$income."','".$livingplace."','".$caste."','".$contactno."','".$email."','".$registerby."','".$filePathFull."','".$thumb_Add_thumb."','".$occupation."')";
$retval = mysql_query( $sql, $connection );
if(! $retval )
{
die('Could not enter data' . mysql_error());
}
echo "<b>Your data was added to database</b>";
}
?>
You switch code makes no sense. Apparently you missed the point of switch/case vs. if and this is wrong:
switch ($imageType) {
case $imageType == "image/gif":
move_uploaded_file($tmpName,$filePathFull);
break;
...
default:
echo 'Wrong image type selected. Only JPG, PNG or GIF formats accepted!.';
}
and should be:
switch ($imageType) {
case "image/gif":
move_uploaded_file($tmpName,$filePathFull);
break;

PHP File Upload Recognition help!

SOLVED MY OWN QUESTION! THANKS EVERYONE FOR THE HELP :)
Ok. I'm having trouble with the code below recognizing the upload FILE TYPE and running the correct function. I can upload PNG just fine and it will convert and resize like it should, but GIF and JPEG don't and just return a black image. If I remove the png code and try the others individually they work. I can't figure this out at the moment why when I combine them they won't work. It's like together they all use whatever function comes first, instead of going by the FILE TYPE
if ($width > $max_width){
$scale = $max_width/$width;
if ($_FILE['image']['type'] = "image/png"){
$uploaded = resizeImagePNG($large_image_location,$width,$height,$scale);
} elseif ($_FILE['image']['type'] = "image/gif"){
$uploaded = resizeImageGIF($large_image_location,$width,$height,$scale);
} elseif ($_FILE['image']['type'] = "image/jpeg" || $_FILE['image']['type'] = "image/pjpeg"){
$uploaded = resizeImageJPG($large_image_location,$width,$height,$scale);
}
session_start();
$_SESSION['image2resize'] = $large_image_location;
}else{
$scale = 1;
if ($_FILE['image']['type'] = "image/png"){
$uploaded = resizeImagePNG($large_image_location,$width,$height,$scale);
} elseif ($_FILE['image']['type'] = "image/gif"){
$uploaded = resizeImageGIF($large_image_location,$width,$height,$scale);
} elseif ($_FILE['image']['type'] = "image/jpeg" || $_FILE['image']['type'] = "image/pjpeg"){
$uploaded = resizeImageJPG($large_image_location,$width,$height,$scale);
}
session_start();
$_SESSION['image2resize'] = $large_image_location;
}
}
edit: combined with Pekka's method for the mime, and rewritten for clarity
You have an error in all your if/elseif comparations. You need to put double == instead of single =
You may use this code that should do the same, but in a cleaner and safer way
$info = getimagesize(($_FILE['image']['tmp_name']);
$mime = $info["mime"];
if ($width > $max_width){
$scale = $max_width/$width;
} else {
$scale = 1;
}
switch ($mime)
{
case "image/png":
$uploaded = resizeImagePNG($large_image_location,$width,$height,$scale);
break;
case "image/gif":
$uploaded = resizeImageGIF($large_image_location,$width,$height,$scale);
break;
case "image/jpeg":
$uploaded = resizeImageJPG($large_image_location,$width,$height,$scale);
break;
default:
// do a better handling of the error
die('image type not supported');
}
session_start();
$_SESSION['image2resize'] = $large_image_location;
Also, don't rely on $_FILE['image']['type'], as this value is sent by the browser and an attacker can forge it. Use the getimagesize() method for obtaining the filetype as Pekka suggested in his answer.
#Carlos answers your question.
As a side note, I wouldn't rely on the MIME type server by the user's browser at all, and use getimagesize() to detect the file type instead.
$info = getimagesize(($_FILE['image']['tmp_name']);
$mime = $info["mime"];
that is safer.
FIGURED IT OUT!!!!!!!! The verification was screwing things up. Instead of checking if it's not a image, I checked if it was and it started working. NEW verification -> if ($mime == 'image/gif' || $mime == 'image/jpeg' || $mime == 'image/pjpeg' || $mime == 'image/png' || $_FILES['image']['size'] < 3000000){ working code here } else { error code here } . Thanks for all the help!

Categories