如何使用php封装类实现图片上传可直接引用_PHP教程

编辑Tag赚U币
教程Tag:暂无Tag,欢迎添加,赚取U币!

推荐:如何使用php实现封装数据库的类文件
?php class dbname{ private $localhost; private $root; private $pass; private $db_name;public function __construct($localhost,$root,$pass,$db_name){ $this-localhost=$localhost; $this-root=$root; $this-pass=$pass; $this-db_name=$db_name; $this-query()

 <?php

class image { /** *完成图片的上传 * *@param array $file 待上传的文件信息的数组,用于5个元素的那个数组 *@return mixed 如果执行成功,返回上传了的文件名,否则返回false */ public function upload($file) { if($file['error'] == 0) { $allow_types = array('image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'); if(in_array($file['type'], $allow_types)) { $maxsize = 2000000; if($file['size'] <= $maxsize) { //上传 //需要将文件重命名,1,防止不规则的字符出现在文件名中,2,防止重名 //采用时间戳加随机数的形式 //后缀名如何获得?在原始文件名中获得后缀名 //在文件名中最后一个点截取到最后就是扩展名 //strrchr(在哪个字符串中查,查的字符串); $new_filename = time() . mt_rand(10000, 99999) . strrchr($file['name'], '.'); //移动 //此函数返回移动成功还是失败 if(move_uploaded_file($file['tmp_name'],'images/'. $new_filename)) { return $new_filename; } } } } //只有一种情况返回文件名,其他全部返回false return false; } } ?> //------------------------------------------------------------------------------------- <?php header("content-type:text/html;charset=utf-8"); function __autoload($image){ require_once($image.'.class.php'); } $image = new image(); $user = $_POST['user']; $img = $_FILES['img']; //var_dump($img); $img = $image ->upload($img); mysql_connect('localhost','root','123'); mysql_select_db('lyb'); mysql_query('set names utf8'); $q = "insert test_image(name,url) values('$user','$img')"; //var_dump($q); $result = mysql_query($q); if($result){ echo "添加成功.....<br /><br />"; } else{ echo "添加失败。。。"; } ?> //-------------------------------------------------------------------------------------- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>图片上传类</title> </head> <body> <form enctype="multipart/form-data" method="post" action="images.php"> 姓名:<input type="text" name="user" id="user"/><br> 图片:<input type="file" name="img" id="img"/><br> <input type="submit" value="提交"/> </form> </body> </html>

分享:PHP5中Cookie与 Session使用详解
在非常多时候,我们需要跟踪浏览者在整个网站的活动,对他们身份进行自动或半自动的识别(也就是平时常说的网站登陆之类的功能),这时候,我们常采用Cookie与 Session来跟踪和判断

来源:模板无忧//所属分类:PHP教程/更新时间:2013-05-02
相关PHP教程