I check file extension for upload or not uploaded. my i.e methods worked but now i need to understand, my methods (pathinfo) is true ? another better and faster way ?! Thanks
我检查文件扩展名是否上传或未上传。我的方法工作但现在我需要理解,我的方法(pathinfo)是真的吗?另一种更好更快的方式?!谢谢
$filename = $_FILES['video_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if( $ext !== 'gif' || $ext !== 'png' || $ext !== 'jpg' ) {echo 'error';}
10 个解决方案
#1
103
Using if( $ext !== 'gif'
) might not be efficient what if you allow like 20 different extensions
使用if($ ext!=='gif')可能效率不高,如果允许20个不同的扩展名
Try
尝试
$allowed = array('gif','png' ,'jpg');
$filename = $_FILES['video_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
echo 'error';
}
#2
41
Checking file extension is not considered best practice, preferred method of accomplishing this task is by checking the files mime type.
检查文件扩展名不是最佳做法,完成此任务的首选方法是检查文件mime类型。
From PHP:
来自PHP:
<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type
foreach (glob("*") as $filename) {
echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);
?>
The above example will output something similar to which you should be checking.
上面的示例将输出与您应该检查的类似的内容。
text/html
image/gif
application/vnd.ms-excel
Although mime-types can also be tricked (edit the first few bytes of a file and modify the magic numbers) but it's harder than editing a filename. So you can never be 100% sure what that file type actually is, and care should be taken about handling files uploaded/emailed by your users.
虽然mime类型也可以被欺骗(编辑文件的前几个字节并修改幻数),但它比编辑文件名更难。因此,您永远无法100%确定该文件类型实际上是什么,并且应该小心处理用户上传/通过电子邮件发送的文件。
#3
10
Personally,I prefer to use preg_match() function:
就个人而言,我更喜欢使用preg_match()函数:
if(preg_match("/\.(gif|png|jpg)$/", $filename))
or in_array()
或者in_array()
$exts = array('gif', 'png', 'jpg');
if(in_array(end(explode('.', $filename)), $exts)
With in_array()
can be useful if you have a lot of extensions to validate and perfomance question. Another way to validade file images: you can use @imagecreatefrom*()
, if the function fails, this mean the image is not valid.
如果你有很多扩展来验证和性能问题,使用in_array()会很有用。验证文件图像的另一种方法是:你可以使用@ imagecreatefrom *(),如果函数失败,这意味着图像无效。
For example:
例如:
function testimage($path)
{
if(!preg_match("/\.(png|jpg|gif)$/",$path,$ext)) return 0;
$ret = null;
switch($ext)
{
case 'png': $ret = @imagecreatefrompng($path); break;
case 'jpeg': $ret = @imagecreatefromjpeg($path); break;
// ...
default: $ret = 0;
}
return $ret;
}
then:
然后:
$valid = testimage('foo.png');
Assuming that foo.png
is a PHP-script file with .png
extension, the above function fails. It can avoid attacks like shell update and LFI.
假设foo.png是扩展名为.png的PHP脚本文件,则上述函数失败。它可以避免shell更新和LFI等攻击。
#4
5
pathinfo is cool but your code can be improved:
pathinfo很酷但你的代码可以改进:
$filename = $_FILES['video_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$allowed = array('jpg','png','gif');
if( ! in_array( $ext, $allowed ) ) {echo 'error';}
Of course simply checking the extension of the filename would not guarantee the file type as a valid image. You may consider using a function like getimagesize
to validate uploaded image files.
当然,只检查文件名的扩展名并不能保证文件类型为有效图像。您可以考虑使用getimagesize之类的函数来验证上传的图像文件。
#5
2
Not sure if this would have a faster computational time, but another option...
不确定这是否会有更快的计算时间,但另一种选择......
$acceptedFormats = array('gif', 'png', 'jpg');
if(!in_array(pathinfo($filename, PATHINFO_EXTENSION), $acceptedFormats))) {
echo 'error';
}
#6
2
file type can be checked in other ways also. I believe this is the easiest way to check the uploaded file type.. if u are dealing with an image file then go for the following code. if you are dealing with a video file then replace the image check with a video check in the if block.. have fun
文件类型也可以通过其他方式检查。我相信这是检查上传文件类型的最简单方法..如果您正在处理图像文件,请转到以下代码。如果你正在处理视频文件,那么用if块中的视频检查替换图像检查..玩得开心
$img_up = $_FILES['video_file']['type']; $img_up_type = explode("/", $img_up); $img_up_type_firstpart = $img_up_type[0];if($img_up_type_firstpart == "image") { // image is the image file type, you can deal with video if you need to check video file type
if($ img_up_type_firstpart ==“image”){//图像是图像文件类型,如果需要检查视频文件类型,可以处理视频
/* do your logical code */ }
/ *做你的逻辑代码* / }
#7
1
i think this might work for you
我认为这可能对你有用
//<?php
//checks file extension for images only
$allowed = array('gif','png' ,'jpg');
$file = $_FILES['file']['name'];
$ext = pathinfo($file, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) )
{
//?>
<script>
alert('file extension not allowed');
window.location.href='some_link.php?file_type_not_allowed_error';
</script>
//<?php
exit(0);
}
//?>
#8
0
To properly achieve this, you'd be better off by checking the mime type.
要正确实现这一点,最好通过检查mime类型来实现。
function get_mime($file) {
if (function_exists("finfo_file")) {
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$mime = finfo_file($finfo, $file);
finfo_close($finfo);
return $mime;
} else if (function_exists("mime_content_type")) {
return mime_content_type($file);
} else if (!stristr(ini_get("disable_functions"), "shell_exec")) {
// http://*.com/a/134930/1593459
$file = escapeshellarg($file);
$mime = shell_exec("file -bi " . $file);
return $mime;
} else {
return false;
}
}
//pass the file name as
echo(get_mime($_FILES['file_name']['tmp_name']));
#9
0
How to validate file extension (jpg/jpeg only) on a form before upload takes place. A variation on another posted answer here with an included data filter which may be useful when evaluating other posted form values. Note: error is left blank if empty as this was an option for my users, not a requirement.
如何在上载之前验证表单上的文件扩展名(仅限jpg / jpeg)。另一个在此处发布的答案的变体与包含数据过滤器在评估其他发布的表单值时可能很有用。注意:如果为空,则错误保留为空,因为这是我的用户的选项,而不是要求。
<?php
if(isset($_POST['save'])) {
//Validate image
if (empty($_POST["image"])) {
$imageError = "";
} else {
$image = test_input($_POST["image"]);
$allowed = array('jpeg','jpg');
$ext = pathinfo($image, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
$imageError = "jpeg only";
}
}
}
// Validate data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
<?
Your html will look something like this;
你的HTML看起来像这样;
<html>
<head>
</head>
<body>
<!-- Validate -->
<?php include_once ('validate.php'); ?>
<!-- Form -->
<form method="post" action="">
<!-- Image -->
<p>Image <?php echo $imageError; ?></p>
<input type="file" name="image" value="<?php echo $image; ?>" />
<p><input type="submit" name="save" value="SAVE" /></p>
</form>
</body>
</html>
#10
-2
use this function
使用此功能
function check_image_extension($image){
$images_extentions = array("jpg","JPG","jpeg","JPEG","png","PNG");
$image_parts = explode(".",$image);
$image_end_part = end($image_parts);
if(in_array($image_end_part,$images_extentions ) == true){
return time() . "." . $image_end_part;
}else{
return false;
}
}
#1
103
Using if( $ext !== 'gif'
) might not be efficient what if you allow like 20 different extensions
使用if($ ext!=='gif')可能效率不高,如果允许20个不同的扩展名
Try
尝试
$allowed = array('gif','png' ,'jpg');
$filename = $_FILES['video_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
echo 'error';
}
#2
41
Checking file extension is not considered best practice, preferred method of accomplishing this task is by checking the files mime type.
检查文件扩展名不是最佳做法,完成此任务的首选方法是检查文件mime类型。
From PHP:
来自PHP:
<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type
foreach (glob("*") as $filename) {
echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);
?>
The above example will output something similar to which you should be checking.
上面的示例将输出与您应该检查的类似的内容。
text/html
image/gif
application/vnd.ms-excel
Although mime-types can also be tricked (edit the first few bytes of a file and modify the magic numbers) but it's harder than editing a filename. So you can never be 100% sure what that file type actually is, and care should be taken about handling files uploaded/emailed by your users.
虽然mime类型也可以被欺骗(编辑文件的前几个字节并修改幻数),但它比编辑文件名更难。因此,您永远无法100%确定该文件类型实际上是什么,并且应该小心处理用户上传/通过电子邮件发送的文件。
#3
10
Personally,I prefer to use preg_match() function:
就个人而言,我更喜欢使用preg_match()函数:
if(preg_match("/\.(gif|png|jpg)$/", $filename))
or in_array()
或者in_array()
$exts = array('gif', 'png', 'jpg');
if(in_array(end(explode('.', $filename)), $exts)
With in_array()
can be useful if you have a lot of extensions to validate and perfomance question. Another way to validade file images: you can use @imagecreatefrom*()
, if the function fails, this mean the image is not valid.
如果你有很多扩展来验证和性能问题,使用in_array()会很有用。验证文件图像的另一种方法是:你可以使用@ imagecreatefrom *(),如果函数失败,这意味着图像无效。
For example:
例如:
function testimage($path)
{
if(!preg_match("/\.(png|jpg|gif)$/",$path,$ext)) return 0;
$ret = null;
switch($ext)
{
case 'png': $ret = @imagecreatefrompng($path); break;
case 'jpeg': $ret = @imagecreatefromjpeg($path); break;
// ...
default: $ret = 0;
}
return $ret;
}
then:
然后:
$valid = testimage('foo.png');
Assuming that foo.png
is a PHP-script file with .png
extension, the above function fails. It can avoid attacks like shell update and LFI.
假设foo.png是扩展名为.png的PHP脚本文件,则上述函数失败。它可以避免shell更新和LFI等攻击。
#4
5
pathinfo is cool but your code can be improved:
pathinfo很酷但你的代码可以改进:
$filename = $_FILES['video_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$allowed = array('jpg','png','gif');
if( ! in_array( $ext, $allowed ) ) {echo 'error';}
Of course simply checking the extension of the filename would not guarantee the file type as a valid image. You may consider using a function like getimagesize
to validate uploaded image files.
当然,只检查文件名的扩展名并不能保证文件类型为有效图像。您可以考虑使用getimagesize之类的函数来验证上传的图像文件。
#5
2
Not sure if this would have a faster computational time, but another option...
不确定这是否会有更快的计算时间,但另一种选择......
$acceptedFormats = array('gif', 'png', 'jpg');
if(!in_array(pathinfo($filename, PATHINFO_EXTENSION), $acceptedFormats))) {
echo 'error';
}
#6
2
file type can be checked in other ways also. I believe this is the easiest way to check the uploaded file type.. if u are dealing with an image file then go for the following code. if you are dealing with a video file then replace the image check with a video check in the if block.. have fun
文件类型也可以通过其他方式检查。我相信这是检查上传文件类型的最简单方法..如果您正在处理图像文件,请转到以下代码。如果你正在处理视频文件,那么用if块中的视频检查替换图像检查..玩得开心
$img_up = $_FILES['video_file']['type']; $img_up_type = explode("/", $img_up); $img_up_type_firstpart = $img_up_type[0];if($img_up_type_firstpart == "image") { // image is the image file type, you can deal with video if you need to check video file type
if($ img_up_type_firstpart ==“image”){//图像是图像文件类型,如果需要检查视频文件类型,可以处理视频
/* do your logical code */ }
/ *做你的逻辑代码* / }
#7
1
i think this might work for you
我认为这可能对你有用
//<?php
//checks file extension for images only
$allowed = array('gif','png' ,'jpg');
$file = $_FILES['file']['name'];
$ext = pathinfo($file, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) )
{
//?>
<script>
alert('file extension not allowed');
window.location.href='some_link.php?file_type_not_allowed_error';
</script>
//<?php
exit(0);
}
//?>
#8
0
To properly achieve this, you'd be better off by checking the mime type.
要正确实现这一点,最好通过检查mime类型来实现。
function get_mime($file) {
if (function_exists("finfo_file")) {
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$mime = finfo_file($finfo, $file);
finfo_close($finfo);
return $mime;
} else if (function_exists("mime_content_type")) {
return mime_content_type($file);
} else if (!stristr(ini_get("disable_functions"), "shell_exec")) {
// http://*.com/a/134930/1593459
$file = escapeshellarg($file);
$mime = shell_exec("file -bi " . $file);
return $mime;
} else {
return false;
}
}
//pass the file name as
echo(get_mime($_FILES['file_name']['tmp_name']));
#9
0
How to validate file extension (jpg/jpeg only) on a form before upload takes place. A variation on another posted answer here with an included data filter which may be useful when evaluating other posted form values. Note: error is left blank if empty as this was an option for my users, not a requirement.
如何在上载之前验证表单上的文件扩展名(仅限jpg / jpeg)。另一个在此处发布的答案的变体与包含数据过滤器在评估其他发布的表单值时可能很有用。注意:如果为空,则错误保留为空,因为这是我的用户的选项,而不是要求。
<?php
if(isset($_POST['save'])) {
//Validate image
if (empty($_POST["image"])) {
$imageError = "";
} else {
$image = test_input($_POST["image"]);
$allowed = array('jpeg','jpg');
$ext = pathinfo($image, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
$imageError = "jpeg only";
}
}
}
// Validate data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
<?
Your html will look something like this;
你的HTML看起来像这样;
<html>
<head>
</head>
<body>
<!-- Validate -->
<?php include_once ('validate.php'); ?>
<!-- Form -->
<form method="post" action="">
<!-- Image -->
<p>Image <?php echo $imageError; ?></p>
<input type="file" name="image" value="<?php echo $image; ?>" />
<p><input type="submit" name="save" value="SAVE" /></p>
</form>
</body>
</html>
#10
-2
use this function
使用此功能
function check_image_extension($image){
$images_extentions = array("jpg","JPG","jpeg","JPEG","png","PNG");
$image_parts = explode(".",$image);
$image_end_part = end($image_parts);
if(in_array($image_end_part,$images_extentions ) == true){
return time() . "." . $image_end_part;
}else{
return false;
}
}