分享10段PHP常用代碼
本文匯集PHP開發(fā)中經(jīng)常用到的十段代碼,包括Email、64位編碼和解碼、解壓縮、64位編碼、解析JSON等,希望對(duì)您有所幫助。
1、使用PHP Mail函數(shù)發(fā)送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、獲取遠(yuǎn)程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、驗(yàn)證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.'; }
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、數(shù)據(jù)庫(kù)連接
﹤?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、創(chuàng)建和解析JSON數(shù)據(jù)
$json_data = array ('id'=﹥1,'name'=﹥"rolf",'country'=﹥'russia', "office"=﹥array("google","oracle")); echo json_encode($json_data);
9、處理MySQL時(shí)間戳
$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'; ?﹥
PHP常用功能如下
1.PHP字符串
字符串聲明 變量=''或者""(一般情況會(huì)使用單引號(hào),因?yàn)閷懫饋?lái)會(huì)比較方便)
$str = 'Hello PHP';
echo $str;
strpos 計(jì)算字符在字符串中的位置(從0開始)
$str = 'Hello PHP';
echo strpos($str,'o'); //計(jì)算字符在字符串中的位置
echo '<br/>';
echo strpos($str,'PH');
substr 截取字符串
$str = 'Hello PHP'; //截取字符串 $str1 = substr($str,2,3); //從2位置開始截取,截取長(zhǎng)度為3的字符串 echo $str1;
不傳入長(zhǎng)度參數(shù)的話,會(huì)從指定位置一直截取到字符串的末尾
str_split 分割字符串 固定長(zhǎng)度的分割(默認(rèn)長(zhǎng)度為1)
$str = 'Hello PHP'; //分割字符串 $result = str_split($str); //將結(jié)果保存到一個(gè)數(shù)組中 print_r($result); //使用print_r輸入一個(gè)數(shù)組 echo '<br/>'; $result1 = str_split($str,2); print_r($result1);
explode(分割字符,待分割的字符串) 按照空格進(jìn)行分割
$str = 'Hello PHP Java C# C++'; $result = explode(' ',$str); print_r($result);
字符串的連接
$str = 'Hello PHP Java C# C++'; //字符串的連接 $num = 100; $str1 = $str.'<br/>Objective-C '.$num; echo $str1; echo '<br/>'; $str2 = "$str<br/>Objective-C $num"; //另一中簡(jiǎn)便的寫法 echo $str2;
- Thinkphp無(wú)限級(jí)分類代碼
- 2款PHP無(wú)限級(jí)分類實(shí)例代碼
- PHP防止刷新重復(fù)提交頁(yè)面的示例代碼
- php抓取并保存網(wǎng)站圖片的實(shí)現(xiàn)代碼
- PHP文件緩存類實(shí)現(xiàn)代碼
- 一個(gè)簡(jiǎn)單至極的PHP緩存類代碼
- php防止網(wǎng)站被攻擊的應(yīng)急代碼
- php限制文件下載速度的代碼
- PHP代碼判斷設(shè)備是手機(jī)還是平板電腦(兩種方法)
- jQuery+Ajax+PHP“喜歡”評(píng)級(jí)功能實(shí)現(xiàn)代碼
- PHP抽獎(jiǎng)算法程序代碼分享
- php視頻拍照上傳頭像功能實(shí)現(xiàn)代碼分享
- PHP常用的小程序代碼段
相關(guān)文章
Zend Framework教程之動(dòng)作的基類Zend_Controller_Action詳解
這篇文章主要介紹了Zend Framework教程之動(dòng)作的基類Zend_Controller_Action的用法,結(jié)合實(shí)例形式詳細(xì)分析了動(dòng)作的基類Zend_Controller_Action具體功能,使用方法與相關(guān)注意事項(xiàng),需要的朋友可以參考下2016-03-03thinkphp配置連接數(shù)據(jù)庫(kù)技巧
這篇文章主要介紹了thinkphp配置連接數(shù)據(jù)庫(kù)技巧,實(shí)例講述了ThinkPHP入口同目錄下配置數(shù)據(jù)庫(kù)及控制器另外連接數(shù)據(jù)庫(kù)的技巧,需要的朋友可以參考下2014-12-12使用PHP實(shí)現(xiàn)一個(gè)輕量級(jí)HTML模板引擎
在Web開發(fā)中,我們經(jīng)常需要?jiǎng)討B(tài)生成HTML頁(yè)面,為了提高開發(fā)效率和代碼可維護(hù)性,使用模板引擎是一個(gè)非常普遍的方案,本文將介紹如何使用PHP實(shí)現(xiàn)一個(gè)簡(jiǎn)單的HTML模板引擎,滿足變量綁定輸出和if判斷的需求,需要的朋友可以參考下2023-08-08修改apache配置文件去除thinkphp url中的index.php
這篇文章主要介紹了修改apache配置文件去除thinkphp url中的index.php的方法,大家參考使用吧2014-01-01基于PHP的簡(jiǎn)單采集數(shù)據(jù)入庫(kù)程序【續(xù)篇】
在上篇 基于PHP的簡(jiǎn)單采集數(shù)據(jù)入庫(kù)程序 中提到采集新聞信息頁(yè)的列表數(shù)據(jù),接下來(lái)講講關(guān)于采集新聞具體內(nèi)容2014-07-07php設(shè)計(jì)模式之命令模式的應(yīng)用詳解
本篇文章是對(duì)php的命令模式進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05PHP+Ajax異步帶進(jìn)度條上傳文件實(shí)例
這篇文章主要介紹了PHP+Ajax異步帶進(jìn)度條上傳文件實(shí)例代碼,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下。2016-11-11PHP提取字符串中的手機(jī)號(hào)正則表達(dá)式怎么寫
PHP通過(guò)正則表達(dá)式提取字符串中的手機(jī)號(hào)并判斷運(yùn)營(yíng)商,簡(jiǎn)單快速方便,能提取多個(gè)手機(jī)號(hào)。下面通過(guò)本文實(shí)例代碼給大家詳細(xì)介紹,需要的的朋友參考下吧2017-07-07