I've got a script and simple if check to see if a value is in a array. I can't seem to find out why the if tag runs when it's in the array.
else if (!in_array($type, $avatarformats)) {
$error .= '<div class="alert error">You\'re image is not a allowed format</div>';
unlink($_FILES['file']['tmp_name']);
}
When the script reads $type and $avatarformats it's = to the following.
$avatarformats = Array ( [0] => .jpg [1] => .jpeg [2] => .png )
$type = .png
The if tag runs when it should not because .png is in the array. Or am I no understaind what am doing.
I'm not sure how you determined the type, but typically the ['type'] that comes from $_FILES is the content type (e.g. 'image/jpeg'), rather than the extension of the filename itself.
To test for file extensions, you could use this code:
// get file extension (without leading period)
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
// ...
elseif (!in_array($ext, array('png', 'jpg', 'jpeg'))) {
// error
}
Note: Use exif_imagetype(), please read http://www.php.net/manual/en/function.exif-imagetype.php
function image_allowed($imgfile) {
$types = array(IMAGETYPE_JPEG, IMAGETYPE_PNG);
return in_array(exif_imagetype($imgfile), $types);
}
Then in your code.
else if (!image_allowed($_FILES['file']['tmp_name'])) {
$error .= '<div class="alert error">You\'re image is not a allowed format</div>';
unlink($_FILES['file']['tmp_name']);
}
I suspect that in_array() is returning true because the statement !in_array($type, $avatarformats) is evaluating to true due to the full stop. It is evaluating the value of $type as an integer because of the decimal place.
That being said you have 2 options:
1) Try stripping the dot i.e. ".png" to "png" from the file extension before adding it to the array in the first place and then do the test.
2) or change your conditional to the following: else if (in_array($type, $avatarformats) == false) {
in_array() is a strange beast and I try to avoid it at the best of times. isset() is your friend and much faster than in_array under most conditions anyways.
Related
I have a very weird problem with php and I can't find any explanation for it.
I want to add this line of code to grab extension from the sent file:
$extension = array_pop( explode( "." , $_FILES["myFiles"]["name"][$key]);
but if i do so php doens't send a respond although the file is saved successfully. If I simply delete this line and hardcode ".jpg" instead $extension it sends the response as expected.
<?php
$response = array();
if (isset($_FILES)) {
foreach ($_FILES["myFiles"]["tmp_name"] as $key => $value) {
$user = $_POST["user"];
// when i add the line below it deosn't send the response!
$extension = array_pop( explode( "." , $_FILES["myFiles"]["name"][$key]) );
move_uploaded_file($value, "uploads/$user.$extension");
};
$response["msg"] = "image has been uploaded";
} else {
$response["msg"] = "selcect an image";
}
echo json_encode($response);
array_pop takes argument by reference. You can't provide argument directly from another function to array_pop.
Instead in your case you should do this:
$parts = explode("." , $_FILES["myFiles"]["name"][$key]);
$extension = array_pop($parts);
But! You should NEVER trust client's data, even if it's just a file extension. It is better to check extension itself (is it jpg, png, svg, gif), also check if the file is really an image, check size of that image, etc...
I've following code snippet:
$aSupportedImages = array('jpg', 'gif', 'png');
foreach($vshare as $file) {
if(!in_array(pathinfo($file, PATHINFO_EXTENSION), $aSupportedImages))
$errArr = 'File extension of image is wrong';
echo $errArr;
break;
}
The array $vshare is as follows(output of print_r($vshare);):
Array
(
[IMG_0004.jpg] => Array
(
[0] => https://www.filepicker.io/api/file/UYUkZVHERGufB0enRbJo
)
)
I'm not understanding why always the loop is getting broken and getting error "File extension of image is wrong" even after the file having extension which is present in array $aSupportedImages?
Please help me.
Thanks.
You should use below code,
as the image name is the key of the array, and you were using value in your extension check
EDIT : As other users said, you are missing {} brackets in your if condition
NOTE : When you want to execute only one statement than you dont neet to use the curly braces. If you want to execute multiple statements than you must wrap the statements into curly braces.
$aSupportedImages = array('jpg', 'gif', 'png');
foreach($vshare as $key=> $value) {
if(!in_array(pathinfo($key, PATHINFO_EXTENSION), $aSupportedImages))
{
$errArr = 'File extension of image is wrong';
echo $errArr;
break;
}
}
Use parenthesis {} for if block and check print_r statement.
Use bracket for if statement:
foreach($vshare as $file) {
if(!in_array(pathinfo($file, PATHINFO_EXTENSION), $aSupportedImages)) {
$errArr = 'File extension of image is wrong';
echo $errArr;
break;
}
}
Also it's better use continue instead of break. Break destruct loop and other files don't checked, but continue let check other files and show error only for broken conditions.
This question already has answers here:
How to get a file's extension in PHP?
(31 answers)
Closed 9 years ago.
I need to verify string whether the string is image file name.
$aaa = 'abskwlfd.png';
if ($aaa is image file) {
echo 'it's image';
else {
echo 'not image';
}
How do i do that? It will chck 100 images, so it should be fast. I know there is a filetype verification method, but I think that's slow.. What about preg_match? Is it faster?
I'm not good at preg_match.
Thank you in advance.
Try this:
<?php
$supported_image = array(
'gif',
'jpg',
'jpeg',
'png'
);
$src_file_name = 'abskwlfd.PNG';
$ext = strtolower(pathinfo($src_file_name, PATHINFO_EXTENSION)); // Using strtolower to overcome case sensitive
if (in_array($ext, $supported_image)) {
echo "it's image";
} else {
echo 'not image';
}
?>
try this code,
if (preg_match('/(\.jpg|\.png|\.bmp)$/i', $aaa)) {
echo "image";
} else{
echo "not image";
}
Maybe you are looking for this:
function isImageFile($file) {
$info = pathinfo($file);
return in_array(strtolower($info['extension']),
array("jpg", "jpeg", "gif", "png", "bmp"));
}
I am using pathinfo to retrieve detail information about file including extension.
I am using strtolower to ensure that the extension will match our list of supported image even it is in different case
Using in_array to check whether file extension is in our list of image extenion.
try this
$allowed = array(
'.jpg',
'.jpeg',
'.gif',
'.png',
'.flv'
);
if (!in_array(strtolower(strrchr($inage_name, '.')), $allowed)) {
print_r('error message');
}else {
echo "correct image";
}
or strrchr it takes last occurence of character string..
else some other concept.
$allowed = array(
'image/jpeg',
'image/pjpeg',
'image/png',
'image/x-png',
'image/gif',
'application/x-shockwave-flash'
);
if (!in_array($image_name, $allowed)) {
print_r('error message');
}else {
echo "correct image";
}
Here you can used STRTOLOWER function and also used in_array function
try this:
$a=pathinfo("example.exe");
var_dump($a['extension']);//returns exe
Yes, regex is the way to go. Alternatively, you could split around the "." and check the last element in the returned array against an array of image extensions. I'm not a PHP guy so I can't write the code for you, but I can write the regex:
^[a-zA-Z\.0-9_-]+\.([iI][mM][gG]|[pP][nN][gG]|etc....)$
This one is fairly simple. I know you don't have much experience with regex, but here's what this one does:
^: start of string
[a-zA-Z\.0-9_-]: describes range of characters including all letters, numbers, and ._-
\.: "." character
([iI][mM][gG]|[pP][nN][gG]|etc....): | means or. So just put all image extensions you know here. Again, the brackets for case-insensitivity
if you want to match any sequence then instead of the stuff in the brackets and the +, just use:
.*
"." matches any character and "*" means any amount of it. So this just basically says "no restrictions" (except newlines)
There are probably a lot of other things I'm missing, as you can see in the comments. Just read those, look at a regex reference, and you'll be fine.
Try this
use pathinfo():
$ext = pathinfo($file_name, PATHINFO_EXTENSION); case sensitive
if (in_array($ext, $supported_image)) {
echo "it's image";
} else {
echo 'not image';
}
As a bit of a follow up to Javascript form won't submit (to view the code I am using visit that link) I am now encountering a problem that I cannot find the file that has been uploaded.
I have added $files = apc_fetch('files_'.$_POST['APC_UPLOAD_PROGRESS']); to the top of my page and this is the output of print_r($files);
Array
(
[theFile] => Array
(
[name] => tt1.mp4
[type] => video/mp4
[tmp_name] => /tmp/php2BEvy7
[error] => 0
[size] => 1050290
)
)
However when I try to run the following code:
if (file_exists($files['theFile']['tmp_name'])) {
$webinarType = strcmp($files['theFile']['type'], 'video/mp4');
if($webinarType == 0) {
$webinarFile = $fileTitle;
$webinarTempName = $files['theFile']['tmp_name'];
} else {
echo 'Webinar must be .mp4';
}
} else {
echo "No File";
}
I get the No File output.
I have ssh'd into the server and the file is not in /tmp/, /path/to/public_html/tmp/ or path/to/file/tmp/ all of which exist.
I have tried to use move_uploaded_file() but as this is executed on all file inputs I can't get the tmp_name dynamically due to my limited knowledge of javascript.
tl;dr version; Where is my file gone and how can I find it?
NOTE; This form did work before the APC intevention and I am running wordpress in case that affects anything.
Fixed this one on my own as well.
In the progress.php file (found on the other question) I modified the elseif statement with this:
elseif(($s_progressId = $_POST['APC_UPLOAD_PROGRESS']) || ($s_progressId = $_GET['APC_UPLOAD_PROGRESS']))
{
// If the file has finished uploading add content to APC cache
$realpath = realpath($PHP_SELF);
$uploaddir = $realpath . '/tmp/';
foreach ($_FILES as $file) {
if(!empty($file['name'])) {
$uploaded_file = $file['name'];
$moveme = $uploaddir.$uploaded_file;
move_uploaded_file($file['tmp_name'], $moveme);
}
}
apc_store('files_'.$s_progressId, $_FILES);
die();
}
That way I could iterate through the $_FILES array without knowing the name of the input. I noticed that it loops through a couple of times hence the if(!empty()) however in hindsight it's probably best practice anyway.
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.