如何限制用户仅上传图片文件

时间:2015-06-08 08:35:07

标签: php html sql

我想限制用户只上传图片文件。如果任何其他文件用户尝试上传然后生成错误消息将通知用户请仅上传jpeg,jpg,png,bmp格式。如果用户上传任何其他格式而不是上传到数据库的图像。

我要求查看我的代码并告诉我。“

<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] && $_FILES['userfile2']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];

$fileName2 = $_FILES['userfile2']['name'];
$tmpName2 = $_FILES['userfile2']['tmp_name'];
$fileSize2= $_FILES['userfile2']['size'];
$fileType2 = $_FILES['userfile2']['type'];

$fp = fopen($tmpName, 'r');
$image = fread($fp, filesize($tmpName));
$image = addslashes($image);
fclose($fp);

$fp2 = fopen($tmpName2, 'r');
$image2 = fread($fp2, filesize($tmpName2));
$image2 = addslashes($image2);
fclose($fp2);


if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}

if(!get_magic_quotes_gpc())
{
$fileName2 = addslashes($fileName2);
}



defined('_JEXEC') or die;

$user = JFactory::getUser();

$empid = $user->username;

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dat_database";

$conn=mysqli_connect($servername, $username, $password, $dbname);

$query = "UPDATE emp_perdetails SET image_name='$fileName', size='$fileSize', type='$fileType', image='$image',image2='".$image2."' WHERE EMP_ID='$empid'";
mysqli_query($conn,$query) or die('Error, query failed'); 





echo  "<script type='text/javascript'>alert('uploaded sucessfully!')</script>";



} 
?>

`

<html>
<body>
<table>
<form method="post" enctype="multipart/form-data">
<tr><input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<td><h4>Please upload front side of passpot</h4></td>
<td><input name="userfile" type="file" id="userfile" accept="image/*"> </td></tr>
<tr><td><h4>Please upload rear side of passpot</h4></td>
<td><input name="userfile2" type="file" id="userfile" accept="image/*"></td></tr>

<tr><td><td><input name="upload" type="submit" class="box" id="upload" value=" submit "></td></tr>
</table>
</form>
</body>
</html>

2 个答案:

答案 0 :(得分:4)

您可以使用if else语句来检查文件类型

if (($_FILES["userfile"]["type"] == "image/gif")
    || ($_FILES["userfile"]["type"] == "image/jpeg")
    || ($_FILES["userfile"]["type"] == "image/jpg")
    || ($_FILES["userfile"]["type"] == "image/png")) {

//upload file
} else {
    //error
}

答案 1 :(得分:0)

这允许您检查用户上传的文件的扩展名:

<?php
    $fileinfo= pathinfo($_FILES['myfile']['name']);
    $extension_upload = $fileinfo['extension'];
    $extensions_allowed = array('jpg', 'jpeg', 'gif', 'png');
    if (in_array($extension_upload, $extensions_allowed ))
    {
        //upload file
    }
?>