我编写的代码应该检查文件大小是否超过8.5 MB&如果是,它应该产生和错误,并禁止帖子进入数据库。该代码禁止帖子进入数据库但它没有显示任何错误表明文件大小超过。 (P.S:检查未知文件格式是否有效。)这是我写的代码:
//$session id
define ("MAX_SIZE","9000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "uploads/"; //a directory inside
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//get the extension of the file in a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
if(in_array($ext,$valid_formats))
{
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname))
{
$time=time();
mysql_query("INSERT INTO user_uploads(image_name,user_id_fk,created) VALUES('$image_name','$session_id','$time')");
}
else
{
echo '<p style="color: Red;">You have exceeded the size limit! so moving unsuccessful! </p>';
}
}
else
{
echo '<p style="color: Red;">You have exceeded the size limit!</p>';
}
}
else
{
echo '<p style="color: Red;">Unknown extension!</p>';
}
}
}
答案 0 :(得分:2)
我改变了你的代码。
你不需要getExtension这么复杂的函数。
我改变了foreach,不是通过文件的属性来遍历文件。
最后,您需要在移动文件之前检查目录是否存在。 如果没有,你应该创建它。
if(!is_dir($uploaddir)) {
mkdir($uploaddir);
}
看看是否有效并检查差异:
<?php
//$session id
define ("MAX_SIZE","9000");
function getExtension($str)
{
$ext = explode("/",$str);
return $ext[1];
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "uploads/"; //a directory inside
foreach ($_FILES as $FILE)
{
$filename = stripslashes($FILE['name']);
$size=$FILE['size'];
//get the extension of the file in a lower case format
$ext = getExtension($FILE['type']);
$ext = strtolower($ext);
if(in_array($ext,$valid_formats)){
if ($size < (MAX_SIZE*1024)){
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Before you upload the file to the directory, check if it exists like this
if(!is_dir($uploaddir)) {
mkdir($uploaddir);
}
if (move_uploaded_file($FILE['name'], $newname)){
$time=time();
mysql_query("INSERT INTO user_uploads(image_name,user_id_fk,created) VALUES('$image_name','$session_id','$time')");
}else{
echo '<p style="color: Red;">You have exceeded the size limit! so moving unsuccessful! </p>';
}
}else{
echo '<p style="color: Red;">You have exceeded the size limit!</p>';
}
}else{
echo '<p style="color: Red;">Unknown extension!</p>';
}
}
}
它最终在我的电脑上工作,所以假设它将为你工作。 我希望我帮助