使用If语句上传的PHP文件验证

时间:2009-02-05 16:59:45

标签: php mysql validation file-upload if-statement

您好我是非常新的PHP,但我一直在关注一些教程,但他们似乎没有工作,所以我试图调整它们。  我已经测试了这个代码并且它工作到了一点,但是还有一些我无法理解的东西,php文件没有上传(很好)但是细节仍在写入数据库,尽管$ ok是spose to设置为0(不正常)。如果解释这里发生的事情可能会更容易:

- 用户可以上传gif或jpeg文件。添加到db的详细信息。 - 用户可以上传任何文件,默认情况下将被使用。添加到db的详细信息。 - 用户不应能够上传任何其他文件。数据库上没有记录,用户应该再试一次。

我的代码到目前为止:

<?php

//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['photo']['name']);
$ok=0; 


//This gets all the other information from the form
$name= mysql_real_escape_string ($_POST['nameMember']);
$bandMember= mysql_real_escape_string ($_POST['bandMember']);
$pic= mysql_real_escape_string ($_FILES['photo']['name']);
$about= mysql_real_escape_string ($_POST['aboutMember']);
$bands= mysql_real_escape_string ($_POST['otherBands']);

$uploaded_size=$_FILES['photo']['file_size']; 
if ($uploaded_size > 350000)
{
echo "Your file is too large, 35Kb is the largest file you can upload.<br>";
$ok=0;
} 
if ($uploaded_type =="text/php")
{
echo "No PHP files<br>";
$ok=0;
} 

if (!($uploaded_type =="image/jpeg"))
{
echo "JPEG<br>";$ok=1;
} 

if ($uploaded_type =="image/gif")
{
echo "GIf<br>";$ok=1;
} 

if (empty($pic)){
echo "You haven't uploaded a photo, a default will be used instead.<br/>";$ok=1;}


if ($ok==0)
{
Echo "Sorry your file was not uploaded, please try again with the correct format.";
}

//If everything is ok we try to upload it
else
{ 

// Connects to your Database
mysql_connect("localhost", "*******", "******") or die(mysql_error()) ;
mysql_select_db("project") or die(mysql_error()) ;

//Writes the information to the database
mysql_query("INSERT INTO dbProfile (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;

//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory<br/>";
print "<a class=\"blue\" href=\"createMember.php\">Add Another Record</a> | <a class=\"blue\" href=\"listMember.php\">Band Member Profiles and Affiliates Menu</a>";
}
else {

//Gives and error if its not
echo "<p>If you have uploaded a picture there may have been a problem uploading your file.</p>";
print "<a class=\"blue\" href=\"createMember.php\">Add Another Record</a> | <a class=\"blue\" href=\"listMember.php\">Band Member Profiles and Affiliates Menu</a>";
}
}
?> 

提前干杯。 CHL

1 个答案:

答案 0 :(得分:1)

错误可能是这个if语句:

  if (!($uploaded_type =="image/jpeg"))
  {
    echo "JPEG<br>";$ok=1;
  }

因为每次上传的图像都没有等于“image / jpeg”的内容类型时,$ ok的计算结果为1,所以所有内容都会写入数据库。

但是请注意,只是像这样检查MIME类型会让你遇到麻烦,因为用户可以伪造文件的MIME类型。

例如,您可以使用Imagick获取正确的图像MIME类型。在此处查看更多详细信息:http://de2.php.net/manual/en/function.imagick-identifyimage.php

编辑:注意,$ uploaded_type不会在脚本中的任何位置初始化。正如我所说,你可以使用$ _FILES ['photo'] ['type']粗略估计MIME类型。