15个有用的PHP代码脚本

这篇文章总结了15个最有用的PHP代码片段,可能对你有用。

1.使用PHP mail函数发邮件

 

$to = "viralpatel.net@gmail.com";
$subject = "VIRALPATEL.net";
$body = "Body of your message here you can use HTML too. e.g. <br> <b> Bold </b>";
$headers = "From: Peter\r\n";
$headers .= "Reply-To: info@yoursite.com\r\n";
$headers .= "Return-Path: info@yoursite.com\r\n";
$headers .= "X-Mailer: PHP5\n";
$headers .= 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to,$subject,$body,$headers);

 

2.PHP Base64加密解密字符串

 

function base64url_encode($plainText) {
	$base64 = base64_encode($plainText);
	$base64url = strtr($base64, '+/=', '-_,');
	return $base64url;
}

function base64url_decode($plainText) {
	$base64url = strtr($plainText, '-_,', '+/=');
	$base64 = base64_decode($base64url);
	return $base64;
}

echo base64url_encode("nihao");
echo base64url_decode("bmloYW8,");

3.获取客户端IP地址

function getRemoteIPAddress() {
	$ip = $_SERVER['REMOTE_ADDR'];
	return $ip;
}
echo getRemoteIPAddress();

如果客户端使用代理服务器,上面的代码可能不会起作用,使用以下代码可以获得客户端的真实IP地址:

 

function getRealIPAddr()
{
	if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
	{
		$ip=$_SERVER['HTTP_CLIENT_IP'];
	}
	elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
	{
		$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
	}
	else
	{
		$ip=$_SERVER['REMOTE_ADDR'];
	}
	return $ip;
}

 

4.将秒转换为时间字符串


function secsToStr($secs) {
	if($secs>=86400){$days=floor($secs/86400);$secs=$secs%86400;$r=$days.' day';
          if($days<>1){$r.='s';}if($secs>0){$r.=', ';}}
	if($secs>=3600){$hours=floor($secs/3600);$secs=$secs%3600;$r.=$hours.' hour';
          if($hours<>1){$r.='s';}if($secs>0){$r.=', ';}}
	if($secs>=60){$minutes=floor($secs/60);$secs=$secs%60;$r.=$minutes.' minute';
          if($minutes<>1){$r.='s';}if($secs>0){$r.=', ';}}
	$r.=$secs.' second';if($secs<>1){$r.='s';}
	return $r;
}

 

5.使用PHP验证email正则表达式

6.使用PHP解析XML

需要支持SimpleXML扩展

//this is a sample xml string
$xml_string="<?xml version='1.0'?>
<moleculedb>
    <molecule name='Benzine'>
        <symbol>ben</symbol>
        <code>A</code>
    </molecule>
    <molecule name='Water'>
        <symbol>h2o</symbol>
        <code>K</code>
    </molecule>
</moleculedb>";

//load the xml string using simplexml function
$xml = simplexml_load_string($xml_string);

//loop through the each node of molecule
foreach ($xml->molecule as $record)
{
   //attribute are accessted by
   echo $record['name'], '  ';
   //node are accessted by -> operator
   echo $record->symbol, '  ';
   echo $record->code, '<br />';
}

 

7.PHP连接mysql数据库
 
<?php
if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])) send_404();
$dbHost = "localhost";        //Location Of Database usually its localhost
$dbUser = "xxxx";            //Database User Name
$dbPass = "xxxx";            //Database Password
$dbDatabase = "xxxx";       //Database Name

$db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");

# This function will send an imitation 404 page if the user
# types in this files filename into the address bar.
# only files connecting with in the same directory as this
# file will be able to use it as well.
function send_404()
{
    header('HTTP/1.x 404 Not Found');
    print '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">'."n".
    '<html><head>'."n".
    '<title>404 Not Found</title>'."n".
    '</head><body>'."n".
    '<h1>Not Found</h1>'."n".
    '<p>The requested URL '.
    str_replace(strstr($_SERVER['REQUEST_URI'], '?'), '', $_SERVER['REQUEST_URI']).
    ' was not found on this server.</p>'."n".
    '</body></html>'."n";
    exit;
}

# In any file you want to connect to the database,
# and in this case we will name this file db.php
# just add this line of php code (without the pound sign):
# include"db.php";
?>

8.PHP创建和解析JSON数据

从数组创建json:
$json_data = array ('id'=>1,'name'=>"rolf",'country'=>'russia',"office"=>array("google","oracle"));
echo json_encode($json_data);


 
解析json:
$json_string='{"id":1,"name":"rolf","country":"russia","office":["google","oracle"]} ';
$obj=json_decode($json_string);
//print the parsed data
echo $obj->name; //displays rolf
echo $obj->office[0]; //displays google


 

9.PHP处理MYSQL时间截 Timestamp

 
$query = "select UNIX_TIMESTAMP(date_field) as mydate from mytable where 1=1";
$records = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($records))
{
	echo $row;
}

 

10.PHP生成认证代码

 

<?php

# This particular code will generate a random string
# that is 25 charicters long 25 comes from the number
# that is in the for loop
$string = "abcdefghijklmnopqrstuvwxyz0123456789";
$str = "";
for($i=0;$i<25;$i++){
    $pos = rand(0,36);
    $str .= $string{$pos};
}
echo $str;
# If you have a database you can save the string in
# there, and send the user an email with the code in
# it they then can click a link or copy the code
# and you can then verify that that is the correct email
# or verify what ever you want to verify
?>

 

11.PHP验证日期格式
验证日期是否为“YYYY-MM-DD”这种格式:
<?php
function checkDateFormat($date)
{
	//match the format of the date
	if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts))
	{
		//check weather the date is valid of not
		if(checkdate($parts[2],$parts[3],$parts[1]))
			return true;
		else
		return false;
	}
	else
		return false;
}
 echo checkDateFormat("1999-1-1")? "true" : "false";
?>

12.HTTP页面跳转
 
<?php
	header('Location: http://phpcode8.com/about'); // stick your url here
?>

13.PHP列出目录和文件
 
<?php

function list_files($dir)
{
	if(is_dir($dir))
  	{
  		if($handle = opendir($dir))
  		{
  			while(($file = readdir($handle)) !== false)
  			{
  				if($file != "." && $file != ".." && $file != "Thumbs.db"/*pesky windows, images..*/)
  				{
  					echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";
  				}
  			}
  			closedir($handle);
  		}
	}
}

/*
To use:
*/
list_files(".");

?>

14.探测浏览器脚本
 
<?php
	$useragent = $_SERVER ['HTTP_USER_AGENT'];
	echo "<b>Your User Agent is</b>: " . $useragent;
	/*类似的结果:
	Your User Agent is: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/4.0; 
        QQDownload 679; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; 
        Media Center PC 6.0; InfoPath.2)
	 */
?>

15.使用PHP解压缩文件
 
<?php
    function unzip($location,$newLocation){
        if(exec("unzip $location",$arr)){
            mkdir($newLocation);
            for($i = 1;$i< count($arr);$i++){
                $file = trim(preg_replace("~inflating: ~","",$arr[$i]));
                copy($location.'/'.$file,$newLocation.'/'.$file);
                unlink($location.'/'.$file);
            }
            return TRUE;
        }else{
            return FALSE;
        }
    }
?>
<?php
if(unzip('zipedfiles/test.zip','unziped/myNewZip'))
    echo 'Success!';
else
    echo 'Error';
?>
如果你有好玩的code,也请帖在评论里!

posted on 2012-03-01 12:10  IT技术畅销书  阅读(734)  评论(0编辑  收藏  举报

导航