當前位置:才華齋>計算機>php語言>

超級實用的9個PHP程式碼片段

php語言 閱讀(2.33W)

在開發網站、app或部落格時,程式碼片段可以真正地為你節省時間。今天,讓我們一起來分享小編收集整理好的這些超級有用的PHP程式碼片段。一起來看一看吧!

超級實用的9個PHP程式碼片段

  1.建立資料URI

資料URI在嵌入影象到HTML / CSS / JS中以節省HTTP請求時非常有用,並且可以減少網站的載入時間。下面的函式可以建立基於$file的資料URI。

function data_uri($file, $mime) {

$contents=file_get_contents($file);

$base64=base64_encode($contents);

echo "data:$mime;base64,$base64";

}

  2.合併JavaScript和CSS檔案

另一個可以儘量減少HTTP請求和節省頁面載入時間的好建議是:合併你的CSS和JS檔案。雖然我更建議大家使用專用外掛(例如minify),但使用PHP來合併檔案也非常容易。我們來看一下:

function combine_my_files($array_files, $destination_dir, $dest_file_name){

if(!is_file($destination_dir . $dest_file_name)){ //continue only if file doesn't exist

$content = "";

foreach ($array_files as $file){ //loop through array list

$content .= file_get_contents($file); //read each file

}

//You can use some sort of minifier here

//minify_my_js($content);

$new_file = fopen($destination_dir . $dest_file_name, "w" ); //open file for writing

fwrite($new_file , $content); //write to destination

fclose($new_file);

return ''; //output combined file

}else{

//use stored file

return ''; //output combine file

}

}

並且,用法是這樣的:

$files = array(

'http://example/files/sample_js_file_',

'http://example/files/sample_js_file_',

'http://example/files/beautyquote_',

'http://example/files/',

'http://example/files/',

);

echo combine_my_files($files, 'minified_files/', md5("my_mini_file")."");

  3.檢視你的電子郵件是否已讀

當傳送電子郵件時,你會希望知道你的郵件是否已讀。這裡有一個非常有趣的程式碼片段,它可以記錄閱讀你郵件的IP地址,以及實際的日期和時間。

error_reporting(0);

Header("Content-Type: image/jpeg");

//Get IP

if (!empty($_SERVER['HTTP_CLIENT_IP']))

{

$ip=$_SERVER['HTTP_CLIENT_IP'];

}

elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))

{

$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];

}

else

{

$ip=$_SERVER['REMOTE_ADDR'];

}

//Time

$actual_time = time();

$actual_day = date('Y.m.d', $actual_time);

$actual_day_chart = date('d/m/y', $actual_time);

$actual_hour = date('H:i:s', $actual_time);

//GET Browser

$browser = $_SERVER['HTTP_USER_AGENT'];

//LOG

$myFile = "";

$fh = fopen($myFile, 'a+');

$stringData = $actual_day . ' ' . $actual_hour . ' ' . $ip . ' ' . $browser . ' ' . " ";

fwrite($fh, $stringData);

fclose($fh);

//Generate Image (Es. dimesion is 1x1)

$newimage = ImageCreate(1,1);

$grigio = ImageColorAllocate($newimage,255,255,255);

ImageJPEG($newimage);

ImageDestroy($newimage);

?>

  4.從網頁提取關鍵詞

正如這小標題所說的那樣:這個程式碼片段能讓你輕易地從網頁中提取元關鍵詞。

$meta = get_meta_tags('');

$keywords = $meta['keywords'];

// Split keywords

$keywords = explode(',', $keywords );

// Trim them

$keywords = array_map( 'trim', $keywords );

// Remove empty values

$keywords = array_filter( $keywords );

print_r( $keywords );

  5.查詢頁面上的所有連結

使用DOM,你可以輕鬆地抓取來網頁上的所有連結。這裡有一個工作示例:

$html = file_get_contents('');

$dom = new DOMDocument();

@$dom->loadHTML($html);

// grab all the on the page

$xpath = new DOMXPath($dom);

$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {

$href = $hrefs->item($i);

$url = $href->getAttribute('href');

echo $url.'

';

}

  6.自動轉換URL為可點選的超連結

在WordPress中,如果你想在字串中自動轉換所有的URL成可點選的超連結,那麼使用內建函式make_clickable()可以讓你心想事成。如果你需要在WordPress之外這麼做,那麼你可以在wp-includes/參考該函式的原始碼:

function _make_url_clickable_cb($matches) {

$ret = '';

$url = $matches[2];

if ( empty($url) )

return $matches[0];

// removed trailing [.,;:] from URL

if ( in_array(substr($url, -1), array('.', ',', ';', ':')) === true ) {

$ret = substr($url, -1);

$url = substr($url, 0, strlen($url)-1);

}

return $matches[1] . "$url" . $ret;

}

function _make_web_ftp_clickable_cb($matches) {

$ret = '';

$dest = $matches[2];

$dest = 'http://' . $dest;

if ( empty($dest) )

return $matches[0];

// removed trailing [,;:] from URL

if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) {

$ret = substr($dest, -1);

$dest = substr($dest, 0, strlen($dest)-1);

}

return $matches[1] . "$dest" . $ret;

}

function _make_email_clickable_cb($matches) {

$email = $matches[2] . '@' . $matches[3];

return $matches[1] . "$email";

}

function make_clickable($ret) {

$ret = ' ' . $ret;

// in testing, using arrays here was found to be faster

$ret = preg_replace_callback('#([s>])([w]+?://[wx80-xff#$%&~/.-;:=,?@[]+]*)#is', '_make_url_clickable_cb', $ret);

$ret = preg_replace_callback('#([s>])((www|ftp).[wx80-xff#$%&~/.-;:=,?@[]+]*)#is', '_make_web_ftp_clickable_cb', $ret);

$ret = preg_replace_callback('#([s>])([.0-9a-z_+-]+)@(([0-9a-z-]+.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);

// this one is not in an array because we need it to run last, for cleanup of accidental links within links

$ret = preg_replace("#(]+?>|>))]+?>([^>]+?)#i", "$1$3", $ret);

$ret = trim($ret);

return $ret;

}