首页 > 编程知识 正文

一个php图片上传的例子,php上传照片

时间:2023-12-27 22:27:47 阅读:326722 作者:UNDZ

本文目录一览:

用php上传图片怎么做?

上传图片原理:首先判断文件类型是否为图片格式,若是则上传文件,然后重命名文件(一般都是避免上传文件重名,现在基本上都是以为时间来命名),接着把文件上传到指定目录,成功上传后输出上传图片的预览。

1.首先我们开始判断文件类型是否为图片类型用到的函数

{

strrchr:查找字符串在另一个字符串中最后一次出现的位置,并返回从该位置到字符串结尾的所有字符。

substr: 取部份字符串。

$HTTP_POST_FILES['file']['name']:获取当前上传的文件全称。

}

图片类型就是“.”后面的字符(比如:一个文件名称为XXX.JPG 那么它的类型就是“.”后面的JPG)。 我们可以用PHP中的函数来截取上传者文件名字的。我们来写个获取文件类型的函数

?

function type()

{

return substr(strrchr($HTTP_POST_FILES['file']['name'],'.'),1);

}

?

2.若是则上传文件,然后重命名文件用到的函数

{ strtolower:把字符串的字母全部转换为小写字母. in_array: 函数在数组中搜索给定的值。 implode:函数把数组元素组合为一个字符串 random:随机生成的数 $_FILES['userfile']['name']:上传文件名称 $uploaddir:自己定义的变量。比如在同一个文件夹里面,你想把上传的文件放到这个文件夹的FILE文件夹下,你可以这样定义$uploaddir="./file/";注意写法 } 这边会出现很多问题,第一先写一个能上传类型的数组。第二判断文件合法性。第三给文件重名。*(这边判断文件大小就不写了)先定义允许上传文件的类型数组:$type=array("jpg","gif","bmp","jpeg","png");第二用一个IF。。else。。写一个判断文件合法性的控制流语句。if(!in_arry(strtolower(type()),$type))//如果不存在能上传的类型 { $text=implode('.',$type); echo "您只能上传以下类型文件: ",$text,"br"; } 下面就是给他们重新命名了,else { $filename=explode(".",$_FILES['userfile']['name']);//把上传的文件名以“.”好为准做一个数组。 $time=date("m-d-H-i-s");//去当前上传的时间 $filename[0]=$time;//取文件名t替换 name=implode(".",$filename); //上传后的文件名 $uploadfile=$uploaddir.$name;//上传后的文件名地址 } 3.最后把文件上传到指定目录,成功上传后输出上传图片的预览用到的函数{ move_uploaded_file:执行上传文件 } if(move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadfile)) { echo "center您的文件已经上传完毕 上传图片预览: /centerbrcenterimg src='$uploadfile'/center"; echo"brcentera href='javascrīpt:history.go(-1)'继续上传/a/center"; } else { echo"传输失败!"; }

用php写一个上传图片的程序 谢谢

?php

$uptypes=array('image/jpg', //上传文件类型列表

'image/jpeg',

'image/png',

'image/pjpeg',

'image/gif',

'image/bmp',

'application/x-shockwave-flash',

'image/x-png');

$max_file_size=5000000; //上传文件大小限制, 单位BYTE

$destination_folder="upload/"; //上传文件路径

$watermark=0; //是否附加水印(1为加水印,其他为不加水印);

$watertype=1; //水印类型(1为文字,2为图片)

$waterposition=1; //水印位置(1为左下角,2为右下角,3为左上角,4为右上角,5为居中);

$waterstring="newphp.site.cz"; //水印字符串

$waterimg="xplore.gif"; //水印图片

$imgpreview=1; //是否生成预览图(1为生成,其他为不生成);

$imgpreviewsize=1/2; //缩略图比例

?

html

head

titleM4U BLOG - fywyj.cn/title

meta http-equiv="Content-Type" content="text/html; charset=gb2312"

style type="text/css"body,td{font-family:tahoma,verdana,arial;font-size:11px;line-height:15px;background-color:white;color:#666666;margin-left:20px;}

strong{font-size:12px;}

aink{color:#0066CC;}

a:hover{color:#FF6600;}

aisited{color:#003366;}

a:active{color:#9DCC00;}

table.itable{}

td.irows{height:20px;background:url("index.php?i=dots" repeat-x bottom}/style

/head

body

centerform enctype="multipart/form-data" method="post" name="upform"

上传文件: brbrbr

input name="upfile" type="file" style="width:200;border:1 solid #9a9999; font-size:9pt; background-color:#ffffff" size="17"

input type="submit" value="上传" style="width:30;border:1 solid #9a9999; font-size:9pt; background-color:#ffffff" size="17"brbrbr

允许上传的文件类型为:jpg|jpeg|png|pjpeg|gif|bmp|x-png|swf brbr

a href="index.php"返回/a

/form

?php

if ($_SERVER['REQUEST_METHOD'] == 'POST')

{

if (!is_uploaded_file($_FILES["upfile"][tmp_name]))

//是否存在文件

{

echo "font color='red'文件不存在!/font";

exit;

}

$file = $_FILES["upfile"];

if($max_file_size $file["size"])

//检查文件大小

{

echo "font color='red'文件太大!/font";

exit;

}

if(!in_array($file["type"], $uptypes))

//检查文件类型

{

echo "font color='red'只能上传图像文件或Flash!/font";

exit;

}

if(!file_exists($destination_folder))

mkdir($destination_folder);

$filename=$file["tmp_name"];

$image_size = getimagesize($filename);

$pinfo=pathinfo($file["name"]);

$ftype=$pinfo[extension];

$destination = $destination_folder.time().".".$ftype;

if (file_exists($destination) $overwrite != true)

{

echo "font color='red'同名文件已经存在了!/a";

exit;

}

if(!move_uploaded_file ($filename, $destination))

{

echo "font color='red'移动文件出错!/a";

exit;

}

$pinfo=pathinfo($destination);

$fname=$pinfo[basename];

echo " font color=red已经成功上传/fontbr文件名: font color=blue".$destination_folder.$fname."/fontbr";

echo " 宽度:".$image_size[0];

echo " 长度:".$image_size[1];

if($watermark==1)

{

$iinfo=getimagesize($destination,$iinfo);

$nimage=imagecreatetruecolor($image_size[0],$image_size[1]);

$white=imagecolorallocate($nimage,255,255,255);

$black=imagecolorallocate($nimage,0,0,0);

$red=imagecolorallocate($nimage,255,0,0);

imagefill($nimage,0,0,$white);

switch ($iinfo[2])

{

case 1:

$simage =imagecreatefromgif($destination);

break;

case 2:

$simage =imagecreatefromjpeg($destination);

break;

case 3:

$simage =imagecreatefrompng($destination);

break;

case 6:

$simage =imagecreatefromwbmp($destination);

break;

default:

die("font color='red'不能上传此类型文件!/a");

exit;

}

imagecopy($nimage,$simage,0,0,0,0,$image_size[0],$image_size[1]);

imagefilledrectangle($nimage,1,$image_size[1]-15,80,$image_size[1],$white);

switch($watertype)

{

case 1: //加水印字符串

imagestring($nimage,2,3,$image_size[1]-15,$waterstring,$black);

break;

case 2: //加水印图片

$simage1 =imagecreatefromgif("xplore.gif");

imagecopy($nimage,$simage1,0,0,0,0,85,15);

imagedestroy($simage1);

break;

}

switch ($iinfo[2])

{

case 1:

//imagegif($nimage, $destination);

imagejpeg($nimage, $destination);

break;

case 2:

imagejpeg($nimage, $destination);

break;

case 3:

imagepng($nimage, $destination);

break;

case 6:

imagewbmp($nimage, $destination);

//imagejpeg($nimage, $destination);

break;

}

//覆盖原上传文件

imagedestroy($nimage);

imagedestroy($simage);

}

if($imgpreview==1)

{

echo "br图片预览:br";

echo "a href="".$destination."" target='_blank'img src="".$destination."" width=".($image_size[0]*$imgpreviewsize)." height=".($image_size[1]*$imgpreviewsize);

echo " alt="图片预览:r文件名:".$destination."r上传时间:" border='0'/a";

}

}

?

/center

/body

/html

怎样用php实现上传图片到数据库

php实现上传图片保存到数据库的方法。具体分析如下:

php 上传图片,一般都使用move_uploaded_file方法保存在服务器上。但如果一个网站有多台服务器,就需要把图片发布到所有的服务器上才能正常使用(使用图片服务器的除外)

如果把图片数据保存到数据库中,多台服务器间可以实现文件共享,节省空间。

首先图片文件是二进制数据,所以需要把二进制数据保存在mysql数据库。

mysql数据库提供了BLOB类型用于存储大量数据,BLOB是一个二进制对象,能容纳不同大小的数据。

BLOB类型有以下四种,除存储的最大信息量不同外,其他都是一样的。可根据需要使用不同的类型。

TinyBlob       最大 255B

Blob              最大 65K

MediumBlob  最大 16M

LongBlob      最大 4G

数据表photo,用于保存图片数据,结构如下:

CREATE TABLE `photo` (  

  `id` int(10) unsigned NOT NULL auto_increment,  

  `type` varchar(100) NOT NULL,  

  `binarydata` mediumblob NOT NULL,  

  PRIMARY KEY  (`id`)  

) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

upload_image_todb.php代码如下:

?php  

// 连接数据库  

$conn=@mysql_connect("localhost","root","")  or die(mysql_error());  

@mysql_select_db('demo',$conn) or die(mysql_error()); // 判断action  

$action = isset($_REQUEST['action'])? $_REQUEST['action'] : ''; 

// 上传图片  

if($action=='add'){  

    $image = mysql_escape_string(file_get_contents($_FILES['photo']['tmp_name']));  

    $type = $_FILES['photo']['type'];  

    $sqlstr = "insert into photo(type,binarydata) values('".$type."','".$image."')";  

    @mysql_query($sqlstr) or die(mysql_error());  

    header('location:upload_image_todb.php');  

    exit();  

// 显示图片  

}elseif($action=='show'){  

    $id = isset($_GET['id'])? intval($_GET['id']) : 0;  

    $sqlstr = "select * from photo where id=$id";  

    $query = mysql_query($sqlstr) or die(mysql_error());  

    $thread = mysql_fetch_assoc($query);  

    if($thread){  

        header('content-type:'.$thread['type']);  

        echo $thread['binarydata'];  

        exit();  

    }  

}else{  

// 显示图片列表及上传表单  

?  

!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ""  

html  

 head  

  meta http-equiv="content-type" content="text/html; charset=utf-8"  

  title upload image to db demo /title  

 /head  

  

 body  

  form name="form1" method="post" action="upload_image_todb.php" enctype="multipart/form-data"  

  p图片:input type="file" name="photo"/p  

  pinput type="hidden" name="action" value="add"input type="submit" name="b1" value="提交"/p  

  /form  

  

?php  

    $sqlstr = "select * from photo order by id desc";  

    $query = mysql_query($sqlstr) or die(mysql_error());  

    $result = array();  

    while($thread=mysql_fetch_assoc($query)){  

        $result[] = $thread;  

    }  

    foreach($result as $val){  

        echo 'pimg 

src="upload_image_todb.php?action=showid='.$val['id'].'t='.time().'"

 width="150"/p';  

    }  

?  

/body  

/html  

?php  

}  

?

程序运行截图和数据库截图:

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。