10段PHP常用功能代码

原创
开发 后端
本文汇集PHP开发中经常用到的时段代码,包括Email、解压缩、64位编码、解析JSON等,希望对您有所帮助。

1、使用PHP Mail函数发送Email

$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中的64位编码和解码

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;
} 

3、获取远程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 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;
}

5、验证Email

$email = $_POST['email'];
if(preg_match("~([a-zA-Z0-9!#$%&'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).
                                 ([a-zA-Z0-9]{2,4})~",$email)) {
	echo 'This is a valid email.';
} else{
	echo 'This is an invalid email.';
} 

#p#

6、在PHP中轻松解析XML

//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
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、创建和解析JSON数据

$json_data = array ('id'=﹥1,'name'=﹥"rolf",'country'=﹥'russia',
			"office"=﹥array("google","oracle"));
echo json_encode($json_data);

9、处理MySQL时间戳

$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、解压缩Zip文件

﹤?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;
        }
    }
?﹥
//Use the code as following:
﹤?php
include 'functions.php';
if(unzip('zipedfiles/test.zip','unziped/myNewZip'))
    echo 'Success!';
else
    echo 'Error';
?﹥

【编辑推荐】

  1. 20个对开发人员非常有用的Java代码片段
  2. PHP 6预览 新增多项特性及改进
  3. 国外十大***PHP框架排名
责任编辑:佚名 来源: 51CTO.com
相关推荐

2010-07-28 15:42:44

Flex

2019-09-04 14:30:54

Nginx功能服务器

2011-02-22 09:08:14

vsFTPd

2011-02-22 09:55:00

vsFTPd

2011-03-01 14:00:16

vsFTPd功能

2013-08-20 16:14:46

pythonpython文本处理

2011-02-22 09:40:42

vsFTPd

2011-07-07 17:24:28

PHP

2011-07-07 17:27:54

PHP

2011-02-22 10:12:07

vsFTPd

2011-10-08 13:54:27

JavaScript

2010-02-03 17:39:21

2010-02-03 09:58:33

全光交换机

2021-12-15 09:44:36

Windows 11Windows微软

2018-02-26 11:25:33

2011-02-22 09:23:21

vsFTPd

2016-06-29 13:50:12

云计算

2011-02-21 18:11:27

vsFTPd

2010-02-25 16:12:23

WCF IDispos

2023-10-27 08:59:00

网络wiresharkIO
点赞
收藏

51CTO技术栈公众号