PHP的一些技巧

来源:互联网 发布:穿衣搭配技巧软件 编辑:程序博客网 时间:2024/04/30 02:17

防止网页被不停刷新:

$refreshLimitTime = 60;
$timeStamp = time();
 $cookieTime = $timeStamp+3153600;
 if ($timeStamp-$_COOKIE['lastvisit_fresh'] < $refreshLimitTime)
{
 die('请您不要频繁刷新,谢谢合作。防刷新时间<font color=red>'.$refreshLimitTime.'</font>秒');
  }
 setCookie('lastvisit_fresh', $timeStamp, $cookieTime);
-----------------------------------------------------------------------------------
将session封装入一个简单的购物车类之中

<?php

/************************

将session封装入一个简单的购物车类之中,
请参考PHP学习记录的相应文章。

每件商品要求具备id,name,price,count四个属性,
如果你要加新的属性,请修改相应部分。

*************************/

class TCart {

  var $SortCount; //商品种类数
  var $TotalCost; //商品总价值
  
  var $Id;        //每类商品的ID(数组)
  var $Name;        //每类商品的名称(数组)
  var $Price;        //每类商品的价格(数组)
  var $Count;        //每类商品的件数(数组)
  var $Cost;        //每类商品的价值(数组)

  
  //******构造函数
  function TCart(){
    $this->SortCount=0;
    
    session_start();    //初始化一个session
    session_register('sId');
    session_register('sName');
    session_register('sPrice');
    session_register('sCount');
    
    $this->Update();
    $this->Calculate();
    
  }
  
  //********私有,根据session的值更新类中相应数据
  function Update(){
    global $sId,$sName,$sPrice,$sCount;
    
    if(!isset($sId) or !isset($sName) or !isset($sPrice)) return;
    
    $this->Id=$sId;
    $this->Name=$sName;
    $this->Price=$sPrice;
    $this->Count=$sCount;
    
    $this->SortCount=count($sId);
    
  }
  
  //********私有,根据新的数据计算每类商品的价值及全部商品的总价
  function Calculate(){
   for($i=0;$i<$this->SortCount;$i++){
     $this->Cost[$i]=$this->Price[$i]*$this->Count[$i];
     $this->TotalCost += $this->Cost[$i];
   }
  }
  
 
 //**************以下为接口函数
  
 //*** 加一件商品
 // 判断是否蓝中已有,如有,加count,否则加一个新商品
 //首先都是改session的值,然后再调用update() and calculate()来更新成员变量
  function AddOne($id,$na,$pr){
    global $sId,$sName,$sPrice,$sCount;
    
    $k=count($sId);
    for($i=0;$i<$k;$i++){ //先找一下是否已经加入了这种商品
      if($sId[$i]==$id){
       $sCount[$i]++;
       break;
      }
    }
    if($i>=$k){   //没有则加一个新商品种类
      $sId[]=$id;
      $sName[]=$na;
      $sPrice[]=$pr;
      $sCount[]=1;
    }
    
    $this->Update();    //更新一下类的成员数据
    $this->Calculate();
  }
 
 //移去一件商品
  function RemoveOne($id){
    global $sId,$sName,$sPrice,$sCount;
    
    $k=count($sId);
    for($i=0;$i<$k;$i++){
      if($sId[$i]==$id){
       $sCount[$i]--;
       break;
      }
    }
    
    $this->Update();
    $this->Calculate();
  }
  
  //改变商品的个数
  function ModifyCount($i,$ncount){
   global $sCount;
      
   $sCount[$i]=$ncount;
  
   $this->Update();
   $this->Calculate();
  
  }
  
  //清空一种商品
  function EmptyOne($i){
   global $sCount;
  
   $sCount[$i]=0;
      
   $this->Update();
   $this->Calculate();
  }
  
  
  /***************************
  清空所有的商品
  
  因为在win里PHP不支持session_destroy()函数,所以这个清空函数不完善,
  只是把每种商品的个数置为0。
  如果是在linux下,可以直接用session_destroy()来做。
  *****************************/
  function EmptyAll(){
    global $sId,$sName,$sPrice,$sCount;
    
    $k=count($sId);
    for($i=0;$i<$k;$i++){
       $sCount[$i]=0;
    }
    
    $this->Update();
    $this->Calculate();
    
    session_unregister('sId');
    session_unregister('sName');
    session_unregister('sPrice');
    session_unregister('sCount');
    
    $this->SortCount=0;
    
  }
  
  //是否某件商品已在蓝内,参数为此商品的ID
  function InCart($id){
    for($i=0;$i<$this->SortCount;$i++){
      if($this->Id[$i]==$id) return TRUE;
    }
    return FALSE;
  }
  
  //某件商品在蓝内的位置
  function IndexOf($id){
    for($i=0;$i<$this->SortCount;$i++){
      if($this->Id[$i]==$id) return $i;
    }
    return 0;
  }
  
  //取一件商品的信息,主要的工作函数
  //返回一个关联数组,下标分别对应 id,name,price,count,cost
  function GetOne($i){
    $Result[id]=$this->Id[$i];
    $Result[name]=$this->Name[$i];
    $Result[price]=$this->Price[$i];
    $Result[count]=$this->Count[$i];
    $Result[cost]=$this->Cost[$i];
    
    return $Result;
  }
  
  //取总的商品种类数
  function GetSortCount(){
    return $this->SortCount;
  }
  
  //取总的商品价值
  function GetTotalCost(){
    return $this->TotalCost;
  }
  
//end class 
}

?> 

-----------------------------------------------------------------
一个把字符串按php代码高亮显示的函数 
 
  日期:2003-06-07 19 作者:c.w. 来源:
       
///// by iwind.org  coldwind/iwind/month/ccterran
//这个函数是对[code][/code]标签里的内容进行分析,并输出
//例如:
//  <?php $string='[code]<?$hello="hello";?>[/code]sssssssssssss';
//        highlight($string);
//    ?>
//保留了不完全的标签,如只有[code],没有[/code],则输出中含有[code]
          
function highlight($string){
    $arr=explode("[code]",$string);
    $total=sizeof($arr);
    for($i=0;$i<$total;$i++){
        if(ereg("(.+)[/code]",$arr[$i])){
          list($astr,$bstr)=split("[/code]",$arr[$i],"2");
          highlight_string($astr);
          echo"$bstr";
        }
 else{
      if($i!="0"){
         echo"[code]";
     }
      echo"$arr[$i]";
     }
 }
}
-----------------------------------------------------------------
如何用正则表达式来表示中文?
 
由于中文的ASCII码是有一定的范围的。所以你可以用下面的正则表达式来表示中文。

/^[chr(0xa1)-chr(0xff)]+$/

下面是一个使用的例子:

$str = "超越PHP";
if  (preg_match("/^[".chr(0xa1)."-".chr(0xff)."]+$/", $str)) {
    echo "这是一个纯中文字符串";
} else {
    echo "这不是一个纯中文字串";
}

--------------------------------------------------------------------------------------------------
将PHP作为Shell脚本语言使用

--英文原著:Darrell Brogdon,发表于 http://www.phpbuilder.com/columns/darrell20000319.php3
可能很多人都想过使用PHP编写一些定时发信之类的程序,但是却没有办法定时执行PHP;一次去PHPBuilder的时候,发现了这一篇文章,于是想给大家翻译一下(同时做了一些修改),希望对大家有用。第一次翻译文章,不好请多多见谅。
----------------------------------------------------------------------------------
我们都知道,PHP是一种非常好的动态网页开发语言(速度飞快,开发周期短……)。但是只有很少数的人意识到PHP也可以很好的作为编写Shell脚本的语言,当PHP作为编写Shell脚本的语言时,他并没有Perl或者Bash那么强大,但是他却有着很好的优势,特别是对于我这种熟悉PHP但是不怎么熟悉Perl的人。
要使用PHP作为Shell脚本语言,你必须将PHP作为二进制的CGI编译,而不是Apache模式;编译成为二进制CGI模式运行的PHP有一些安全性的问题,关于解决的方法可以参见PHP手册(http://www.php.net)。
一开始你可能会对于编写Shell脚本感到不适应,但是会慢慢好起来的:将PHP作为一般的动态网页编写语言和作为Shell脚本语言的唯一不同就在于一个Shell脚本需要在第一行生命解释本脚本的程序路径:
#!/usr/local/bin/php -q
我们在PHP执行文件后面加入了参数“-1”,这样子PHP就不会输出HTTPHeader(如果仍需要作为Web的动态网页,那么你需要自己使用header函数输出HTTPHeader)。当然,在Shell脚本的里面你还是需要使用PHP的开始和结束标记:
<?php 代码 ?>
现在让我们看一个例子,以便于更好的了解用PHP作为Shell脚本语言的使用:
#!/usr/local/bin/php -q
<?php
print("Hello, world!/n");
?>
上面这个程序会简单的输出“Hello, world!”到显示器上。

一、传递Shell脚本运行参数给PHP:
作为一个Shell脚本,经常会在运行程序时候加入一些参数,PHP作为Shell脚本时有一个内嵌的数组“$argv”,使用“$argv”数组可以很方便的读取Shell脚本运行时候的参数(“$argv[1]”对应的是第一个参数,“$argv[2]”对应的是第二个参数,依此类推)。比如下面这个程序:
#!/usr/local/bin/php -q
<?php
$first_name = $argv[1];
$last_name = $argv[2];
printf("Hello, %s %s! How are you today?/n", $first_name, $last_name);
?>
上面的代码在运行的时候需要两个参数,分别是姓和名,比如这样子运行:
[dbrogdon@artemis dbrogdon]$ scriptname.ph Darrell Brogdon
Shell脚本在显示器上面会输出:
Hello, Darrell Brogdon! How are you today?
[dbrogdon@artemis dbrogdon]$
在PHP作为动态网页编写语言的时候也含有“$argv”这个数组,不过和这里有一些不同:当PHP作为Shell脚本语言的时候“$argv[0]”对应的是脚本的文件名,而当用于动态网页编写的时候,“$argv[1]”对应的是QueryString的第一个参数。

二、编写一个具有交互式的Shell脚本:
如果一个Shell脚本仅仅是自己运行,失去了交互性,那么也没有什么意思了。当PHP用于Shell脚本的编写的时候,怎么读取用户输入的信息呢?很不幸的是PHP自身没有读取用户输入信息的函数或者方法,但是我们可以效仿其他语言编写一个读取用户输入信息的函数“read”:
<?php
function read() {
$fp = fopen('/dev/stdin', 'r');
$input = fgets($fp, 255);
fclose($fp);
return $input;
}
?>
需要注意的是上面这个函数只能用于Unix系统(其他系统需要作相应的改变)。上面的函数会打开一个文件指针,然后读取一个不超过255字节的行(就是fgets的作用),然后会关闭文件指针,返回读取的信息。
现在我们可以使用函数“read”将我们前面编写的程序1修改一下,使他更加具有“交互性”了:
#!/usr/local/bin/php -q
<?php
function read() {
$fp = fopen('/dev/stdin', 'r');
$input = fgets($fp, 255);
fclose($fp);
return $input;
}
print("What is your first name? ");
$first_name = read();
print("What is your last name? ");
$last_name = read();
print("/nHello, $first_name $last_name! Nice to meet you!/n");
?>
将上面的程序保存下来,运行一下,你可能会看到一件预料之外的事情:最后一行的输入变成了三行!这是因为“read”函数返回的信息还包括了用户每一行的结尾换行符“/n”,保留到了姓和名中,要去掉结尾的换行符,需要把“read”函数修改一下:
<?php
function read() {
$fp = fopen('/dev/stdin', 'r');
$input = fgets($fp, 255);
fclose($fp);
$input = chop($input); // 去除尾部空白
return $input;
}
?>

三、在其他语言编写的Shell脚本中包含PHP编写的Shell脚本:
有时候我们可能需要在其他语言编写的Shell脚本中包含PHP编写的Shell脚本。其实非常简单,下面是一个简单的例子:
#!/bin/bash
echo This is the Bash section of the code.

/usr/local/bin/php -q << EOF
<?php
print("This is the PHP section of the code/n");
?>
EOF
其实就是调用PHP来解析下面的代码,然后输出;那么,再试试下面的代码:
#!/bin/bash
echo This is the Bash section of the code.

/usr/local/bin/php -q << EOF
<?php
$myVar = 'PHP';
print("This is the $myVar section of the code/n");
?>
EOF
可以看出两次的代码唯一的不同就是第二次使用了一个变量“$myVar”,试试运行,PHP竟然给出出错的信息:“Parse error: parse error in - on line 2”!这是因为Bash中的变量也是“$myVar”,而Bash解析器先将变量给替换掉了,要想解决这个问题,你需要在每个PHP的变量前面加上“/”转义符,那么刚才的代码修改如下:
#!/bin/bash
echo This is the Bash section of the code.

/usr/local/bin/php -q << EOF
<?php
/$myVar = 'PHP';
print("This is the /$myVar section of the code/n");
?>
EOF

好了,现在你可以用PHP编写你自己的Shell脚本了,希望你一切顺利。如果有什么问题,可以去http://www.PHPBuilder.com或者http://www.zPHP.com上面讨论。

-----------------------------------------------------------------------------------------
天气预报 php代码
其实就是从SINA上拿的

目前支持的城市有
北京 天津 呼和浩特 太原 石家庄 济南 青岛 合肥 上海 南京 杭州 福州 南宁 海口 广州 厦门
汕头 深圳 郑州 武汉 长沙 南昌 哈尔滨 沈阳 长春 大连 乌鲁木齐 银川 西安 西宁 兰州
重庆 昆明 成都 贵阳 香港 澳门 台北

/**********************************************/
$city="西安"; //这里设置城市数据

//远程打开新浪的天气预报页面
$filename="http://weather.sina.com.cn/index.html";
$fp=fopen($filename,"r");
$www=fread($fp,100000);

//取得第一个时间
$riqi=strstr($www,"<td colspan=3>");
$num=strpos($riqi,"</td>")-strlen("<td colspan=3>");
$riqi=substr($riqi,strlen("<td colspan=3>"),$num);


//取得第二个时间
$riqi2=strstr($www,"colspan=3>");
$riqi2=strstr($riqi2,"<td colspan=3>");
$num=strpos($riqi2,"</td>")-strlen("<td colspan=3>");
$riqi2=substr($riqi2,strlen("<td colspan=3>"),$num);

//取得预报的数据
$city="<td>".$city."</td>";
$www=strstr($www,$city);
$ender="</tr>";
$num=strpos($www,$ender);
$www=substr($www,0,$num);

//=========处理预报数据开始========
$www=substr($www,4);
$www=explode("<td>",$www);

//定义处理函数
function sub($x)
{
$num=strpos($x,"</td>");
$real=substr($x,0,$num);
return $real;
}

//处理数据
$www[1]=sub($www[1]); //时间一天气状况
$www[2]=sub($www[2]); //时间一风向风力
$www[3]=sub($www[3]); //时间一最低温度
$www[4]=sub($www[4]); //时间二天气状况
$www[5]=sub($www[5]); //时间二风向风力
$www[6]=sub($www[6]); //时间二最高温度

//=========处理预报数据完成========

//格式化输出,了解html的兄弟可以直接修改 嘿嘿.
echo "<font size=2 color=red>";
echo $city."市天气预报:";
echo $riqi;//时间一
echo "&nbsp";
echo $www[1];
echo "&nbsp风力风向:&nbsp";
echo $www[2];
echo "&nbsp最低温度:&nbsp";
echo $www[3];
echo "&nbsp&nbsp&nbsp";
echo $riqi2;//时间二
echo "&nbsp";
echo $www[4];
echo "&nbsp风力风向:&nbsp";
echo $www[5];
echo "&nbsp最高温度:&nbsp";
echo $www[6];
echo "</font>";

?>

---------------------------------------------------------------------------------

APACHE中的虚拟主机

虚拟主机中对PHP的特殊设置
 
  <VirtualHost 127.0.10.10> 

ServerAdmin webmaster@hostmachine.com 

DocumentRoot /www/virtual.com/htdocs 

ServerName www.virtual.com 

UserDir /www/virtual.com/htdocs 

ScriptAlias /cgi-bin/ /www/virtual.com/cgi-bin/ 

ErrorLog /www/virtual.com/logs/error_log 

CustomLog /www/virtual.com/logs/access_log common</VirtualHost> 

目录设置 

<Directory /www/virtual.com/htdocs> 

# 对该虚拟主机设置是否使用php 

php_engine On 

# 设置php出错信息的调试级别 

php_error_reporting 1 

# 设置是否记录php出错日志 

php_log_errors On 

# 设置php的出错日志文件 

php_error_log /www/virtual.com/logs/php_error_log 

# 设置一个php线程的最长存活时间 

php_max_execution_time 180 

# 设置用户临时上载目录 

php_upload_tmp_dir /www/virtual.com/htdocs/tmp 

# 设置包含头文件 

php_include_path /www/virtual.com/htdocs/include 

</Directory> 

可执行目录设置 

<Directory "/www/virtual.com/cgi-bin"> 

Options Indexes FollowSymLinks 

AllowOverride All 

Order allow,deny 

Allow from all 

</Directory>  
 
---------------------------------------------------------------------------

取得一个文件的扩展名的函数 
function fileextname($filename) 

    $retval=""; 
    $pt=strrpos($filename, "."); 
    if ($pt) $retval=substr($filename, $pt+1, strlen($filename) - $pt); 
    return ($retval); 


---------------------------------------------------------------------------
动态页面转为静态输出

<?php
ob_start(); //启动输出缓存

include "detail.php"; //执行程序

if(isset($_GET['aid'])) {
  $buffer = ob_get_contents(); //取出输出缓存
  $filename = $_GET['aid'].".htm";
  $fp = fopen($filename,"w");
  fwrite($fp,$buffer); //写入文件
  fclose($fp);
  unlink($filename); //删除文件
}
ob_end_flush(); //输出并关闭输出缓存
?>

---------------------------------------------------------------------------

取得操作系统和浏览器

$ip = $_SERVER["REMOTE_ADDR"];

// +----------------------------------------
function osinfo() {
$os="";
$Agent = $_SERVER["HTTP_USER_AGENT"];
if (eregi('win',$Agent) && strpos($Agent, '95')) {
$os="Windows 95";
}
elseif (eregi('win 9x',$Agent) && strpos($Agent, '4.90')) {
$os="Windows ME";
}
elseif (eregi('win',$Agent) && ereg('98',$Agent)) {
$os="Windows 98";
}
elseif (eregi('win',$Agent) && eregi('nt 5',$Agent)) {
$os="Windows 2000";
}
elseif (eregi('win',$Agent) && eregi('nt',$Agent)) {
$os="Windows NT";
}
elseif (eregi('win',$Agent) && ereg('xp',$Agent)) {
$os="Windows XP";
}
elseif (eregi('win',$Agent) && ereg('32',$Agent)) {
$os="Windows 32";
}
elseif (eregi('linux',$Agent)) {
$os="Linux";
}
elseif (eregi('unix',$Agent)) {
$os="Unix";
}
elseif (eregi('sun',$Agent) && eregi('os',$Agent)) {
$os="SunOS";
}
elseif (eregi('ibm',$Agent) && eregi('os',$Agent)) {
$os="IBM OS/2";
}
elseif (eregi('Mac',$Agent) && eregi('PC',$Agent)) {
$os="Macintosh";
}
elseif (eregi('PowerPC',$Agent)) {
$os="PowerPC";
}
elseif (eregi('AIX',$Agent)) {
$os="AIX";
}
elseif (eregi('HPUX',$Agent)) {
$os="HPUX";
}
elseif (eregi('NetBSD',$Agent)) {
$os="NetBSD";
}
elseif (eregi('BSD',$Agent)) {
$os="BSD";
}
elseif (ereg('OSF1',$Agent)) {
$os="OSF1";
}
elseif (ereg('IRIX',$Agent)) {
$os="IRIX";
}
elseif (eregi('FreeBSD',$Agent)) {
$os="FreeBSD";
}
 if ($os=='') $os = "Unknown OS";
return $os;
}

// +----------------------------------------
function browseinfo() {
$browser="";$browserver="";
$Browsers =array("Lynx","MOSAIC","AOL","Opera","JAVA","MacWeb","WebExplorer","OmniWeb");
$Agent = $_SERVER["HTTP_USER_AGENT"];
for ($i=0; $i<=7; $i++) {
if (strpos($Agent,$Browsers[$i])) {
$browser = $Browsers[$i];
$browserver ="";
}
}
   if (ereg("Mozilla",$Agent) && !ereg("MSIE",$Agent)) {
      $temp =explode("(", $Agent); $Part=$temp[0];
      $temp =explode("/", $Part); $browserver=$temp[1];
      $temp =explode(" ",$browserver); $browserver=$temp[0];
      $browserver =preg_replace("/([/d/.]+)/","//1",$browserver);
      $browserver = " $browserver";
      $browser = "Netscape Navigator";
   }
   if (ereg("Mozilla",$Agent) && ereg("Opera",$Agent)) {
      $temp =explode("(", $Agent); $Part=$temp[1];
      $temp =explode(")", $Part); $browserver=$temp[1];
      $temp =explode(" ",$browserver);$browserver=$temp[2];
      $browserver =preg_replace("/([/d/.]+)/","//1",$browserver);
      $browserver = " $browserver";
      $browser = "Opera";
   }
if (ereg("Mozilla",$Agent) && ereg("MSIE",$Agent)) {
$temp = explode("(", $Agent); $Part=$temp[1];
$temp = explode(";",$Part); $Part=$temp[1];
$temp = explode(" ",$Part);$browserver=$temp[2];
$browserver =preg_replace("/([/d/.]+)/","//1",$browserver);
$browserver = " $browserver";
$browser = "Internet Explorer";
}
if ($browser!="") {
$browseinfo = "$browser$browserver";
}
else {
$browseinfo = "Unknow Browse";
}
return $browseinfo;
}

------------------------------------------------------------------------------
PHP中查看真实IP方法 
 
    PHP中查看真实IP方法 :
如果 PHP 版本为 4.1.0 或者以上版本,可以用这个代码
function getip() {
if ($_SERVER) {
if ( $_SERVER[HTTP_X_FORWARDED_FOR] ) {
$realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
} elseif ( $_SERVER["HTTP_CLIENT_IP"] ) {
$realip = $_SERVER["HTTP_CLIENT_IP"];
} else {
$realip = $_SERVER["REMOTE_ADDR"];
}
} else {
if ( getenv( 'HTTP_X_FORWARDED_FOR' ) )
{ $realip = getenv( 'HTTP_X_FORWARDED_FOR' );
} elseif ( getenv( 'HTTP_CLIENT_IP' ) )
{
$realip = getenv( 'HTTP_CLIENT_IP' );
}
else {
$realip = getenv( 'REMOTE_ADDR' );
}
}
return $realip;
}
如果你的PHP版本为 4.1.0以下(这种情况很少哦),你就得用这个代码了:
function getip() {
if (isSet($_SERVER)) {
if (isSet($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
elseif (isSet($_SERVER["HTTP_CLIENT_IP"])) {
$realip = $_SERVER["HTTP_CLIENT_IP"];
} else {
$realip = $_SERVER["REMOTE_ADDR"];
}
} else {
if ( getenv( 'HTTP_X_FORWARDED_FOR' ) )
{
$realip = getenv( 'HTTP_X_FORWARDED_FOR' );
} elseif ( getenv( 'HTTP_CLIENT_IP' ) )
{
$realip = getenv( 'HTTP_CLIENT_IP' );
}
else {
$realip = getenv( 'REMOTE_ADDR' );
}
}
return $realip;
}
关键是代理服务器要发送HTTP_X_FORWARDED_FOR,如果没有发送,也是看不到地 ;)

原创粉丝点击