How to verify whether the file (jpg, png, gif) is the picture in PHP?
I need function like this:
boolean isImage($url);
Or:
boolean isImage(binary_data_from_http_post);
I think second way is better, because works before saving file on disk.
I don't want to experiment with copying from random page found in google.
You can use finfo
http://de3.php.net/manual/en/function.finfo-file.php
Or get image size
http://de.php.net/getimagesize
You can use PHP's GD extension to check for a valid image:
function isImage($url) {
$buffer = file_get_contents($url);
$img = imagecreatefromstring($buffer);
return ($img !== false) ? true : false;
}
If you already have the potential image data you can use this instead:
function isImage($data) {
return (imagecreatefromstring($data) !== false) ? true : false;
}
Related
I could of course check mime types through the exif_imagetype or getimagesize and check mime types one by one... But I just want ANY image - I dont care what type... So I was wondering - can I do something like this: ?
// PHP manual says: Determine the type of an image
// and that Imagetype Constants are 1-17 so :
$tmp_imagetype = exif_imagetype('image.gif');
if ( ($tmp_imagetype>=1) && ($tmp_imagetype<=17) ) {
echo "It is an image!";
} else{
echo "It isn't an image.";
}
Can I rely on that?
What happens when the file is not an image? Will it just return non-image constant value or will it throw a warning or error
Thanks
You really don't need all that you just need the following as exif_imagetype returns false if its not an image
if($imagetype = exif_imagetype('image.gif')){
// its an image
} else {
// its not an image
}
You could check if the function returns (exactly) FALSE:
$file="SOMEFILE";
if(exif_imagetype($file)===FALSE){
print("NOT IMAGE");
}else{
print("IMAGE");
}
Why don't you just put all types of images in an array and then check it with this code:
if(in_array($value, $array)) {
//it's an image! Hooray!
}else {
//it's not.
}
I'm working on Wordpress at the moment and as simple as it's sounds i'm trying to check if the image is there in the directory if not then it will show a standard no-image.
My problem is that the file_exists is returning false although the url is correct inside it, and it's accessible via browser so it's not a permission issue, and maybe i'm doing it wrong, here's the code;
$img = 'no_img.jpg';
if($val->has_prop('user_image')){
$img_tmp = $val->get( 'user_image' );
if(file_exists($upload_dir['baseurl'].'/users/'.$img_tmp)){
$img = $val->get( 'user_image' );
}
}
if i do var_dump($upload_dir['baseurl'].'/users/'.$img_tmp); it will show the exact direct URL to the file, and it's correct one, but when it enters the file_exists it returns $img = 'no_img.jpg' although the file exists in the directory.... What am i doing wrong??
I tried also to add clearstatcache(); before the file_exists but didn't work also.
Any ideas?
Try to use:
if( getimagesize($upload_dir['baseurl'].'/users/'.$img_tmp) !== false ){
$img = $val->get( 'user_image' );
}
else {
$img = $val->get( 'no_image' );
}
Also refer to the doc getimagesize
you can use
$fullPath=$upload_dir['baseurl'].'/users/'.$img_tmp;
if(#fopen($fullPath,"r")){
........
}
Or as mentioned in comments, try sniff instead :
if (#file_get_contents($upload_dir['baseurl'].'/users/'.$img_tmp, null, null, 0, 1)) {
//ok
}
You need to use $upload_dir['basedir'] instead of baseurl if you used $upload_dir = wp_upload_dir(); to determine the upload path of your WP installation.
or you can use file_get_contents, cURL, or fopen to sniff if image exists for the url.
I am writing a script and I need to correctly (I think some mime types can be different from their extensions) get the mime types of files (the files can be of any type).
Web hosting company in use does not have mime_content_type() and is still (don't know which year they will be fixing it) promising to fix the PECL alternative.
Which other way can I go about it (and I don;t have access to shell commands)?
You could try finfo_file - it returns the mime type.
http://php.net/manual/en/book.fileinfo.php
I use the following function, which is a wrapper for the 3 most common methods:
function Mime($path, $magic = null)
{
$path = realpath($path);
if ($path !== false)
{
if (function_exists('finfo_open') === true)
{
$finfo = finfo_open(FILEINFO_MIME_TYPE, $magic);
if (is_resource($finfo) === true)
{
$result = finfo_file($finfo, $path);
}
finfo_close($finfo);
}
else if (function_exists('mime_content_type') === true)
{
$result = mime_content_type($path);
}
else if (function_exists('exif_imagetype') === true)
{
$result = image_type_to_mime_type(exif_imagetype($path));
}
return preg_replace('~^(.+);.+$~', '$1', $result);
}
return false;
}
$_FILES['file']['type'] comes from the browser that uploads the file so you can't rely on this value at all.
Check out finfo_file for identifying file types based on file content. The extension of the file is also unreliable as the user could upload malicious code with an mp3 extension.
I need to check whether a given image is a JPEG.
if ($_FILES["fname"]["error"] > 0) {
$imgData = "hyperlink/holder.jpg";
} else {
$imgData ="hyperlink/" . $_FILES["fname"]["name"];
}
// Only accept jpg images
// pjpeg is for Internet Explorer should be jpeg
if (!($_FILES["fname"]["type"] == "image/pjpeg") ) {
print "I only accept jpg files!";
exit(0);
}
When it goes to first statement in the first if statement it always gives I only accept jpg files!
How can I fix it?
Try the exif_imagetype image function.
Example:
if(exif_imagetype($filepath) != IMAGETYPE_JPEG){
echo 'Not a JPEG image';
}
PHP has such good image-type support, i wonder why you are restricting your app. In just a couple lines of code you can deal with any input format and convert to jpeg, if that is a requirement...
$im = imagecreatefrompng(input_filename)
imagejpeg($im, output_filename);
I believe the following works:
Also note that:
(exif_imagetype($ImagePathAndName) == IMAGETYPE_JPEG)
only reads the first few bytes looking for an image header so isn't really good enough to confirm if an image is corrupt.
Below I have it in a logical “and” statement i.e. both of these tests must be passed in order for the image to qualify as being valid and non-corrupt etc:
if ((exif_imagetype($ImagePathAndName) == IMAGETYPE_JPEG) && (imagecreatefromjpeg( $ImagePathAndName ) !== false ))
{
echo 'The picture is a valid jpg<br>';
}
Note: You need to place this line of code at the top of the php code in order to avoid seeing the warning messages from imagecreatefromjpeg( $ImagePathAndName ) when it encounters a fake/corrupt image file.
ini_set(‘gd.jpeg_ignore_warning’, 1);
Why don't you try creating an array of exceptions (the files you want the user to be able to upload).
// Hyperlink for your website
$hyperlink = "http://www.yourwebsitehere.com";
if($_FILES['fname']['error'] > 0)
{
$image= $hyperlink . "/holder.jpg";
}
else
{
$image = $hyperlink . "/" . $_FILES['fname']['name'];
}
// Only accept files of jpeg format
$exceptions = array("image/jpg", "image/jpeg", "image/pjpeg");
foreach($exceptions as $value)
{
if($_FILES['fname']['type'] != $value)
{
echo "I only accept jpeg images!";
break; // Or exit();
}
}
When using $_FILES, you are relying on informations sent by the client, which is not the best thing to do (you've seen it's not always the same, and, if I remember correctly, $_FILES['...']['type'] can be faked).
If you are using PHP >= 5.3 (or can install PECL packages), maybe you can give a look to the extension Fileinfo. If you are using an older version, what about mime_content_type?
And, as said by Scott, why allow only jpeg?
Looking about the code better : when you are in the first case (error > 0), you are assigning a default file to $imgData? Why the spaces around "hyperlink"?
And why do you always use to check the content-type, even if there was an error a couple of lines before?
To finish, did you have a look at the manual (Handling file uploads)?
Check the mime (Multipurpose Internet Mail Extensions) type of file with this code. And verify your desired type. You can also detect png,gif with this code.
if($_FILES["fname"]["type"] == "image/jpeg")
{
echo "File type is JPEG";
}
I am looking for a way to take a user uploaded image that is currently put in a temporary location ex: /tmp/jkhjkh78 and create a php image from it, autodetecting the format.
Is there a more clever way to do this than a bunch of try/catching with imagefromjpeg, imagefrompng, etc?
This is one of the functions of getimagesize. They probably should have called it "getimageinfo", but that's PHP for you.
//Image Processing
$cover = $_FILES['cover']['name'];
$cover_tmp_name = $_FILES['cover']['tmp_name'];
$cover_img_path = '/images/';
$type = exif_imagetype($cover_tmp_name);
if ($type == (IMAGETYPE_PNG || IMAGETYPE_JPEG || IMAGETYPE_GIF || IMAGETYPE_BMP)) {
$cover_pre_name = md5($cover); //Just to make a image name random and cool :D
/**
* #description : possible exif_imagetype() return values in $type
* 1 - gif image
* 2 - jpg image
* 3 - png image
* 6 - bmp image
*/
switch ($type) { #There are more type you can choose. Take a look in php manual -> http://www.php.net/manual/en/function.exif-imagetype.php
case '1' :
$cover_format = 'gif';
break;
case '2' :
$cover_format = 'jpg';
break;
case '3' :
$cover_format = 'png';
break;
case '6' :
$cover_format = 'bmp';
break;
default :
die('There is an error processing the image -> please try again with a new image');
break;
}
$cover_name = $cover_pre_name . '.' . $cover_format;
//Checks whether the uploaded file exist or not
if (file_exists($cover_img_path . $cover_name)) {
$extra = 1;
while (file_exists($cover_img_path . $cover_name)) {
$cover_name = md5($cover) . $extra . '.' . $cover_format;
$extra++;
}
}
//Image Processing Ends
this will make image name look cool and unique
Use exif_imagetype() if it's available ..:
http://www.php.net/manual/en/function.exif-imagetype.php
I'm pretty sure exif functions are available by default (i.e. you have to specifically exclude them rather than specifically include them) when you install php
You could try finfo_file(), apparently an improved version of mime_content_type().
Edit: OK, getimagesize() is better..
You can call a system command (if you're under linux/unix), file if you like:
kender#eira:~$ file a
a: JPEG image data, EXIF standard 2.2
This will help you to know the Extension as well as result based on condition
$image_file = 'http://foo.com/images.gif';
$extension = substr($image_file, -4); if($extension == ".jpg"){ echo 'Its a JPG Image.'; } else { echo 'Its not a JPG Image.'; }
People are recommending using getimagesize() but the documentation reads:
Caution This function expects filename to be a valid image file. If a
non-image file is supplied, it may be incorrectly detected as an image
and the function will return successfully, but the array may contain
nonsensical values.
Do not use getimagesize() to check that a given file is a valid image.
Use a purpose-built solution such as the Fileinfo extension instead.
The relevant function in the Fileinfo extension is finfo_file():
string finfo_file ( resource $finfo , string $file_name = NULL
[, int $options = FILEINFO_NONE [, resource $context = NULL ]] )
Returns a textual description of the contents of the file_name
argument, or FALSE if an error occurred.
Example return values given are: text/html, image/gif, application/vnd.ms-excel
However, comments on the official documentation page warn that this shouldn't be relied on for validation either.