PHP验证码生成类完整代码

 更新时间:2016年11月25日 16:21  点击:1969
本文章提供这款php验证码生成类灵活好用,用户可以定义各个成员 有宽、高、画布、字数、类型、画类型同时我们只要修改 $Type就可以定义生成的是纯数字 , 纯小写字母,大小写数字混合,有需要的朋友可参考。
 代码如下 复制代码

<?php
class Code{

// 1. 定义各个成员 有宽、高、画布、字数、类型、画类型

private $width; //宽度
private $height; //高度
private $num; //验证码字数
private $imgType; //生成图片类型
private $Type; //字串类型 1,2,3 三个选项 1 纯数字 2 纯小写字母 3 大小写数字混合
private $hb; //画布
public $codestr; // 验证码字串

public function __construct($height=20,$num=4,$imgType="jpeg",$Type=1){
$this->width = $num*20;
$this->height = $height;
$this->num = $num;
$this->imgType = $imgType;
$this->Type = $Type;
$this->codestr = $this->codestr();
$this->zuhe();
}

// 2. 定义随机获取字符串函数
private function codestr(){
switch($this->Type){

case 1: // 类型为1 获取1-9随机数
$str = implode("",array_rand(range(0,9),$this->num));
break;
case 2: // 类型为2 获取a-z随机小写字母
$str = implode("",array_rand(array_flip(range(a,z)),$this->num));
break;
case 3: // 类型为3 获取数字,小写字母,大写字母 混合
for($i=0;$i<$this->num;$i++){
$m = rand(0,2);
switch($m){
case 0:
$o = rand(48,57);
break;
case 1:
$o = rand(65,90);
break;
case 2:
$o = rand(97,122);
break;
}
$str .= sprintf("%c",$o);
}
break;
}


return $str;
}


// 3. 初始化画布图像资源
private function Hb(){
$this->hb = imagecreatetruecolor($this->width,$this->height);
}

// 4. 生成背景颜色
private function Bg(){
return imagecolorallocate($this->hb,rand(130,250),rand(130,250),rand(130,250));
}

// 5. 生成字体颜色
private function Font(){
return imagecolorallocate($this->hb,rand(0,100),rand(0,100),rand(0,100));
}

// 6. 填充背景颜色
private function BgColor(){
imagefilledrectangle($this->hb,0,0,$this->width,$this->height,$this->Bg());
}

// 7. 干扰点
private function ganrao(){
$sum=floor(($this->width)*($this->height)/3);
for($i=0;$i<$sum;$i++){
imagesetpixel($this->hb,rand(0,$this->width),rand(0,$this->height),$this->Bg());
}
}

// 8. 随机直线 弧线
private function huxian(){
for($i=0;$i<$this->num;$i++){
imageArc($this->hb,rand(0,$this->width),rand(0,$this->height),rand(0,$this->width),rand(0,$this->height),rand(0,360),rand(0,360),$this->Bg());
}
}

// 9. 写字
private function xiezi(){
for($i=0;$i<$this->num;$i++){
$x=ceil($this->width/$this->num)*$i;
$y=rand(1,$this->height-15);
imagechar($this->hb,5,$x+4,$y,$this->codestr[$i],$this->Font());
}
}

// 10. 输出
private function OutImg(){
$shuchu="image".$this->imgType;
$header="Content-type:image/".$this->imgType;
if(function_exists($shuchu)){
header($header);
$shuchu($this->hb);
}else{
exit("GD库没有此类图像");
}
}

// 11. 拼装
private function zuhe(){
$this->Hb();
$this->BgColor();
$this->ganrao();
$this->huxian();
$this->xiezi();
$this->OutImg();
}

public function getCodeStr(){
return $this->codestr;
}
}
?>

我们现在只要搜索文件上传类有大把,但是真正好用的上传类不多,下面我介绍这个文件上传类是我自己使用了很久,非常不错的一个代码,大家可参考参考一。
 代码如下 复制代码

<?php
 /**
  * 文件上传类
  */
 class uploadFile {
 
    public $max_size = '1000000';//设置上传文件大小
    public $file_name = 'date';//重命名方式代表以时间命名,其他则使用给予的名称
    public $allow_types;//允许上传的文件扩展名,不同文件类型用“|”隔开
    public $errmsg = '';//错误信息
    public $uploaded = '';//上传后的文件名(包括文件路径)
    public $save_path;//上传文件保存路径
    private $files;//提交的等待上传文件
    private $file_type = array();//文件类型
    private $ext = '';//上传文件扩展名
 
    /**
     * 构造函数,初始化类
     * @access public
     * @param string $file_name 上传后的文件名
     * @param string $save_path 上传的目标文件夹
     */
    public function __construct($save_path = './upload/',$file_name = 'date',$allow_types = '') {
        $this->file_name   = $file_name;//重命名方式代表以时间命名,其他则使用给予的名称
        $this->save_path   = (preg_match('//$/',$save_path)) ? $save_path : $save_path . '/';
        $this->allow_types = $allow_types == '' ? 'jpg|gif|png|zip|rar' : $allow_types;
    }
 
    /**
     * 上传文件
     * @access public
     * @param $files 等待上传的文件(表单传来的$_FILES[])
     * @return boolean 返回布尔值
     */
    public function upload_file($files) {
        $name = $files['name'];
        $type = $files['type'];
        $size = $files['size'];
        $tmp_name = $files['tmp_name'];
        $error = $files['error'];
 
        switch ($error) {
            case 0 : $this->errmsg = '';
                break;
            case 1 : $this->errmsg = '超过了php.ini中文件大小';
                break;
            case 2 : $this->errmsg = '超过了MAX_FILE_SIZE 选项指定的文件大小';
                break;
            case 3 : $this->errmsg = '文件只有部分被上传';
                break;
            case 4 : $this->errmsg = '没有文件被上传';
                break;
            case 5 : $this->errmsg = '上传文件大小为0';
                break;
            default : $this->errmsg = '上传文件失败!';
                break;
            }
        if($error == 0 && is_uploaded_file($tmp_name)) {
            //检测文件类型
            if($this->check_file_type($name) == FALSE){
                return FALSE;
            }
            //检测文件大小
            if($size > $this->max_size){
                $this->errmsg = '上传文件<font color=red>'.$name.'</font>太大,最大支持<font color=red>'.ceil($this->max_size/1024).'</font>kb的文件';
                return FALSE;
            }
            $this->set_save_path();//设置文件存放路径
            $new_name = $this->file_name != 'date' ? $this->file_name.'.'.$this->ext : date('YmdHis').'.'.$this->ext;//设置新文件名
            $this->uploaded = $this->save_path.$new_name;//上传后的文件名
            //移动文件
            if(move_uploaded_file($tmp_name,$this->uploaded)){
                $this->errmsg = '文件<font color=red>'.$this->uploaded.'</font>上传成功!';
                return TRUE;
            }else{
                $this->errmsg = '文件<font color=red>'.$this->uploaded.'</font>上传失败!';
                return FALSE;
            }
 
        }
    }
 
    /**
     * 检查上传文件类型
     * @access public
     * @param string $filename 等待检查的文件名
     * @return 如果检查通过返回TRUE 未通过则返回FALSE和错误消息
     */
    public function check_file_type($filename){
        $ext = $this->get_file_type($filename);
        $this->ext = $ext;
        $allow_types = explode('|',$this->allow_types);//分割允许上传的文件扩展名为数组
        //echo $ext;
        //检查上传文件扩展名是否在请允许上传的文件扩展名中
        if(in_array($ext,$allow_types)){
            return TRUE;
        }else{
            $this->errmsg = '上传文件<font color=red>'.$filename.'</font>类型错误,只支持上传<font color=red>'.str_replace('|',',',$this->allow_types).'</font>等文件类型!';
            return FALSE;
        }
    }
 
    /**
     * 取得文件类型
     * @access public
     * @param string $filename 要取得文件类型的目标文件名
     * @return string 文件类型
     */
    public function get_file_type($filename){
        $info = pathinfo($filename);
        $ext = $info['extension'];
        return $ext;
    }
 
    /**
     * 设置文件上传后的保存路径
     */
    public function set_save_path(){
        $this->save_path = (preg_match('//$/',$this->save_path)) ? $this->save_path : $this->save_path . '/';
        if(!is_dir($this->save_path)){
            //如果目录不存在,创建目录
            $this->set_dir();
        }
    }
 
 
    /**
     * 创建目录
     * @access public
     * @param string $dir 要创建目录的路径
     * @return boolean 失败时返回错误消息和FALSE
     */
    public function set_dir($dir = null){
        //检查路径是否存在
        if(!$dir){
            $dir = $this->save_path;
        }
        if(is_dir($dir)){
            $this->errmsg = '需要创建的文件夹已经存在!';
        }
        $dir = explode('/', $dir);
        foreach($dir as $v){
            if($v){
                $d .= $v . '/';
                if(!is_dir($d)){
                    $state = mkdir($d, 0777);
                    if(!$state)
                        $this->errmsg = '在创建目录<font color=red>' . $d . '时出错!';
                }
            }
        }
        return true;
    }
 }
 
/*************************************************
 * 图片处理类
 *
 * 可以对图片进行生成缩略图,打水印等操作
 * 本类默认编码为UTF8 如果要在GBK下使用请将img_mark方法中打中文字符串水印iconv注释去掉
 *
 * 由于UTF8汉字和英文字母大小(像素)不好确定,在中英文混合出现太多时可能会出现字符串偏左
 * 或偏右,请根据项目环境对get_mark_xy方法中的$strc_w = strlen($this->mark_str)*7+5进
 * 行调整
 * 需要GD库支持,为更好使用本类推荐使用GD库2.0+
 *
 * @author kickflip@php100 QQ263340607
 *************************************************/
 
 class uploadImg extends uploadFile {
 
    public $mark_str = 'kickflip@php100';  //水印字符串
    public $str_r = 0; //字符串颜色R
    public $str_g = 0; //字符串颜色G
    public $str_b = 0; //字符串颜色B
    public $mark_ttf = './upload/SIMSUN.TTC'; //水印文字字体文件(包含路径)
    public $mark_logo = './upload/logo.png';    //水印图片
    public $resize_h;//生成缩略图高
    public $resize_w;//生成缩略图宽
    public $source_img;//源图片文件
    public $dst_path = './upload/';//缩略图文件存放目录,不填则为源图片存放目录
 
    /**
     * 生成缩略图 生成后的图
     * @access public
     * @param integer $w 缩小后图片的宽(px)
     * @param integer $h 缩小后图片的高(px)
     * @param string $source_img 源图片(路径+文件名)
     */
    public function img_resized($w,$h,$source_img = NULL){
        $source_img = $source_img == NULL ? $this->uploaded : $source_img;//取得源文件的地址,如果为空则默认为上次上传的图片
        if(!is_file($source_img)) { //检查源图片是否存在
            $this->errmsg = '文件'.$source_img.'不存在';
            return FALSE;
        }
        $this->source_img = $source_img;
        $img_info = getimagesize($source_img);
        $source = $this->img_create($source_img); //创建源图片
        $this->resize_w = $w;
        $this->resize_h = $h;
        $thumb = imagecreatetruecolor($w,$h);
        imagecopyresized($thumb,$source,0,0,0,0,$w,$h,$img_info[0],$img_info[1]);//生成缩略图片
        $dst_path = $this->dst_path == '' ? $this->save_path : $this->dst_path; //取得目标文件夹路径
        $dst_path = (preg_match('//$/',$dst_path)) ? $dst_path : $dst_path . '/';//将目标文件夹后加上/
        if(!is_dir($dst_path)) $this->set_dir($dst_path); //如果不存在目标文件夹则创建
        $dst_name = $this->set_newname($source_img);
        $this->img_output($thumb,$dst_name);//输出图片
        imagedestroy($source);
        imagedestroy($thumb);
    }
 
    /**
     *打水印
     *@access public
     *@param string $source_img 源图片路径+文件名
     *@param integer $mark_type 水印类型(1为英文字符串,2为中文字符串,3为图片logo,默认为英文字符串)
     *@param integer $mark_postion 水印位置(1为左下角,2为右下角,3为左上角,4为右上角,默认为右下角);
     *@return 打上水印的图片
     */
    public function img_mark($source_img = NULL,$mark_type = 1,$mark_postion = 2) {
        $source_img = $source_img == NULL ? $this->uploaded : $source_img;//取得源文件的地址,如果为空则默认为上次上传的图片
        if(!is_file($source_img)) { //检查源图片是否存在
            $this->errmsg = '文件'.$source_img.'不存在';
            return FALSE;
        }
        $this->source_img = $source_img;
        $img_info = getimagesize($source_img);
        $source = $this->img_create($source_img); //创建源图片
        $mark_xy = $this->get_mark_xy($mark_postion);//取得水印位置
        $mark_color = imagecolorallocate($source,$this->str_r,$this->str_g,$this->str_b);
 
        switch($mark_type) {
 
            case 1 : //加英文字符串水印
            $str = $this->mark_str;
            imagestring($source,5,$mark_xy[0],$mark_xy[1],$str,$mark_color);
            $this->img_output($source,$source_img);
            break;
 
            case 2 : //加中文字符串水印
            if(!is_file($this->mark_ttf)) { //检查字体文件是否存在
                $this->errmsg = '打水印失败:字体文件'.$this->mark_ttf.'不存在!';
            return FALSE;
            }
            $str = $this->mark_str;
            //$str = iconv('gbk','utf-8',$str);//转换字符编码 如果使用GBK编码请去掉此行注释
            imagettftext($source,12,0,$mark_xy[2],$mark_xy[3],$mark_color,$this->mark_ttf,$str);
            $this->img_output($source,$source_img);
            break;
 
            case 3 : //加图片水印
            if(is_file($this->mark_logo)){  //如果存在水印logo的图片则取得logo图片的基本信息,不存在则退出
                $logo_info = getimagesize($this->mark_logo);
            }else{
                $this->errmsg = '打水印失败:logo文件'.$this->mark_logo.'不存在!';
                return FALSE;
            }
 
            $logo_info = getimagesize($this->mark_logo);
            if($logo_info[0]>$img_info[0] || $logo_info[1]>$img_info[1]) { //如果源图片小于logo大小则退出
                $this->errmsg = '打水印失败:源图片'.$this->source_img.'比'.$this->mark_logo.'小!';
                return FALSE;
            }
 
            $logo = $this->img_create($this->mark_logo);
            imagecopy ( $source, $logo, $mark_xy[4], $mark_xy[5], 0, 0, $logo_info[0], $logo_info[1]);
            $this->img_output($source,$source_img);
            break;
 
            default: //其它则为文字图片
            $str = $this->mark_str;
            imagestring($source,5,$mark_xy[0],$mark_xy[1],$str,$mark_color);
            $this->img_output($source,$source_img);
            break;
        }
        imagedestroy($source);
    }
 
    /**
     * 取得水印位置
     * @access private
     * @param integer $mark_postion 水印的位置(1为左下角,2为右下角,3为左上角,4为右上角,其它为右下角)
     * @return array $mark_xy 水印位置的坐标(索引0为英文字符串水印坐标X,索引1为英文字符串水印坐标Y,
     * 索引2为中文字符串水印坐标X,索引3为中文字符串水印坐标Y,索引4为水印图片坐标X,索引5为水印图片坐标Y)
     */
    private function get_mark_xy($mark_postion){
        $img_info = getimagesize($this->source_img);
 
        $stre_w = strlen($this->mark_str)*9+5 ; //水印英文字符串的长度(px)(5号字的英文字符大小约为9px 为了美观再加5px)
        //(12号字的中文字符大小为12px,在utf8里一个汉字长度为3个字节一个字节4px 而一个英文字符长度一个字节大小大约为9px
        // 为了在中英文混合的情况下显示完全 设它的长度为字节数*7px)
        $strc_w = strlen($this->mark_str)*7+5 ; //水印中文字符串的长度(px)
 
        if(is_file($this->mark_logo)){ //如果存在水印logo的图片则取得logo图片的基本信息
            $logo_info = getimagesize($this->mark_logo);
        }
 
        //由于imagestring函数和imagettftext函数中对于字符串开始位置不同所以英文和中文字符串的Y位置也有所不同
        //imagestring函数是从文字的左上角为参照 imagettftext函数是从文字左下角为参照
        switch($mark_postion){
 
            case 1: //位置左下角
            $mark_xy[0] = 5; //水印英文字符串坐标X
            $mark_xy[1] = $img_info[1]-20;//水印英文字符串坐标Y
            $mark_xy[2] = 5; //水印中文字符串坐标X
            $mark_xy[3] = $img_info[1]-5;//水印中文字符串坐标Y
            $mark_xy[4] = 5;//水印图片坐标X
            $mark_xy[5] = $img_info[1]-$logo_info[1]-5;//水印图片坐标Y
            break;
 
            case 2: //位置右下角
            $mark_xy[0] = $img_info[0]-$stre_w; //水印英文字符串坐标X
            $mark_xy[1] = $img_info[1]-20;//水印英文字符串坐标Y
            $mark_xy[2] = $img_info[0]-$strc_w; //水印中文字符串坐标X
            $mark_xy[3] = $img_info[1]-5;//水印中文字符串坐标Y
            $mark_xy[4] = $img_info[0]-$logo_info[0]-5;//水印图片坐标X
            $mark_xy[5] = $img_info[1]-$logo_info[1]-5;//水印图片坐标Y
            break;
 
            case 3: //位置左上角
            $mark_xy[0] = 5; //水印英文字符串坐标X
            $mark_xy[1] = 5;//水印英文字符串坐标Y
            $mark_xy[2] = 5; //水印中文字符串坐标X
            $mark_xy[3] = 15;//水印中文字符串坐标Y
            $mark_xy[4] = 5;//水印图片坐标X
            $mark_xy[5] = 5;//水印图片坐标Y
            break;
 
            case 4: //位置右上角
            $mark_xy[0] = $img_info[0]-$stre_w; //水印英文字符串坐标X
            $mark_xy[1] = 5;//水印英文字符串坐标Y
            $mark_xy[2] = $img_info[0]-$strc_w; //水印中文字符串坐标X
            $mark_xy[3] = 15;//水印中文字符串坐标Y
            $mark_xy[4] = $img_info[0]-$logo_info[0]-5;//水印图片坐标X
            $mark_xy[5] = 5;//水印图片坐标Y
            break;
 
            default : //其它默认为右下角
            $mark_xy[0] = $img_info[0]-$stre_w; //水印英文字符串坐标X
            $mark_xy[1] = $img_info[1]-5;//水印英文字符串坐标Y
            $mark_xy[2] = $img_info[0]-$strc_w; //水印中文字符串坐标X
            $mark_xy[3] = $img_info[1]-15;//水印中文字符串坐标Y
            $mark_xy[4] = $img_info[0]-$logo_info[0]-5;//水印图片坐标X
            $mark_xy[5] = $img_info[1]-$logo_info[1]-5;//水印图片坐标Y
            break;
        }
        return $mark_xy;
    }
 
    /**
     * 创建源图片
     * @access private
     * @param string $source_img 源图片(路径+文件名)
     * @return img 从目标文件新建的图像
     */
    private function img_create($source_img) {
        $info = getimagesize($source_img);
        switch ($info[2]){
            case 1:
            if(!function_exists('imagecreatefromgif')){
                $source = @imagecreatefromjpeg($source_img);
            }else{
                $source = @imagecreatefromgif($source_img);
            }
            break;
            case 2:
            $source = @imagecreatefromjpeg($source_img);
            break;
            case 3:
            $source = @imagecreatefrompng($source_img);
            break;
            case 6:
            $source = @imagecreatefromwbmp($source_img);
            break;
            default:
            $source = FALSE;
            break;
        }
        return $source;
    }
 
 /**
  * 重命名图片
  * @access private
  * @param string $source_img 源图片路径+文件名
  * @return string $dst_name 重命名后的图片名(路径+文件名)
  */
 private function set_newname($sourse_img) {
    $info = pathinfo($sourse_img);
    $new_name = $this->resize_w.'_'.$this->resize_h.'_'.$info['basename'];//将文件名修改为:宽_高_文件名
    if($this->dst_path == ''){ //如果存放缩略图路径为空则默认为源文件同文件夹
        $dst_name = str_replace($info['basename'],$new_name,$sourse_img);
    }else{
        $dst_name = $this->dst_path.$new_name;
    }
    return $dst_name;
 }
 
 /**
  * 输出图片
  * @access private
  * @param $im 处理后的图片
  * @param $dst_name 输出后的的图片名(路径+文件名)
  * @return 输出图片
  */
 public function img_output($im,$dst_name) {
    $info = getimagesize($this->source_img);
    switch ($info[2]){
            case 1:
            if(!function_exists('imagegif')){
                imagejpeg($im,$dst_name);
            }else{
                imagegif($im, $dst_name);
            }
            break;
            case 2:
            imagejpeg($im,$dst_name);
            break;
            case 3:
            imagepng($im,$dst_name);
            break;
            case 6:
            imagewbmp($im,$dst_name);
            break;
        }
 }
 
 }
?>

使用方法

 代码如下 复制代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>上传文件</title></head><body leftmargin="0" topmargin="0"><table cellpadding="2" cellspacing="1" border="0" height="100%" align="left"><form action='wend.php?action=upload'  method='post' enctype='multipart/form-data'><tr ><td  valign='middle'><input type='file' name='uploadfile'><input name='submit' type='submit' value='上传'></td></tr></form></table</body></html>

php处理文件

调用上面的类文件,然后再如下操作

 代码如下 复制代码

$action = addslashes($_GET['action']);
if( $action =="udd")
{
 $state=uploadfile('uploadfile');
 //echo $state['err'];exit;
 if($state['err']){
  die('<script>alert("上传出错:'.$state['err'].'");history.go(-1);</script>');
 }
 else
 {
  echo '文件己上传!<a href="upp.php">删除重传</a>';
  
 }


}
else{
 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
 echo '<html xmlns="http://www.w3.org/1999/xhtml">';
 echo '<head>';
 echo '<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />';
 echo '<title>上传文件</title>';
 //echo "<meta http-equiv="content-type" content="text/html; charset=gb2312">";
 echo '</head>';
 echo "<body leftmargin="0" topmargin="0">";
 echo "<table cellpadding="2" cellspacing="1" border="0" height="100%" align="left">";
 echo "<form action='abc.php?action=udd'  method='post' enctype='multipart/form-data'>";
 echo "<tr ><td  valign='middle'>";
 echo "<input type='file' name='uploadfile'>";
 echo "<input name='submit' type='submit' value='上传'>";
 echo "</td></tr>";
 echo "</form>";
 echo "</table";
 echo "</body>";
 echo '</html>';
}

在php中我们经常使用写一些简单的采集功能,这样可以自动把远程服务器的图片或资源直接采集保存到本地服务器中,下面我来给大家详细介绍远程图片并把它保存到本地几种方法。

例1

 代码如下 复制代码

/*
*功能:php多种方式完美实现下载远程图片保存到本地
*参数:文件url,保存文件名称,使用的下载方式
*当保存文件名称为空时则使用远程文件原来的名称
*/
function getImage($url,$filename='',$type=0){
    if($url==''){return false;}
    if($filename==''){
        $ext=strrchr($url,'.');
        if($ext!='.gif' && $ext!='.jpg'){return false;}
        $filename=time().$ext;
    }
    //文件保存路径
    if($type){
  $ch=curl_init();
  $timeout=5;
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
  $img=curl_exec($ch);
  curl_close($ch);
    }else{
     ob_start();
     readfile($url);
     $img=ob_get_contents();
     ob_end_clean();
    }
    $size=strlen($img);
    //文件大小
    $fp2=@fopen($filename,'a');
    fwrite($fp2,$img);
    fclose($fp2);
    return $filename;
}

例2

 代码如下 复制代码

<?php

//
// Function: 获取远程图片并把它保存到本地
//
//
//   确定您有把文件写入本地服务器的权限
// 
//
// 变量说明:
// $url 是远程图片的完整URL地址,不能为空。
// $filename 是可选变量: 如果为空,本地文件名将基于时间和日期
// 自动生成.

function GrabImage($url,$filename="") {
   if($url==""):return false;endif;

   if($filename=="") {
     $ext=strrchr($url,".");
     if($ext!=".gif" && $ext!=".jpg"):return false;endif;
     $filename=date("dMYHis").$ext;
   }

   ob_start();
   readfile($url);
   $img = ob_get_contents();
   ob_end_clean();
   $size = strlen($img);

   $fp2=@fopen($filename, "a");
   fwrite($fp2,$img);
   fclose($fp2);

   return $filename;
}


$img=GrabImage("http://www.111cn.net","");
if($img):echo '<pre><img src="'.$img.'"></pre>';else:echo "false";endif;  

?>


dedecms中的:

 

 代码如下 复制代码
if(!empty($saveremoteimg))
         {
                 $body = stripslashes($body);
                 $img_array = array();
                 preg_match_all("/(src|SRC)=["|'| ]{0,}(http://(.*).(gif|jpg|jpeg|bmp|png))/isU",$body,$img_array);
                 $img_array = array_unique($img_array[2]);
                 set_time_limit(0);
                 $imgUrl = $img_dir."/".strftime("%Y%m%d",time());
                 $imgPath = $base_dir.$imgUrl;
                 $milliSecond = strftime("%H%M%S",time());
                 if(!is_dir($imgPath)) @mkdir($imgPath,0777);
                 foreach($img_array as $key =>$value)
                 {
                         $value = trim($value);
                         $get_file = @file_get_contents($value);
                         $rndFileName = $imgPath."/".$milliSecond.$key.".".substr($value,-3,3);
                         $fileurl = $imgUrl."/".$milliSecond.$key.".".substr($value,-3,3);
                         if($get_file)
                         {
                                 $fp = @fopen($rndFileName,"w");
                                 @fwrite($fp,$get_file);
                                 @fclose($fp);
                         }
                         $body = ereg_replace($value,$fileurl,$body);
                 }
                 $body = addslashes($body);
         }
?>

例4

 代码如下 复制代码

<?php
//
// Function: 获取远程图片并把它保存到本地
//
//
// 确定您有把文件写入本地服务器的权限
//
//
// 变量说明:
// $url 是远程图片的完整URL地址,不能为空。
// $filename 是可选变量: 如果为空,本地文件名将基于时间和日期// 自动生成.
function GrabImage($url,$filename='') {
if($url==''):return false;endif;
if($filename=='') {
$ext=strrchr($url,'.');
if($ext!='.gif' && $ext!='.jpg'):return false;endif;$filename=date('dMYHis').$ext;
}
ob_start();
readfile($url);
$img = ob_get_contents();
ob_end_clean();
$size = strlen($img);
$fp2=@fopen($filename, 'a');
fwrite($fp2,$img);
fclose($fp2);
return $filename;
}
$img=GrabImage('http://www.ccc.cc/static/image/common/logo.png','');
if($img){echo '<pre><img src='.$img.'></pre>';}else{echo 'false';}
?>

我们会看到很多的网站不但有设置首页,加入收藏同时还有一个加和到桌面快捷方式的功能,下面我来给大家介绍网页创建快捷方式到桌面多种方法介绍。有需要的朋友可参考。

最简单的js实现方法

 代码如下 复制代码

<script language="JavaScript"> 

function toDesktop(sUrl,sName){ 

try 

var WshShell = new ActiveXObject("WScript.Shell"); 

var oUrlLink = WshShell.CreateShortcut(WshShell.SpecialFolders("Desktop") + "\" + sName + ".url"); 

oUrlLink.TargetPath = sUrl; 

oUrlLink.Save(); 

catch(e) 

alert("请点击弹出对话框的:是 "); 

</script> 

<input name="btn" type="button" id="btn" value="把百度创建快捷方式到桌面" onClick="toDesktop('http://www.111cn.net/','百度一下,你就知道!')"> 

<input name="btn" type="button" id="btn" value="C盘" onClick="toDesktop('file://C:','C盘')"> 

不足:这样做如果浏览器做了安全设置我们是不能使用上面的方法的。

写php程序的朋友可能也知道一种办法,代码如下

 代码如下 复制代码

<?php 

$Shortcut = "[InternetShortcut] 

URL=http://www.111cn.net 

IconFile=http://www.111cn.net/favicon.ico 

IconIndex=0 

HotKey=1613 

IDList= 

[{000214A0-0000-0000-C000-000000000046}] 

Prop3=19,2"; 

header("Content-Type: application/octet-stream"); 

header("Content-Disposition: attachment; filename=蜕变无忧.url"); 

echo $Shortcut; 

?> 


<a href="">发送到桌面</a> 


asp.net程序员可能也知道如下代码

 

 代码如下 复制代码
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class CreateShortcut : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
{
}
/// <summary>
/// 创建快捷方式
/// </summary>
/// <param name="Title">标题</param>
/// <param name="URL">URL地址</param>
private void CreateShortcut(string Title, string URL)
{
string strFavoriteFolder;
// “收藏夹”中 创建 IE 快捷方式
strFavoriteFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.Favorites);
CreateShortcutFile(Title, URL, strFavoriteFolder);
// “ 桌面 ”中 创建 IE 快捷方式
strFavoriteFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
CreateShortcutFile(Title, URL, strFavoriteFolder);
// “ 链接 ”中 创建 IE 快捷方式
strFavoriteFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.Favorites) + "\链接";
CreateShortcutFile(Title, URL, strFavoriteFolder);
//「开始」菜单中 创建 IE 快捷方式
strFavoriteFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.StartMenu);
CreateShortcutFile(Title, URL, strFavoriteFolder);
}
/// <summary>
/// 创建快捷方式
/// </summary>
/// <param name="Title">标题</param>
/// <param name="URL">URL地址</param>
/// <param name="SpecialFolder">特殊文件夹</param>
private void CreateShortcutFile(string Title, string URL, string SpecialFolder)
{
// Create shortcut file, based on Title
System.IO.StreamWriter objWriter = System.IO.File.CreateText(SpecialFolder + "\" + Title + ".url");
// Write URL to file
objWriter.WriteLine("[InternetShortcut]");
objWriter.WriteLine("URL=" + URL);
// Close file
objWriter.Close();
}
private void btnShortcut_Click(object sender, System.EventArgs e)
{
CreateShortcut("脚本之家", http://www.111cn.net);
}
}
在php中要模拟post请求数据提交我们会使用到curl函数,下面我来给大家举几个curl模拟post请求提交数据例子有需要的朋友可参考参考。

注意:curl函数在php中默认是不被支持的,如果需要使用curl函数我们需在改一改你的php.ini文件的设置,找到php_curl.dll去掉前面的";"就行了

例1

 代码如下 复制代码

<?php
$uri = "http://tanteng.duapp.com/test.php";
// 参数数组
$data = array (
        'name' => 'tanteng'
// 'password' => 'password'
);
 
$ch = curl_init ();
// print_r($ch);
curl_setopt ( $ch, CURLOPT_URL, $uri );
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_HEADER, 0 );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
$return = curl_exec ( $ch );
curl_close ( $ch );
 
print_r($return);

接受php页面远程服务器:

<?php
if(isset($_POST['name'])){
    if(!empty($_POST['name'])){
        echo '您好,',$_POST['name'].'!';
    }
}
?>

例2

用CURL模拟POST请求抓取邮编与地址

完整代码:

 代码如下 复制代码

#!/usr/local/php/bin/php
<?php
$runtime = new runtime ();
$runtime->start ();


$cookie_jar = tempnam('/tmp','cookie');

 


$filename = $argv[1];
$start_num= $argv[2];
$end_num  = $argv[3];

 


for($i=$start_num; $i<$end_num; $i++){
    $zip = sprintf('6s',$i);


    $fields_post = array(
            'postcode' => $zip,
            'queryKind' => 2,
            'reqCode' => 'gotoSearch',
            'search_button.x'=>37,
            'search_button.y'=>12
            );


    $fields_string = http_build_query ( $fields_post, '&' );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "URL?reqCode=gotoSearch&queryKind=2&postcode=".$zip);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120 );
    curl_setopt($ch, CURLOPT_REFERER, $refer );
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_login );
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar );
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar );
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_POST, 1); // 发送一个常规的Post请求
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string );


    $data = curl_exec($ch);
    preg_match_all('/id="table1">[s]*?<tr>[s]*?<td class="maintext">[sS]*?</td>[s]*?</tr>/', $data, $matches);
    if (!$handle = fopen($filename, 'a+')) {
        echo "不能打开文件 $filename";
        echo "n";
        exit;
    }


    if (fwrite($handle, $matches[0][1]) === FALSE) {
        echo "不能写入到文件 $filename";
        echo "n";
        exit;
    }


    echo "成功地将 $somecontent 写入到文件$filename";
    echo "n";


    fclose($handle);
    curl_close($ch);
}

 


class runtime
{
    var $StartTime = 0;
    var $StopTime = 0;
    function get_microtime()
    {
        list($usec,$sec)=explode(' ',microtime());return((float)$usec+(float)$sec);
    }
    function start()
    {
        $this->StartTime=$this->get_microtime();
    }
    function stop(){
        $this->StopTime=$this->get_microtime();
    }
    function spent()
    {
        return ($this->StopTime-$this->StartTime);
    }
}

 


$runtime->stop ();


$con = 'Processed in'.$runtime->spent().'seconds';
echo 'Processed in'. $runtime->spent().'seconds';

模拟POST请求 提交数据或上传文件 .

.

 代码如下 复制代码

http://www.a.com/a.php

发送POST请求

function execUpload(){


$file = '/doucment/Readme.txt';
$ch = curl_init();
$post_data = array(
    'loginfield' => 'username',
    'username' => 'ybb',
    'password' => '123456',
'file' => '@d:usrwwwtranslatedocumentReadme.txt'
);
curl_setopt($ch, CURLOPT_HEADER, false);
//启用时会发送一个常规的POST请求,类型为:application/x-www-form-urlencoded,就像表单提交的一样。
curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch,CURLOPT_BINARYTRANSFER,true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
curl_setopt($ch, CURLOPT_URL, 'http://www.b.com/handleUpload.php');
$info= curl_exec($ch);
curl_close($ch);
  
print_r($info);

}

2.http://www.b.com/handleUpload.php

function handleUpload(){
print_r($_POST);
echo '===file upload info:';
print_r($_FILES);
}

■cURL 函数

■curl_close — 关闭一个cURL会话
■curl_copy_handle — 复制一个cURL句柄和它的所有选项
■curl_errno — 返回最后一次的错误号
■curl_error — 返回一个保护当前会话最近一次错误的字符串
■curl_exec — 执行一个cURL会话
■curl_getinfo — 获取一个cURL连接资源句柄的信息
■curl_init — 初始化一个cURL会话
■curl_multi_add_handle — 向curl批处理会话中添加单独的curl句柄
■curl_multi_close — 关闭一组cURL句柄
■curl_multi_exec — 运行当前 cURL 句柄的子连接
■curl_multi_getcontent — 如果设置了CURLOPT_RETURNTRANSFER,则返回获取的输出的文本流
■curl_multi_info_read — 获取当前解析的cURL的相关传输信息
■curl_multi_init — 返回一个新cURL批处理句柄
■curl_multi_remove_handle — 移除curl批处理句柄资源中的某个句柄资源
■curl_multi_select — 等待所有cURL批处理中的活动连接
■curl_setopt_array — 为cURL传输会话批量设置选项
■curl_setopt — 设置一个cURL传输选项
■curl_version — 获取cURL版本信息

[!--infotagslink--]

相关文章

  • 不打开网页直接查看网站的源代码

      有一种方法,可以不打开网站而直接查看到这个网站的源代码..   这样可以有效地防止误入恶意网站...   在浏览器地址栏输入:   view-source:http://...2016-09-20
  • php 调用goolge地图代码

    <?php require('path.inc.php'); header('content-Type: text/html; charset=utf-8'); $borough_id = intval($_GET['id']); if(!$borough_id){ echo ' ...2016-11-25
  • JS基于Mootools实现的个性菜单效果代码

    本文实例讲述了JS基于Mootools实现的个性菜单效果代码。分享给大家供大家参考,具体如下:这里演示基于Mootools做的带动画的垂直型菜单,是一个初学者写的,用来学习Mootools的使用有帮助,下载时请注意要将外部引用的mootools...2015-10-23
  • JS+CSS实现分类动态选择及移动功能效果代码

    本文实例讲述了JS+CSS实现分类动态选择及移动功能效果代码。分享给大家供大家参考,具体如下:这是一个类似选项卡功能的选择插件,与普通的TAb区别是加入了动画效果,多用于商品类网站,用作商品分类功能,不过其它网站也可以用,...2015-10-21
  • JS实现自定义简单网页软键盘效果代码

    本文实例讲述了JS实现自定义简单网页软键盘效果。分享给大家供大家参考,具体如下:这是一款自定义的简单点的网页软键盘,没有使用任何控件,仅是为了练习JavaScript编写水平,安全性方面没有过多考虑,有顾虑的可以不用,目的是学...2015-11-08
  • php 取除连续空格与换行代码

    php 取除连续空格与换行代码,这些我们都用到str_replace与正则函数 第一种: $content=str_replace("n","",$content); echo $content; 第二种: $content=preg_replac...2016-11-25
  • PHP 验证码不显示只有一个小红叉的解决方法

    最近想自学PHP ,做了个验证码,但不知道怎么搞的,总出现一个如下图的小红叉,但验证码就是显示不出来,原因如下 未修改之前,出现如下错误; (1)修改步骤如下,原因如下,原因是apache权限没开, (2)点击打开php.int., 搜索extension=ph...2013-10-04
  • php简单用户登陆程序代码

    php简单用户登陆程序代码 这些教程很对初学者来讲是很有用的哦,这款就下面这一点点代码了哦。 <center> <p>&nbsp;</p> <p>&nbsp;</p> <form name="form1...2016-11-25
  • PHP实现清除wordpress里恶意代码

    公司一些wordpress网站由于下载的插件存在恶意代码,导致整个服务器所有网站PHP文件都存在恶意代码,就写了个简单的脚本清除。恶意代码示例...2015-10-23
  • JS实现双击屏幕滚动效果代码

    本文实例讲述了JS实现双击屏幕滚动效果代码。分享给大家供大家参考,具体如下:这里演示双击滚屏效果代码的实现方法,不知道有觉得有用处的没,现在网上还有很多还在用这个特效的呢,代码分享给大家吧。运行效果截图如下:在线演...2015-10-30
  • js识别uc浏览器的代码

    其实挺简单的就是if(navigator.userAgent.indexOf('UCBrowser') > -1) {alert("uc浏览器");}else{//不是uc浏览器执行的操作}如果想测试某个浏览器的特征可以通过如下方法获取JS获取浏览器信息 浏览器代码名称:navigator...2015-11-08
  • jQuery Real Person验证码插件防止表单自动提交

    本文介绍的jQuery插件有点特殊,防自动提交表单的验证工具,就是我们经常用到的验证码工具,先给大家看看效果。效果图如下: 使用说明 需要使用jQuery库文件和Real Person库文件 同时需要自定义验证码显示的CSS样式 使用实例...2015-11-08
  • JS日期加减,日期运算代码

    一、日期减去天数等于第二个日期function cc(dd,dadd){//可以加上错误处理var a = new Date(dd)a = a.valueOf()a = a - dadd * 24 * 60 * 60 * 1000a = new Date(a)alert(a.getFullYear() + "年" + (a.getMonth() +...2015-11-08
  • JS实现随机生成验证码

    这篇文章主要为大家详细介绍了JS实现随机生成验证码,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-06
  • PHP开发微信支付的代码分享

    微信支付,即便交了保证金,你还是处理测试阶段,不能正式发布。必须到你通过程序测试提交订单、发货通知等数据到微信的系统中,才能申请发布。然后,因为在微信中是通过JS方式调用API,必须在微信后台设置支付授权目录,而且要到...2014-05-31
  • php二维码生成

    本文介绍两种使用 php 生成二维码的方法。 (1)利用google生成二维码的开放接口,代码如下: /** * google api 二维码生成【QRcode可以存储最多4296个字母数字类型的任意文本,具体可以查看二维码数据格式】 * @param strin...2015-10-21
  • Java生成随机姓名、性别和年龄的实现示例

    这篇文章主要介绍了Java生成随机姓名、性别和年龄的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-10-01
  • PHP常用的小程序代码段

    本文实例讲述了PHP常用的小程序代码段。分享给大家供大家参考,具体如下:1.计算两个时间的相差几天$startdate=strtotime("2009-12-09");$enddate=strtotime("2009-12-05");上面的php时间日期函数strtotime已经把字符串...2015-11-24
  • 几种延迟加载JS代码的方法加快网页的访问速度

    本文介绍了如何延迟javascript代码的加载,加快网页的访问速度。 当一个网站有很多js代码要加载,js代码放置的位置在一定程度上将会影像网页的加载速度,为了让我们的网页加载速度更快,本文总结了一下几个注意点...2013-10-13
  • C#生成随机数功能示例

    这篇文章主要介绍了C#生成随机数功能,涉及C#数学运算与字符串操作相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25