18. 使用 mail() 发送邮件
之前我们提供了如何使用 Mandrill 发送邮件的 PHP 代码片段,但是如果你不想使用第三方服务,那么可以使用下面的 PHP 代码片段。
function send_mail($to,$subject,$body) { $headers = "From: KOONK\r\n"; $headers .= "Reply-To: blog@koonk.com\r\n"; $headers .= "Return-Path: blog@koonk.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); }
语法:
<?php $to = "admin@koonk.com"; $subject = "This is a test mail"; $body = "Hello World!"; send_mail($to,$subject,$body); ?>
19. 把秒转换成天数,小时数和分钟
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; }
语法:
<?php $seconds = "56789"; $output = secsToStr($seconds); echo $output; ?>
20. 数据库连接
连接 MySQL 数据库
<?php $DBNAME = 'koonk'; $HOST = 'localhost'; $DBUSER = 'root'; $DBPASS = 'koonk'; $CONNECT = mysql_connect($HOST,$DBUSER,$DBPASS); if(!$CONNECT) { echo 'MySQL Error: '.mysql_error(); } $SELECT = mysql_select_db($DBNAME); if(!$SELECT) { echo 'MySQL Error: '.mysql_error(); } ?>
21. 目录清单
使用下面的 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="'https://www.jb51.net/article/.$dir.$file.'">'.$file.'</a>'."\n"; } } closedir($handle); } } }
语法:
<?php list_files("images/"); //This will list all files of images folder ?>
22. 检测用户语言
使用下面的 PHP 代码片段可以检测用户浏览器所使用的语言
function get_client_language($availableLanguages, $default='en'){ if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']); foreach ($langs as $value){ $choice=substr($value,0,2); if(in_array($choice, $availableLanguages)){ return $choice; } } } return $default; }
23. 查看 CSV 文件
function readCSV($csvFile){ $file_handle = fopen($csvFile, 'r'); while (!feof($file_handle) ) { $line_of_text[] = fgetcsv($file_handle, 1024); } fclose($file_handle); return $line_of_text; }
语法:
<?php $csvFile = "test.csv"; $csv = readCSV($csvFile); $a = csv[0][0]; // This will get value of Column 1 & Row 1 ?>