当前位置导航:炫浪网>>网络学院>>网页制作>>PHP教程

PHP5图片上传代码,日期文件夹,随机文件名

index.htm

<form enctype="multipart/form-data" action="upload.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file">  
<input type="submit" value="上传文件">
</form>

upload.php

<?
$f=$_FILES['jeff_img_upload'];

//有没有传文件判断
if ($f['error']==4){
echo("<script>alert('请选择你要上传的文件,谢谢!');location.href='index.htm';</script>");
}
else{
//出错判断
if ($f['error']){
echo "失败,文件太大了!错误代码是".$f['error'];
exit;
}

//类型判断
if (substr($f['type'], 0, 5) == 'image') {
                    switch ($f['type']) {
                        case 'image/jpeg':
                        case 'image/jpg':
                        case 'image/pjpeg':
                            $ext = '.jpg?http://www.xvna.com';
                            break;
                        case 'image/gif':
                            $ext = '.gif?http://www.xvna.com';
                            break;
                        case 'image/png':
                        case 'image/x-png':
                            $ext = '.png';
                            break;
                        default:
                            header('Content-type: text/html; charset=UTF-8');
                            echo("<script>alert('你传的不是图片吧?');location.href='index.htm';< /script>");
                            die('REDIRECTING...');
                            break;
                    }
}else {
                    header('Content-type: text/html; charset=UTF-8');
                    echo("<script>alert('你传的不是图片吧?');location.href='index.htm';</script>");
                    die('REDIRECTING...');
                }

//生成随机数
$randomnum=NULL;
for($j=0;$j<=5;$j++)//随机数字的长度,本例随机数长度为6
{
srand((double)microtime()*1000000);
$randomnumber=rand(!$j ? 1: 0,9);//产生随机数,不以0为第一个数,有些特殊的地方0开头被系统省略
$randomnum.=$randomnumber;
}


$dest_dir='/var/www/htdocs/upload';//设定上传目录

//生成日期目录。先判断日期目录是否存在,不存在则创建它。
if(!file_exists(date("Ymd"))){
mkdir(date("Ymd"),0777);}


$dest=$dest_dir.'/'.date("Ymd").'/'.time().'_'.$randomnum.$ext;//设置文件名为时间戳加上随机数避免重复
$r=move_uploaded_file($f['tmp_name'],$dest);
chmod($dest, 0777);//设定上传的文件的属性
}
echo "成功了,文件地址是:".$dest;
?>

相关内容
赞助商链接