帝国软件
  设为首页 加入收藏 关于我们
 
解密帝国网站管理系统
栏 目:
 
您的位置:首页 > 技术文档 > PHP编程
轻松实现文件上传
作者:匿名 发布时间:2002-12-21 来源:www.code-labs.com
在以往的工作中,为了将图片作为邮件的附件或者为了将图片作为一篇文章中的内容,我已经写了一些代码来处理文件的上传操作。为了不总重复书写这些代码,我计划将这些代码整理成函数以供以后使用。



正好,一些朋友问我如何将图片上传并作为新闻或文章的一部分,所以我坐下来,写了下面的代码,如果需要的话,可以从这里下载



首先,我们需要定义几个参数变量,你允许用户上传的文件大小,如果是图片的话,还要定义图片的高和宽,例如:一张jpeg的图片,1024*768,大小为1.5MB。



<?php

$my_max_file_size = "102400"; # in bytes

$image_max_width = "300"; # in pixels

$image_max_height = "300"; # in pixels

?>



下一步,我们要定义图片在服务器上存放的位置,这里要注意,定义的路径必须要有可写的权限。



<?php

$the_path = "/usr/local/apache/htdocs/sites/dev/phpbuilder/upload/files";

?>



现在我们需要一个文件类型的列表,通过这个列表我们可以在程序中判断用户提交的文件类型是否符合我们的要求,如果不符合的话,我们可以将错误信息返回给用户。这个可以轻松的通过一个数组来实现,数组的索引是真实的文件类型,而数组的值是一些我们所熟悉的文件类型扩展名。



<?php

$registered_types = array(

"application/x-gzip-compressed" => ".tar.gz, .tgz",

"application/x-zip-compressed" => ".zip",

"application/x-tar" => ".tar",

"text/plain" => ".html, .php, .txt, .inc (etc)",

"image/bmp" => ".bmp, .ico",

"image/gif" => ".gif",

"image/pjpeg" => ".jpg, .jpeg",

"image/jpeg" => ".jpg, .jpeg",

"application/x-shockwave-flash" => ".swf",

"application/msword" => ".doc",

"application/vnd.ms-excel" => ".xls",

"application/octet-stream" => ".exe, .fla (etc)"

); # these are only a few examples, you can add as many as you like

?>



最后,我们需要指定允许用户上传的文件类型,例如,我们允许上传以下图片类型:



<?php

$allowed_types = array("image/bmp","image/gif","image/pjpeg","image/jpeg");

?>



一个面向对象的程序员可能会将所有的代码写成一个类,并将下面的函数写成类的方法,不过我个人还是比较喜欢写成函数的形式。



好,下面我们就要开始写代码了。首先,我们要写一个函数用来生成上传的表单,以便在后面调用它。也许你可能会疑惑,为什么代码中有许多n's,使用它是为了避免输出到浏览器的html代码挤压到一行里面去。这样,可以使你轻松地通过浏览前台的html代码来帮助寻找程序中的BUG。



<?php

function form($error=false) {

global $PHP_SELF,$my_max_file_size;

if ($error) print $error . "<br><br>";

print "n<form ENCTYPE="multipart/form-data" action="" . $PHP_SELF . "" method="post">";

print "n<INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="" . $my_max_file_size . "">";

print "n<INPUT TYPE="hidden" name="task" value="upload">";

print "n<P>Upload a file";

print "n<BR>NOTE: Max file size is " . ($my_max_file_size / 1024) . "KB";

print "n<br><INPUT NAME="the_file" TYPE="file" SIZE="35"><br>";

print "n<input type="submit" Value="Upload">";

print "n</form>";

} # END form

?>



第二个函数用来判断提交的值是否在一个数组中,php4已经提供了这个功能,但php3没有提供,所以我们使用一个IF语句来判断PHP的版本。如果你运行的是PHP4,你可以删除掉多余的东西,不过建议保留,这样它就可以在不过的服务器上运行了。



<?php

if (!ereg("^4",phpversion())) {

function in_array($needle,$haystack) { # we have this function in PHP4, so for you PHP3 people

for ($i=0; $i < count($haystack); $i++) {

if ($haystack[$i] == $needle) {

return true;

}

}

}

}

?>



主要的函数用来确认上传的内容,这里我们需要判断文件的类型,如果是图片的话,还有它的尺寸。



<?php

function validate_upload($the_file) {

global $my_max_file_size, $image_max_width, $image_max_height,$allowed_types,$the_file_type,$registered_types; $start_error = "n<b>Error:</b>n<ul>";

if ($the_file == "none") { # do we even have a file?

$error .= "n<li>You did not upload anything!</li>";

} else { # check if we are allowed to upload this file_type

if (!in_array($the_file_type,$allowed_types)) {

$error .= "n<li>The file that you uploaded was of a ".

"type that is not allowed, you are only

allowed to upload files of the type:n<ul>";

while ($type = current($allowed_types)) {

$error .= "n<li>" . $registered_types[$type] . " (" . $type . ")</li>";

next($allowed_types);

}

$error .= "n</ul>";

}



if (ereg("image",$the_file_type) && (in_array($the_file_type,$allowed_types))) {



$size = GetImageSize($the_file);

list($foo,$width,$bar,$height) = explode(""",$size[3]);



if ($width > $image_max_width) {

$error .= "n<li>Your image should be no wider than " .

$image_max_width . " Pixels</li>";

}



if ($height > $image_max_height) {

$error .= "n<li>Your image should be no higher than " .

$image_max_height . " Pixels</li>";

}



}



if ($error) {

$error = $start_error . $error . "n</ul>";

return $error;

} else {

return false;

}

}

} # END validate_upload



?>



1-4: we start our function off and tell PHP what variables have a global scope (i.e. originated outside this function), this also saves us having to use $GLOBALS[] everywhere.

5: Start our error message off

6-9: if there is no file, $the_file is set to 'none' so we check if the user actually specified a file to upload

13-21: Here, our in_array function and the two arrays we built earlier come into play, we loop through the $allowed_types array and see if the PHP set $the_file_type is in there, if it is the script knows that it is allowed to accept this. If it is not allowed, then we use the $registered_types array to give a sensible error message.

23-35: If the uploaded file is an image, we want to check that it's dimensions are smaller than our pre-defined maximum values. We use the PHP function getimagesize() to check the file dimensions and build up the error string if it is too big.

37-42: If we have anything in $error, we finish the string off and return it, else we return false. There that's the hard work done.



下面这个函数并不是必须的,这个函数是用来确认用户已经成功上传了文件,使用的方法是显示出目录下的所有文件,不包括"."和".."。



<?php



function list_files() {



global $the_path;



$handle = dir($the_path);

print "n<b>Uploaded files:</b><br>";

while ($file = $handle->read()) {

if (($file != ".") && ($file != "..")) {

print "n" . $file . "<br>";

}

}

print "<hr>";

}



?>



最后一个函数,用来将我们前面的函数组合在一起。首先我们通过表单得到用户需要上传的文件,然后用validate_upload()函数验证文件是否符合我们的要求,如果符合的话,我们就将它拷贝到服务器的指定目录下,如果这些都成功的话,我们再使用list_files()函数列出目录下的所有文件,以便确认上传成功。



<?php



function upload($the_file) {



global $the_path,$the_file_name;



$error = validate_upload($the_file);

if ($error) {

form($error);

} else { # cool, we can continue

if (!@copy($the_file, $the_path . "/" . $the_file_name)) {

form("n<b>Something barfed, check the path to and ".

"the permissions for the upload directory</b>");

} else {

list_files();

form();

}

}

} # END upload



?>



最后,我使用case()语句,来执行不同的操作。如果$task = upload ,那么上传操作开始,否则就显示上传的表单。



<?php



print "<html>n<head>n<title>Upload example</title>n</head>n<body>";



switch($task) {

case 'upload':

upload($the_file);

break;

default:

form();

}



print "n</body>n</html>";



?>



运行上面的代码,你会看到一个表单显示在页面上,通过浏览硬盘选择文件并提交。如果程序没有出现什么错误,程序会显示服务器上的文件列表并再次显示上传表单。



好了,图片上传后,你就可以在文章中使用图片了。
  
评论】【加入收藏夹】【 】【打印】【关闭
※ 相关链接
 ·用Visual C#中轻松浏览数据库记  (2005-03-12)
 ·EJB轻松进阶之八  (2005-03-12)
 ·EJB轻松进阶之七  (2005-03-12)
 ·EJB轻松进阶之六  (2005-03-12)
 ·EJB轻松进阶之五  (2005-03-12)
 ·EJB轻松进阶之四  (2005-03-12)
 ·EJB轻松进阶之三  (2005-03-12)
 ·EJB轻松进阶之二  (2005-03-12)
 ·EJB轻松进阶之一  (2005-03-12)
 ·PEAR:使用PHPDoc轻松建立你的PE  (2005-03-11)

   栏目导行
  PHP编程
  ASP编程
  ASP.NET编程
  JAVA编程
   站点最新
·致合作伙伴的欢迎信
·媒体报道
·帝国软件合作伙伴计划协议
·DiscuzX2.5会员整合通行证发布
·帝国CMS 7.0版本功能建议收集
·帝国网站管理系统2012年授权购买说
·PHPWind8.7会员整合通行证发布
·[官方插件]帝国CMS-访问统计插件
·[官方插件]帝国CMS-sitemap插件
·[官方插件]帝国CMS内容页评论AJAX分
   类别最新
·Windows下集成安装Apache,PHP,MYSQ
·Mysql注入:SQL Injection with MyS
·PHP 的来龙去脉
·PHP 的功能概述
·PHP与其它CGI的比较
·PHP 的编译配置详细选项
·php.ini 配置详细选项
·如何写作PHP程序
·Hello,World
·嵌入方法
 
关于帝国 | 广告服务 | 联系我们 | 程序开发 | 网站地图 | 留言板 帝国网站管理系统