9 Very Useful PHP Code Snippets, _PHP Tutorial
Jul 12, 2016 am 08:54 AM非常有用的9個(gè)PHP代碼片段,
本文我們就來(lái)分享一下我收集的一些超級(jí)有用的PHP代碼片段。一起來(lái)看一看吧!
1.創(chuàng)建數(shù)據(jù)URI
數(shù)據(jù)URI在嵌入圖像到HTML / CSS / JS中以節(jié)省HTTP請(qǐng)求時(shí)非常有用,并且可以減少網(wǎng)站的加載時(shí)間。下面的函數(shù)可以創(chuàng)建基于$file的數(shù)據(jù)URI。
function data_uri($file, $mime) { $contents=file_get_contents($file); $base64=base64_encode($contents); echo "data:$mime;base64,$base64"; }
2.合并JavaScript和CSS文件
另一個(gè)可以盡量減少HTTP請(qǐng)求和節(jié)省頁(yè)面加載時(shí)間的好建議是:合并你的CSS和JS文件。雖然我更建議大家使用專(zhuān)用插件(例如minify),但使用PHP來(lái)合并文件也非常容易。我們來(lái)看一下:
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 '<script src="'. $destination_dir . $dest_file_name.'"></script>'; //output combined file }else{ //use stored file return '<script src="'. $destination_dir . $dest_file_name.'"></script>'; //output combine file } }
并且,用法是這樣的:
$files = array( 'http://example/files/sample_js_file_1.js', 'http://example/files/sample_js_file_2.js', 'http://example/files/beautyquote_functions.js', 'http://example/files/crop.js', 'http://example/files/jquery.autosize.min.js', ); echo combine_my_files($files, 'minified_files/', md5("my_mini_file").".js");
3.查看你的電子郵件是否已讀
當(dāng)發(fā)送電子郵件時(shí),你會(huì)希望知道你的郵件是否已讀。這里有一個(gè)非常有趣的代碼片段,它可以記錄閱讀你郵件的IP地址,以及實(shí)際的日期和時(shí)間。
<? 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 = "log.txt"; $fh = fopen($myFile, 'a+'); $stringData = $actual_day . ' ' . $actual_hour . ' ' . $ip . ' ' . $browser . ' ' . "\r\n"; 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.從網(wǎng)頁(yè)提取關(guān)鍵詞
正如這小標(biāo)題所說(shuō)的那樣:這個(gè)代碼片段能讓你輕易地從網(wǎng)頁(yè)中提取元關(guān)鍵詞。
$meta = get_meta_tags('http://www.emoticode.net/'); $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.查找頁(yè)面上的所有鏈接
使用DOM,你可以輕松地抓取來(lái)網(wǎng)頁(yè)上的所有鏈接。這里有一個(gè)工作示例:
$html = file_get_contents('http://www.example.com'); $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.'<br />'; }
6.自動(dòng)轉(zhuǎn)換URL為可點(diǎn)擊的超鏈接
在WordPress中,如果你想在字符串中自動(dòng)轉(zhuǎn)換所有的URL成可點(diǎn)擊的超鏈接,那么使用內(nèi)置函數(shù)make_clickable()可以讓你心想事成。如果你需要在WordPress之外這么做,那么你可以在wp-includes/formatting.php參考該函數(shù)的源代碼:
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] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $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] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>" . $ret; } function _make_email_clickable_cb($matches) { $email = $matches[2] . '@' . $matches[3]; return $matches[1] . "<a href=\"mailto:$email\">$email</a>"; } function make_clickable($ret) { $ret = ' ' . $ret; // in testing, using arrays here was found to be faster $ret = preg_replace_callback('#([\s>])([\w]+?://[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_url_clickable_cb', $ret); $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\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("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret); $ret = trim($ret); return $ret; }
7.在你的服務(wù)器上下載并保存遠(yuǎn)程圖像
在遠(yuǎn)程服務(wù)器上下載一個(gè)圖像,并將其保存在自己的服務(wù)器上,在建立網(wǎng)站時(shí)很有用,而且這也很容易做到。下面的這兩行代碼就能為你辦到。
$image = file_get_contents('http://www.url.com/image.jpg'); file_put_contents('/images/image.jpg', $image); //Where to save the image
8.檢測(cè)瀏覽器語(yǔ)言
如果你的網(wǎng)站使用多種語(yǔ)言,那么檢測(cè)瀏覽器語(yǔ)言,并將這種語(yǔ)言作為默認(rèn)語(yǔ)言會(huì)很有用。下面的代碼將返回客戶(hù)瀏覽器使用的語(yǔ)言。
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; }
9.全文顯示Facebook粉絲的數(shù)量
如果你的網(wǎng)站或博客有一個(gè)Facebook的頁(yè)面,那么你可能想要顯示你有多少個(gè)粉絲。這個(gè)代碼片段可以幫助你獲取Facebook粉絲的數(shù)量。不要忘記在第二行添加你的頁(yè)面ID。頁(yè)面ID可以在地址http://facebook.com/yourpagename/info找到。
<?php $page_id = "302807633129400"; $xml = @simplexml_load_file("http://api.facebook.com/restserver.php?method=facebook.fql.query&query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=".$page_id."") or die ("a lot"); $fans = $xml->page->fan_count; echo $fans; ?>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。
您可能感興趣的文章:
- 7個(gè)超級(jí)實(shí)用的PHP代碼片段
- 10個(gè)實(shí)用的PHP代碼片段
- php中常用字符串處理代碼片段整理
- 超級(jí)實(shí)用的7個(gè)PHP代碼片段分享
- PHP 安全檢測(cè)代碼片段(分享)
- 19個(gè)超實(shí)用的PHP代碼片段
- 9個(gè)經(jīng)典的PHP代碼片段分享
- 10個(gè)超級(jí)有用值得收藏的PHP代碼片段
- 46 個(gè)非常有用的 PHP 代碼片段

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses
