分享10段PHP常用代碼_php執行個體

來源:互聯網
上載者:User

本文彙集PHP開發中經常用到的十段代碼,包括Email、64位編碼和解碼、解壓縮、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 dateif (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts)){//check weather the date is valid of notif(checkdate($parts[2],$parts[3],$parts[1]))return true;elsereturn false;}elsereturn 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.';}

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 moleculeforeach ($xml-﹥molecule as $record){ //attribute are accessted by echo $record['name'], ' '; //node are accessted by -﹥ operator echo $record-﹥symbol, ' '; echo $record-﹥code, '﹤br /﹥';}

7、資料庫連接

﹤?phpif(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:﹤?phpinclude 'functions.php';if(unzip('zipedfiles/test.zip','unziped/myNewZip')) echo 'Success!';else echo 'Error';?﹥

PHP常用功能如下

1.PHP字串

字串聲明 變數=''或者""(一般情況會使用單引號,因為寫起來會比較方便)

$str = 'Hello PHP';
echo $str;

strpos 計算字元在字串中的位置(從0開始)

$str = 'Hello PHP';
echo strpos($str,'o');  //計算字元在字串中的位置
echo '<br/>';
echo strpos($str,'PH');

substr 截取字串

$str = 'Hello PHP';//截取字串$str1 = substr($str,2,3); //從2位置開始截取,截取長度為3的字串echo $str1;

不傳入長度參數的話,會從指定位置一直截取到字串的末尾

str_split 分割字串  固定長度的分割(預設長度為1)

$str = 'Hello PHP';//分割字串$result = str_split($str); //將結果儲存到一個數組中print_r($result); //使用print_r輸入一個數組echo '<br/>';$result1 = str_split($str,2);print_r($result1);

explode(分割字元,待分割的字串) 按照空格進行分割

$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"; //另一中簡便的寫法echo $str2;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.