分类:PHP     文章(11) 篇

C++ POST到PHP (2010-08-17)

今天做WAP版的网站,与C++那边配合
从C++ POST过来的的值用$_POST怎么也接收不到
无论打印 print_r($_POST) 和 print_r($_REQUEST); 都是0
把我郁闷坏了,但是GET值可以接收得到
就要快放弃的时候,找到一个方法
$key=file_get_contents("php://input");
print_r($key);
这样就可以接收到值了,是POST的原始数据
C++ POST给PHP数据用普通的$_POST方法接收不到任何值
没想到还有这种用方法接收POST!
 这个问题搞了一天 不过又学会一个小技巧,还算值了!

点击查看原文阅读(88) | 评论(1) | 分类:PHP

PHPACL角色权限控制 (2010-05-23)

PHP ACL角色权限类,能实现无限角色权限的访问控制
网上关于RBAC方面资料比较少!
原理很简单,就是在执行control 前检查controller和action在acl表中的权限,
判断当前的访问者“可以”或“不可以”访问某个action的机制
满足条件就继续执行,否则跳转的制定页面
 

代码如下
  1. <?php
  2. class Acl{
  3.     /**
  4.      * 默认权限检查的处理程序设置,可以是函数名或是数组(array(类名,方法)的形式)
  5.      */
  6.     public $checker = array('spAclModel','check');
  7.  
  8.     /**
  9.      * 默认提示无权限提示,可以是函数名或是数组(array(类名,方法)的形式)
  10.      */
  11.     public $prompt = array('spAcl','def_prompt');
  12.     /**
  13.      * 构造函数,设置权限检查程序与提示程序
  14.      */
  15.     public function __construct(){
  16.         $params = spExt("spAcl");
  17.         if( !empty($params["prompt"]) )$this->prompt = $params["prompt"];
  18.         if( !empty($params["checker"]) )$this->checker = $params["checker"];
  19.     }
  20.  
  21.     /**
  22.      * 获取当前会话的用户标识
  23.      */
  24.     public function get(){
  25.         return $_SESSION["SpAclSession"];
  26.     }
  27.  
  28.     /**
  29.      * 强制控制的检查程序,适用于后台。无权限控制的页面均不能进入
  30.      */
  31.     public function maxcheck(){
  32.         $acl_handle = $this->check();
  33.         if( 1 !== $acl_handle ){
  34.             $this->prompt();
  35.             return FALSE;
  36.         }
  37.         return TRUE;
  38.     }
  39.  
  40.     /**
  41.      * 有限的权限控制,适用于前台。仅在权限表声明禁止的页面起作用,其他无声明页面均可进入
  42.      */
  43.     public function mincheck(){
  44.         $acl_handle = $this->check();
  45.         if( 0 === $acl_handle ){
  46.             $this->prompt();
  47.             return FALSE;
  48.         }
  49.         return TRUE;
  50.     }
  51.  
  52.     /**
  53.      * 使用程序调度器进行检查等处理
  54.      */
  55.     private function check(){
  56.         GLOBAL $__controller, $__action;
  57.         $checker = $this->checker; $name = $this->get();
  58.  
  59.         if( is_array($checker) ){
  60.             return spClass($checker[0])->{$checker[1]}($name, $__controller, $__action);
  61.         }else{
  62.             return call_user_func_array($checker, array($name, $__controller, $__action));
  63.         }
  64.     }
  65.     /**
  66.      * 无权限提示跳转
  67.      */
  68.     public function prompt(){
  69.         $prompt = $this->prompt;
  70.         if( is_array($prompt) ){
  71.             return spClass($prompt[0])->{$prompt[1]}();
  72.         }else{
  73.             return call_user_func_array($prompt,array());
  74.         }
  75.     }
  76.  
  77.     /**
  78.      * 默认的无权限提示跳转
  79.      */
  80.     public function def_prompt(){
  81.         $url = spUrl(); // 跳转到首页,在强制权限的情况下,请将该页面设置成可以进入。
  82.         echo "<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><script>function sptips(){alert("Access Failed!");location.href="{$url}";}</script></head><body onload="sptips()"></body></html>";
  83.         exit;
  84.     }
  85.  
  86.     /**
  87.      * 设置当前用户,内部使用SESSION记录
  88.      *
  89.      * @param acl_name    用户标识:可以是组名或用户名
  90.      */
  91.     public function set($acl_name){
  92.         $_SESSION["SpAclSession"] = $acl_name;
  93.     }
  94.  
  95.     /**
  96.      * 获取安全加密的密码输入框,开发者将需要在HTML中form标签上加入<code>onsubmit="aclcode();"</code>来触发加密
  97.      *
  98.      * @param id    在input框的id值。
  99.      * @param add    在input框内的其他内容,除id外,name,class等均可。
  100.      */
  101.     public function pwinput($id, $add = null){
  102.         $raphash = substr(md5(mt_rand(10000,99999)),2,12);
  103.         $html = "<script type='text/javascript'>".spAcl::getmd5()."</script>";
  104.         $html .= "<script type='text/javascript'>function aclcode(){aclpwinput=document.getElementById('{$id}');document.getElementById('{$raphash}').value = hex_md5(aclpwinput.value);aclpwinput.value = '0000000000000000';}</script>";
  105.         $html .= "<input type='password' id='{$id}' {$add}>";
  106.         $html .= "<input type='hidden' id='{$raphash}' name='{$raphash}'>";
  107.         $_SESSION["SpAclInputHash"] = $raphash;
  108.         return $html;
  109.     }
  110.     /**
  111.      * 辅助pwinput的函数,让pwinput可在模板中使用。
  112.      * @param params 传入的参数
  113.      */
  114.     public function smarty_pwinput($params){
  115.         return spAcl::pwinput($params["id"],$params["add"]);
  116.     }
  117.     /**
  118.      * 获取加密后的密码,该密码为MD5加密后的字符串
  119.      *
  120.      * 请注意返回值:
  121.      *
  122.      * -1 是无hash值,可以判断为远程提交等方式的攻击或是访问超时。需要重新访问登录页面。
  123.      * false 是没有输入密码,或是远程提交导致无法获取到正确的hash码。同样要求重新访问登录页面以再次输入密码提交。
  124.      * MD5编码后的密码
  125.      */
  126.     public function pwvalue()
  127.     {
  128.         if(empty($_SESSION["SpAclInputHash"]))return -1;
  129.         $md5pw = spClass("spArgs")->get($_SESSION["SpAclInputHash"],false);
  130.         unset($_SESSION["SpAclInputHash"]);
  131.         return $md5pw;
  132.     }
  133.  
  134. }
  135.  
  136. class spAclModel extends spModel{
  137.  
  138.     public $pk = 'aclid';
  139.     /**
  140.      * 表名
  141.      */
  142.     public $table = 'acl';
  143.  
  144.     /**
  145.      * 检查对应的权限
  146.      *
  147.      * 返回1是通过检查,0是不能通过检查(控制器及动作存在但用户标识没有记录)
  148.      * 返回-1是无该权限控制(即该控制器及动作不存在于权限表中)
  149.      *
  150.      * @param acl_name    用户标识:可以是组名或是用户名
  151.      * @param controller    控制器名称
  152.      * @param action    动作名称
  153.      */
  154.     public function check($acl_name = SPANONYMOUS, $controller, $action){
  155.         $rows = array('controller' => $controller, 'action' => $action );
  156.         if( $acl = $this->findAll($rows) ){
  157.             foreach($acl as $v){
  158.                 if($v["acl_name"] == SPANONYMOUS || $v["acl_name"] == $acl_name)return 1;
  159.             }
  160.             return 0;
  161.         }else{
  162.             return -1;
  163.         }
  164.     }
  165. }
  166. ?>

点击查看原文阅读(252) | 评论(2) | 分类:PHP

封装PHP验证码类 (2010-03-05)

PHP验证码是很常见的应用
下面是一段封装好的类库
方便以后使用
 

总结一下核心函数:
imagecreate 创建图像;
imagecolorallocate  为图像上色
imagerectangle 创建矩形
imagestring 画字符串
imageline 生成干扰线
imagejpeg 生成JPEG格式
imagedestroy 催婚图像

PHP验证码类
  1. <?php
  2. session_start();
  3. class checkImage {
  4.  
  5.     private $config;
  6.     private $im;
  7.     private $str;
  8.  
  9.     function __construct() {
  10.         $this->config['width']      = 50;
  11.         $this->config['height']     = 20;
  12.         $this->config['vcode']      = "vcode";
  13.         $this->config['type']       = "default";
  14.         $this->config['length']     = 4;
  15.         $this->config['interfere']  = 10;
  16.         $this->str['default']       = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  17.         $this->str['string']        = "abcdefghijklmnopqrstuvwxyz";
  18.         $this->str['int']           = "0123456789";
  19.     }
  20.  
  21.     public function init($config=array()){
  22.         if (!empty($config) && is_array($config)){
  23.             foreach($config as $key=>$value){
  24.                 $this->config[$key] =   $value;
  25.             }
  26.         }
  27.     }
  28.  
  29.     public function create(){
  30.         if (!function_exists("imagecreate")){
  31.             return false;
  32.         }
  33.         $this->createImage();
  34.     }
  35.  
  36.     private function createImage(){
  37.         $this->im   =   imagecreate($this->config['width'],$this->config['height']);
  38.         imagecolorallocate($this->im, 255, 255, 255);
  39.  
  40.         $bordercolor=   imagecolorallocate($this->im,0,0,0);
  41.         imagerectangle($this->im,0,0,$this->config['width']-1,$this->config['height']-1,$bordercolor);
  42.  
  43.         $this->createStr();
  44.         $vcode  =   $_SESSION[$this->config['vcode']];
  45.         $fontcolor  =   imagecolorallocate($this->im,46,46,46);
  46.         for($i=0;$i<$this->config['length'];$i++){
  47.             imagestring($this->im,5,$i*10+6,rand(2,5),$vcode[$i],$fontcolor);
  48.         }
  49.  
  50.         $interfere  =   $this->config['interfere'];
  51.         $interfere  =   $interfere>30?"30":$interfere;
  52.         if (!empty($interfere) && $interfere>1){
  53.             for($i=1;$i<$interfere;$i++){
  54.                 $linecolor  =   imagecolorallocate($this->im,rand(0,255),rand(0,255),rand(0,255));
  55.                 $x  =   rand(1,$this->config['width']);
  56.                 $y  =   rand(1,$this->config['height']);
  57.                 $x2 =   rand($x-10,$x+10);
  58.                 $y2 =   rand($y-10,$y+10);
  59.                 imageline($this->im,$x,$y,$x2,$y2,$linecolor);
  60.             }
  61.         }
  62.         header("Pragma:no-cachern");
  63.         header("Cache-Control:no-cachern");
  64.         header("Expires:0rn");
  65.         header("content-type:image/jpegrn");
  66.         imagejpeg($this->im);
  67.         imagedestroy($this->im);
  68.         exit;
  69.     }
  70.  
  71.     private function createStr(){
  72.         if ($this->config['type']=="int"){
  73.             for($i=1;$i<=$this->config['length'];$i++){
  74.                 $vcode  .=  rand(0,9);
  75.             }
  76.             $_SESSION[$this->config['vcode']] = $vcode;
  77.             return true;
  78.         }
  79.         $len    =   strlen($this->str[$this->config['type']]);
  80.         if (!$len){
  81.             $this->config['type'] = "default";
  82.             $this->create_str();
  83.         }
  84.         for($i=1;$i<=$this->config['length'];$i++){
  85.             $offset  =  rand(0,$len-1);
  86.             $vcode  .=  substr($this->str[$this->config['type']],$offset,1);
  87.         }
  88.         $_SESSION[$this->config['vcode']] = $vcode;
  89.         return true;
  90.     }
  91.  
  92. }
  93.  
  94. $v = new checkImage();
  95. //$config['width']  =   50;         //验证码宽
  96. //$config['height'] =   20;         //验证码高
  97. //$config['vcode']  =   "vcode";    //检查验证码时用的SESSION
  98. //$config['type']   =   "int";  //验证码展示的类型default:大写字母,string:小写字母,int:数字
  99. //$config['length'] =   2;          //验证码长度
  100. //$config['interfere']= 10;         //干扰线强度,范围为1-30,0或空为不起用干扰线
  101. //$v->init($config);    //配置
  102. $v->create();
  103.  
  104. ?>
  105.  
  106. <SCRIPT LANGUAGE="JavaScript">
  107.     <!--
  108.         function reloadcode(){
  109.          var d = new Date();
  110.          document.getElementById('safecode').src="./vcode.php?t="+d.toTimeString()
  111.         }
  112.     //-->
  113. </SCRIPT>
  114.  
  115. <img src="vcode.php" id="safecode" onclick="reloadcode()">

 

点击查看原文阅读(431) | 评论(1) | 分类:PHP

最简单的PHP模板引擎 (2010-02-21)

模板类都是用是现成的,没有自己写过,杯具了!
今天自己写一下PHP模板引擎;
这是个最精简的PHP模板类;
模板标签采用纯天然原生态PHP语法
<?=$test?>使用这种原生形式比较快
因为PHP本身就是个很好的模板引擎
瞎写的玩的,反正核心原理就是替换变量
这是0.0001beta版,哈
过两天做个完整的

template.class.php
  1. <?php
  2. class Templates {
  3.  
  4.     var $vars;
  5.     var $path;
  6.  
  7.     public function __construct($path = null) {
  8.         $this->path = $path;
  9.     }
  10.  
  11.     public function assign($name, $value) {
  12.         $this->vars[$name] = $value;
  13.     }
  14.  
  15.     public function display($file) {
  16.         extract($this->vars);
  17.         ob_start();
  18.         include($this->path.$file.'.tpl.php');
  19.         $contents = ob_get_contents();
  20.         ob_end_clean();
  21.         return $contents;
  22.     }
  23.  
  24. }
  25.  
  26. /*test*/
  27. $template_url = './tp/';
  28. $name = 'Test Tempalte';
  29. $tpl = new Templates($template_url);
  30.  
  31. $tpl->assign('title', $name);
  32. $tpl->assign('user_list', fetch_user_list());
  33.  
  34. echo $tpl->display('test');
  35. ?>

 

 

点击查看原文阅读(551) | 评论(1) | 分类:PHP

大年初七,在家无聊,写了个mysql操作类 (2010-02-20)

在家无聊,写了个简单的DB类,方便以后CURD;
以前用公司现成的DB类,现在自己写个;
支持Mysqli,高手见笑,本人还是菜鸟 ;
 

代码如下
  1. <?php
  2.  
  3. class MysqlDB {
  4.  
  5.     private $hostname;
  6.     private $username;
  7.     private $password;
  8.     private $db;
  9.  
  10.     public function __construct() {
  11.         $num_args = func_num_args();
  12.         if($num_args > 0) {
  13.             $args = func_get_args();
  14.             $this->host = $args[0];
  15.             $this->user = $args[1];
  16.             $this->pass = $args[2];
  17.         }
  18.         $this->content();
  19.     }
  20.  
  21.     private function mysqli_installed(){
  22.         if (function_exists ("mysqli_connect")){
  23.             return true;
  24.         } else {
  25.             return false;
  26.         }
  27.     }
  28.  
  29.     private function content() {
  30.         try{
  31.          if($this->mysqli_installed()) {
  32.              if(!$this->db = new mysqli($this->host,$this->user,$this->pass)) {
  33.                  $exceptionstring = "Error connection to database: <br />";
  34.                  $exceptionstring .= mysqli_connect_errno() . ": " . mysqli_connect_error();
  35.                  throw new exception ($exceptionstring);
  36.              }
  37.          }else{
  38.             if(!$this->db = new mysql_connect($this->host,$this->user,$this->pass)) {
  39.                 $exceptionstring = "Error connection to database: <br />";
  40.                 $exceptionstring .= mysql_errno() . ": " . mysql_error();
  41.                 throw new exception ($exceptionstring);
  42.             }
  43.          }
  44.         } catch (exception $e) {
  45.             echo $e->getmessage();
  46.         }
  47.     }
  48.  
  49.     public function select_db($db_name) {
  50.         try{
  51.             if($this->mysqli_installed() ) {
  52.                 if(!$this->db->select_db($db_name)) {
  53.                     $exceptionstring = "Error opening database: $db_name: <br />";
  54.                     $exceptionstring .= $this->db->errno . ": " . $this->db->error;
  55.                     throw new exception ($exceptionstring);
  56.                 }
  57.             }else{
  58.                 if(!mysql_select_db($db_name,$this->db)) {
  59.                     $exceptionstring = "Error opening database: $db_name: <br />";
  60.                     $exceptionstring .= mysql_errno() . ": " . mysql_error();
  61.                     throw new exception ($exceptionstring);
  62.                 }
  63.             }
  64.         } catch (exception $e) {
  65.             echo $e->getmessage();
  66.         }
  67.     }
  68.  
  69.     public function execute($query) {
  70.         try{
  71.             if($this->mysqli_installed()) {
  72.                 if(!$this->db->query($query)) {
  73.                     $exceptionstring = "Error performing query: $query: <br />";
  74.                     $exceptionstring .= $this->db->errno . ": " . $this->db->error;
  75.                     throw new exception ($exceptionstring);
  76.                 }
  77.             }else{
  78.                 if(!mysql_query($query,$this->db)) {
  79.                     $exceptionstring = "Error performing query: $query: <br />";
  80.                     $exceptionstring .= mysql_errno() . ": " . mysql_error();
  81.                     throw new exception ($exceptionstring);
  82.                 }else{
  83.                     echo "Query performed correctly: " . mysql_affected_rows () . " row(s) affected.<br />";
  84.                 }
  85.             }
  86.         } catch (exception $e) {
  87.             echo $e->getmessage();
  88.         }
  89.     }
  90.  
  91.     public function get_rows ($query){
  92.         try {
  93.             if ($this->mysqli_installed()){
  94.                 if ($result = $this->db->query ($query)){
  95.                     $returnarr = array ();
  96.                     while ($adata = $result->fetch_array ()){
  97.                         $returnarr = array_merge ($returnarr,$adata);
  98.                     }
  99.                     return $returnarr;
  100.                 } else {
  101.                     $exceptionstring = "Error performing query: $query: <br />";
  102.                     $exceptionstring .= $this->db->errno . ": " . $this->db->error;
  103.                     throw new exception ($exceptionstring);
  104.                 }
  105.             } else {
  106.                 if (!$aquery = mysql_query ($query)){
  107.                     $exceptionstring = "Error performing query: $query: <br />";
  108.                     $exceptionstring .= mysql_errno() . ": " . mysql_error();
  109.                     throw new exception ($exceptionstring);
  110.                 } else {
  111.                     $returnarr = array ();
  112.                     while ($adata = mysql_fetch_array ($aquery)){
  113.                         $returnarr = array_merge ($returnarr,$adata);
  114.                     }
  115.                     return $returnarr;
  116.                 }
  117.             }
  118.         } catch (exception $e) {
  119.             echo $e->getmessage();
  120.         }
  121.     }
  122.  
  123.     public function affected_rows() {
  124.         if($this->mysqli_installed()) {
  125.             return $this->db->affected_rows;
  126.         }else{
  127.             return mysql_affected_rows ($this->db);
  128.         }
  129.     }
  130.  
  131.     public function insert_id() {
  132.         if($this->mysqli_installed()) {
  133.             return $this->db->insert_id;
  134.         }else{
  135.             return mysql_insert_id ($this->db);
  136.         }
  137.     }
  138.  
  139.     public function escape($str){
  140.         return trim(mysql_escape_string($str));
  141.     }
  142.  
  143.     public function __destruct() {
  144.         try {
  145.             if ($this->mysqli_installed()){
  146.                 if (!$this->db->close()){
  147.                     $exceptionstring = "Error closing connection: <br />";
  148.                     $exceptionstring .= $this->db->errno . ": " . $this->db->error;
  149.                     throw new exception ($exceptionstring);
  150.                 }
  151.             } else {
  152.                 if (!mysql_close ($this->db)){
  153.                     $exceptionstring = "Error closing connection: <br />";
  154.                     $exceptionstring .= mysql_errno() . ": " . mysql_error();
  155.                     throw new exception ($exceptionstring);
  156.                 }
  157.             }
  158.         } catch (exception $e) {
  159.             echo $e->getmessage();
  160.         }
  161.     }
  162.  
  163. }
  164.  
  165.  
  166. /*test*/
  167. $mysql = new MysqlDB('localhost','root','');
  168.  
  169. $mysql->select_db('test');
  170.  
  171. $update = $mysql->execute ("UPDATE test SET usereMail='test@test.com' WHERE id='1'");
  172.  
  173. $insert = $mysql->execute ("INSERT INTO test SET usereMail = 'test@test.com'");
  174.  
  175. $insert_id = $mysql->insert_id($insert);
  176.  
  177. $test = $mysql->get_rows("SELECT * FROM `test` WHERE 1");
  178.  
  179. $affected_rows = $mysql->affected_rows($insert);
  180.  
  181.  
  182. ?>

点击查看原文阅读(471) | 评论(1) | 分类:PHP

简单的PHP框架 (2009-10-24)

 简单的PHP MVC框架

\application\models\front.php

代码如下
  1. <?php
  2.  
  3. class FrontController {
  4.  
  5.   protected $_controller, $_action, $_params, $_body;
  6.  
  7.   static $_instance;
  8.  
  9.   public static function getInstance() {
  10.     if( ! (self::$_instance instanceof self) ) {
  11.       self::$_instance = new self();
  12.     }
  13.     return self::$_instance;
  14.   }
  15.  
  16.   private function __construct() {
  17.     $request = $_SERVER['REQUEST_URI'];
  18.  
  19.     $splits = explode('/', trim($request,'/'));
  20.     $this->_controller = !empty($splits[0])?$splits[0]:'index';
  21.     $this->_action = !empty($splits[1])?$splits[1]:'index';
  22.     if(!empty($splits[2])) {
  23.       $keys = $values = array();
  24.       for($idx=2, $cnt = count($splits); $idx<$cnt; $idx++) {
  25.         if($idx % 2 == 0) {
  26.           //Is even, is key
  27.           $keys[] = $splits[$idx];
  28.         } else {
  29.           //Is odd, is value;
  30.           $values[] = $splits[$idx];
  31.         }
  32.       }
  33.       $this->_params = array_combine($keys, $values);
  34.     }
  35.   }
  36.  
  37.   public function route() {
  38.     if(class_exists($this->getController())) {
  39.       $rc = new ReflectionClass($this->getController());
  40.       if($rc->implementsInterface('IController')) {
  41.         if($rc->hasMethod($this->getAction())) {
  42.           $controller = $rc->newInstance();
  43.           $method = $rc->getMethod($this->getAction());
  44.           $method->invoke($controller);
  45.         } else {
  46.           throw new Exception("Action");
  47.         }
  48.       } else {
  49.         throw new Exception("Interface");
  50.       }
  51.     } else {
  52.       throw new Exception("Controller");
  53.     }
  54.   }
  55.  
  56.   public function getParams() {
  57.     return $this->_params;
  58.   }
  59.  
  60.   public function getController() {
  61.     return $this->_controller;
  62.   }
  63.  
  64.   public function getAction() {
  65.     return $this->_action;
  66.   }
  67.  
  68.   public function getBody() {
  69.     return $this->_body;
  70.   }
  71.  
  72.   public function setBody($body) {
  73.     $this->_body = $body;
  74.   }
  75.  
  76. }

\application\models\view.php

代码如下
  1. <?php
  2. class View extends ArrayObject {
  3.   public function __construct() {
  4.     parent::__construct(array(), ArrayObject::ARRAY_AS_PROPS);
  5.   }
  6.  
  7.   public function render($file) {
  8.     ob_start();
  9.     include(dirname(__FILE__) . '/' . $file);
  10.     return ob_get_clean();
  11.   }
  12. }


application\models\icontroller.php

 
代码如下
  1. <?php
  2.  
  3. interface IController {}

 

点击查看原文阅读(764) | 评论(0) | 分类:PHP

Mysql导入CSV文件 (2009-09-15)

PHP导入CSV文件不能直接导入,只能通过sql语句导入

代码如下
  1. LOAD DATA LOCAL INFILE 'c:/1.csv' INTO TABLE `table` FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY 'rn';

点击查看原文阅读(694) | 评论(0) | 分类:PHP

去掉VIM的^M (2009-09-02)

去掉VIM换行符

每次有时候打开文件的时候会出现换行符,太烦了
于是把换行符替换掉 如下:
:% s/\r//g
:%s/^M//g

点击查看原文阅读(601) | 评论(0) | 分类:PHP

最简单的MVC模式 (2009-08-28)

 这个实例虽然简单,但是充分体现了 MVC 模式对分离“表现层”和“业务逻辑层”带来的帮助。
首先呢,还是有一个调度器,负责根据 HTTP 请求决定要调用的控制器:

代码如下
  1. <?php
  2. require ('controller/' . preg_replace('/[^a-z0-9_]+/i', '', $_GET['controller']));
  3. ?>

控制器:

代码如下
  1. <?php
  2. // 从 Model 获取数据
  3. require ('model/m1.php');
  4. $m = new m1();
  5. $data = $m->getData();
  6.  
  7. // 构造视图,显示输出
  8. require ('view/v1.php');
  9. $v = new v1();
  10. $v->assign($data);
  11. $v->display();
  12. ?>

模型:

代码如下
  1. <?php
  2. class m1
  3. {
  4.     function getData() {
  5.         return 'hello';
  6.     }
  7. }
  8. ?>

视图:

代码如下
  1. <?php
  2. class v1
  3. {
  4.     var $data;
  5.  
  6.     function assign($data) {
  7.         $this->data = $data;
  8.     }
  9.  
  10.     function display() {
  11.         echo $this->data;
  12.     }
  13. }
  14. ?>

点击查看原文阅读(403) | 评论(0) | 分类:PHP

PHP采集系统 (2009-08-13)

今天公司PHP牛人教了PHP采集系统的原理^_^,太牛了!

代码如下
  1. <?php
  2.  
  3. //获得网页内容
  4.     function getFileContents($url) {
  5.         $user_agent="User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; Windows 2000; Windows XP)";
  6.         $urlparts = parse_url($url);
  7.         $path = $urlparts['path'];
  8.         $host = $urlparts['host'];
  9.         if (!empty($urlparts['query']))
  10.         $path .= "?".$urlparts['query'];
  11.         if (isset ($urlparts['port'])) {
  12.             $port = (int) $urlparts['port'];
  13.         } else
  14.         if ($urlparts['scheme'] == "http") {
  15.             $port = 80;
  16.         } else
  17.         if ($urlparts['scheme'] == "https") {
  18.             $port = 443;
  19.         }
  20.  
  21.         if ($port == 80) {
  22.             $portq = "";
  23.         } else {
  24.             $portq = ":$port";
  25.         }
  26.  
  27.         $all = "*/*";
  28.  
  29.         $request = "GET $path HTTP/1.0rnHost: $host$portqrnAccept: $allrnAccept-Encoding: identityrnUser-Agent: $user_agentrnrn";
  30.  
  31.         $fsocket_timeout = 60;
  32.         if (substr($url, 0, 5) == "https") {
  33.             $target = "ssl://".$host;
  34.         } else {
  35.             $target = $host;
  36.         }
  37.  
  38.  
  39.         $errno = 0;
  40.         $errstr = "";
  41.         $fp = @ fsockopen($target, $port, $errno, $errstr, $fsocket_timeout);
  42.         if (!$fp) {
  43.             $contents['state'] = "NOHOST";
  44.             print "Error: $errstr";
  45.             return $contents;
  46.         } else {
  47.             if (!fputs($fp, $request)) {
  48.                 $contents['state'] = "Cannot send request";
  49.                 return $contents;
  50.             }
  51.             $data = null;
  52.             socket_set_timeout($fp, $fsocket_timeout);
  53.             $status = socket_get_status($fp);
  54.             while (!feof($fp) && !$status['timed_out']) {
  55.                 $data .= fgets($fp, 8192);
  56.             }
  57.             fclose($fp);
  58.             if ($status['timed_out'] == 1) {
  59.                 $contents['state'] = "timeout";
  60.             } else{
  61.                 if(strstr($data,"Location: ")&&strstr($data,"Cache-Control: private")){
  62.                     $contents['state'] = "jump";
  63.                     $contents['file'] = substr($data, strpos($data, "rnrn") + 4);
  64.                 }
  65.                 else{
  66.                     $contents['state'] = "ok";
  67.                     $contents['file'] = substr($data, strpos($data, "rnrn") + 4);
  68.                 }
  69.             }
  70.         }
  71.  
  72.         return $contents;
  73.     }
  74.  
  75.     /*
  76.     检查url文件是否可以读取
  77.     check if file is available and in readable form
  78.     */
  79.     function url_status($url) {
  80.         $user_agent="User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; Windows 2000; Windows XP)";
  81.         $urlparts = parse_url($url);
  82.         $path = $urlparts['path'];
  83.         $host = $urlparts['host'];
  84.         if (!empty($urlparts['query']))
  85.         $path .= "?".$urlparts['query'];
  86.  
  87.         if (isset ($urlparts['port'])) {
  88.             $port = (int) $urlparts['port'];
  89.         } else
  90.         if ($urlparts['scheme'] == "http") {
  91.             $port = 80;
  92.         } else
  93.         if ($urlparts['scheme'] == "https") {
  94.             $port = 443;
  95.         }
  96.  
  97.         if ($port == 80) {
  98.             $portq = "";
  99.         } else {
  100.             $portq = ":$port";
  101.         }
  102.  
  103.         $all = "*/*"; //just to prevent "comment effect" in get accept
  104.         $request = "HEAD $path HTTP/1.1rnHost: $host$portqrnAccept: $allrnAccept-Charset: iso-8859-1rnAccept-Encoding: identityrnUser-Agent: $user_agentrnrn";
  105.  
  106.         if (substr($url, 0, 5) == "https") {
  107.             $target = "ssl://".$host;
  108.         } else {
  109.             $target = $host;
  110.         }
  111.  
  112.         $fsocket_timeout = 60;
  113.         $errno = 0;
  114.         $errstr = "";
  115.         $fp = fsockopen($target, $port, $errno, $errstr, $fsocket_timeout);
  116.  
  117.         $linkstate = "ok";
  118.         if (!$fp) {
  119.             $status['state'] = "NOHOST";
  120.         } else {
  121.             socket_set_timeout($fp, $fsocket_timeout);
  122.             fputs($fp, $request);
  123.             $answer = fgets($fp, 4096);
  124.             $regs = Array ();
  125.             if (ereg("HTTP/[0-9.]+ (([0-9])[0-9]{2})", $answer, $regs)) {
  126.                 $httpcode = $regs[2];
  127.                 $full_httpcode = $regs[1];
  128.  
  129.                 if ($httpcode <> 2 && $httpcode <> 3) {
  130.                     $status['state'] = "Unreachable: http $full_httpcode";
  131.                     $linkstate = "Unreachable";
  132.                 }
  133.             }
  134.  
  135.             if ($linkstate <> "Unreachable") {
  136.                 while ($answer) {
  137.                     $answer = fgets($fp, 4096);
  138.  
  139.                     if (ereg("Location: *([^nr ]+)", $answer, $regs) && $httpcode == 3 && $full_httpcode != 302) {
  140.                         $status['path'] = $regs[1];
  141.                         $status['state'] = "Relocation: http $full_httpcode";
  142.                         fclose($fp);
  143.                         return $status;
  144.                     }
  145.  
  146.                     if (eregi("Last-Modified: *([a-z0-9,: ]+)", $answer, $regs)) {
  147.                         $status['date'] = $regs[1];
  148.                     }
  149.  
  150.                     if (eregi("Content-Type:", $answer)) {
  151.                         $content = $answer;
  152.                         $answer = '';
  153.                         break;
  154.                     }
  155.                 }
  156.                 $socket_status = socket_get_status($fp);
  157.                 if (eregi("Content-Type: *([a-z/]*)", $content, $regs)) {
  158.                     if ($regs[1] == 'text/html' || $regs[1] == 'text/' || $regs[1] == 'text/plain') {
  159.                         $status['content'] = 'text';
  160.                         $status['state'] = 'ok';
  161.                     } else if ($regs[1] == 'application/pdf') {
  162.                         $status['content'] = 'pdf';
  163.                         $status['state'] = 'ok';
  164.                     } else if ($regs[1] == 'application/msword') {
  165.                         $status['content'] = 'doc';
  166.                         $status['state'] = 'ok';
  167.                     } else {
  168.                         $status['state'] = "Not text or html";
  169.                     }
  170.  
  171.                 } else
  172.                 if ($socket_status['timed_out'] == 1) {
  173.                     $status['state'] = "Timed out (no reply from server)";
  174.  
  175.                 } else
  176.                 $status['state'] = "Not text or html";
  177.  
  178.             }
  179.         }
  180.         fclose($fp);
  181.         return $status;
  182.     }
  183.  
  184.  
  185.     $host = 'http://www.admin5.com';
  186.     $list_exp = '<div class="itembox"';
  187.     $url_start = '<a href="';
  188.     $url_end = '" target=';
  189.     $detail_title_start = '<h1>';
  190.     $detail_title_end = '</h1>';
  191.     $detail_summary_start = '<div id="arctext">';
  192.     $detail_summary_end = '<div id="arctext">';
  193.  
  194.     $max_page = 179;
  195.     for($page=$max_page;$page>0;$page--){
  196.  
  197.         $url = "http://www.admin5.com/browse/26/list_".$page.".shtml";
  198.  
  199.         $status = url_status($url);
  200.  
  201.         if($status['content'] == 'text' && $status['state'] == 'ok'){
  202.  
  203.             $files = getFileContents($url);
  204.  
  205.             $contents = $files['file'];
  206.  
  207.             $arr = explode($list_exp, $contents);
  208.  
  209.             for($i=1;$i<count($arr);$i++){
  210.                 $detail_url = "";
  211.                 $detail_url = strstr($arr[$i], $url_start);
  212.                 $detail_url = str_replace($url_start, "", $detail_url);
  213.                 $pos = strpos($detail_url, $url_end);
  214.                 $detail_url = substr($detail_url, 0, $pos);
  215.                 $detail_url = $host.$detail_url;
  216.  
  217.                 $summary = getFileContents($detail_url);
  218.  
  219.                 print_r($summary);
  220.                 exit;
  221.             }
  222.  
  223.         }
  224.  
  225.     }
  226.  
  227. ?>

点击查看原文阅读(666) | 评论(0) | 分类:PHP
<< 1 2 >>