您的位置:首页 > 编程语言 > PHP开发

php封装类实现的图片上传可直接引用

2013-04-24 21:13 756 查看
<?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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息