Home Backend Development PHP Tutorial php Ten super useful PHP code snippets

php Ten super useful PHP code snippets

Jul 25, 2016 am 08:42 AM

Ten super useful php code snippets

[PHP] code

  1. 1. Send SMS
  2. Call TextMagic API.
  3. // Include the TextMagic PHP lib
  4. require('textmagic-sms-api-php/TextMagicAPI.php');
  5. // Set the username and password information
  6. $username = 'myusername';
  7. $password = 'mypassword';
  8. // Create a new instance of TM
  9. $router = new TextMagicAPI(array(
  10. 'username' => $username,
  11. 'password' => $password
  12. ));
  13. // Send a text message to '999-123-4567'
  14. $result = $router->send('Wake up!', array(9991234567), true);
  15. // result: Result is: Array ( [messages] => Array ( [19896128] => 9991234567 ) [sent_text] => Wake up! [parts_count] => 1 )
  16. 2. 根据IP查找地址
  17. function detect_city($ip) {
  18. $default = 'UNKNOWN';
  19. if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost')
  20. $ip = '8.8.8.8';
  21. $curlopt_useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';
  22. $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
  23. $ch = curl_init();
  24. $curl_opt = array(
  25. CURLOPT_FOLLOWLOCATION => 1,
  26. CURLOPT_HEADER => 0,
  27. CURLOPT_RETURNTRANSFER => 1,
  28. CURLOPT_USERAGENT => $curlopt_useragent,
  29. CURLOPT_URL => $url,
  30. CURLOPT_TIMEOUT => 1,
  31. CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],
  32. );
  33. curl_setopt_array($ch, $curl_opt);
  34. $content = curl_exec($ch);
  35. if (!is_null($curl_info)) {
  36. $curl_info = curl_getinfo($ch);
  37. }
  38. curl_close($ch);
  39. if ( preg_match('{
  40. City : ([^<]*)
  41. }i', $content, $regs) ) {
  42. $city = $regs[1];
  43. }
  44. if ( preg_match('{
  45. State/Province : ([^<]*)
  46. }i', $content, $regs) ) {
  47. $state = $regs[1];
  48. }
  49. if( $city!='' && $state!='' ){
  50. $location = $city . ', ' . $state;
  51. return$location;
  52. }else{
  53. return$default;
  54. }
  55. }
  56. 3. 显示网页的源代码
  57. $lines = file('http://google.com/');
  58. foreach ($lines as $line_num => $line) {
  59. // loop thru each line and prepend line numbers
  60. echo "Line #{$line_num} : " . htmlspecialchars($line) . "
    n";
  61. }
  62. 4. 检查服务器是否使用HTTPS
  63. if ($_SERVER['HTTPS'] != "on") {
  64. echo "This is not HTTPS";
  65. }else{
  66. echo "This is HTTPS";
  67. }
  68. 5. 显示Faceboo**丝数量
  69. function fb_fan_count($facebook_name){
  70. // Example: https://graph.facebook.com/digimantra
  71. $data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));
  72. echo $data->likes;
  73. }
  74. 6. 检测图片的主要颜色
  75. $i = imagecreatefromjpeg("image.jpg");
  76. for ($x=0;$xfor ($y=0;$y$rgb = imagecolorat($i,$x,$y);
  77. $r = ($rgb >> 16) & 0xFF;
  78. $g = ($rgb >> & 0xFF;
  79. $b = $rgb & 0xFF;
  80. $rTotal += $r;
  81. $gTotal += $g;
  82. $bTotal += $b;
  83. $total++;
  84. }
  85. }
  86. $rAverage = round($rTotal/$total);
  87. $gAverage = round($gTotal/$total);
  88. $bAverage = round($bTotal/$total);
  89. 7. 获取内存使用信息
  90. echo"Initial: ".memory_get_usage()." bytes n";
  91. /* prints
  92. Initial: 361400 bytes
  93. */
  94. // http://www.baoluowanxiang.com/
  95. // let's use up some memory
  96. for ($i = 0; $i < 100000; $i++) {
  97. $array []= md5($i);
  98. }
  99. // let's remove half of the array
  100. for ($i = 0; $i < 100000; $i++) {
  101. unset($array[$i]);
  102. }
  103. echo"Final: ".memory_get_usage()." bytes n";
  104. /* prints
  105. Final: 885912 bytes
  106. */
  107. echo"Peak: ".memory_get_peak_usage()." bytes n";
  108. /* prints
  109. Peak: 13687072 bytes
  110. */
  111. 8. Use gzcompress() to compress data
  112. $string =
  113. "The pain itself should be real, it will be followed
  114. adipiscing elit. Now as elit it my ultricies
  115. adipiscing. No facilisi. Praesent pulvinar,
  116. sapien or feugiat vestibulum, no dui price orci,
  117. not ultricies lacus
  118. sit amet adipiscing
  119. the price of ullamcorper
  120. sed turpis
  121. to decorate a now
  122. Nullam in neque methres hendrerit
  123. eu no for. Ut malesuada lacus nulla drinkum
  124. id euismod urna. ";
  125. $compressed = gzcompress($string);
  126. echo "Original size: ". strlen($string)."n";
  127. /* prints
  128. Original size: 800
  129. */
  130. echo "Compressed size: ". strlen($compressed)."n";
  131. /* prints
  132. Compressed size: 418
  133. */
  134. // getting it back
  135. $original = gzuncompress($compressed);
  136. 9. Using PHP 做Whois 免费
  137. function whois_query($domain) {
  138. // fix the domain name:
  139. $domain = strtolower(trim($domain));
  140. $domain = preg_replace('/^http:/// i', '', $domain);
  141. $domain = preg_replace('/^www./i', '', $domain);
  142. $domain = explode('/', $domain);
  143. $domain = trim($domain[0]);
  144. // split the TLD from domain name
  145. $_domain = explode('.', $domain);
  146. $lst = count($_domain)-1;
  147. $ext = $ _domain[$lst];
  148. // You find resources and lists
  149. // like these on wikipedia:
  150. //
  151. // http://de.wikipedia.org/wiki/Whois
  152. //
  153. $servers = array (
  154. "biz" => "whois.neulevel.biz",
  155. "com" => "whois.internic.net",
  156. "us" => "whois.nic.us",
  157. "coop" => "whois.nic.coop" => "whois.nic.name" => "whois.nic.name" => .internic.net",
  158. "gov" => "whois.nic.gov",
  159. "edu" => "whois.internic.net",
  160. "mil" => "rs.internic.net" ,
  161. "int" => "whois.iana.org",
  162. "ac" => "whois.uaenic.ae" => "whois.ripe.net",
  163. "au" => "whois.aunic.net" => "whois.dns.be" => "whois.ripe.net",
  164. "br" => "whois.registro.br",
  165. "bz" => "whois.belizenic.bz",
  166. "ca" => "whois.cira.ca",
  167. "cc" => "whois.nic.cc",
  168. "ch" => "whois.nic.ch",
  169. "cl" => "whois.nic.cl",
  170. "cn" => "whois.cnnic.net.cn",
  171. "cz" => "whois.nic.cz",
  172. "de" => "whois.nic.de",
  173. "fr" => "whois.nic.fr",
  174. "hu" => "whois.nic.hu",
  175. "ie" => "whois.domainregistry.ie",
  176. "il" => "whois.isoc.org.il",
  177. "in" => "whois.ncst.ernet.in",
  178. "ir" => "whois.nic.ir",
  179. "mc" => "whois.ripe.net",
  180. "to" => "whois.tonic.to",
  181. "tv" => "whois.tv",
  182. "ru" => "whois.ripn.net",
  183. "org" => "whois.pir.org",
  184. "aero" => "whois.information.aero",
  185. "nl" => "whois.domain-registry.nl"
  186. );
  187. if (!isset($servers[$ext])){
  188. die('Error: No matching nic server found!');
  189. }
  190. $nic_server = $servers[$ext];
  191. $output = '';
  192. // connect to whois server:
  193. if ($conn = fsockopen ($nic_server, 43)) {
  194. fputs($conn, $domain."rn ");
  195. while(!feof($conn)) {
  196. $output .= fgets($conn,128);
  197. }
  198. fclose($conn);
  199. }
  200. else { die('Error: Could not connect to ' . $nic_server '!'); }
  201. return $output;
  202. }
  203. 10. 通过Email发送PHP错误
  204. // Our custom error handler
  205. function nettuts_error_handler($number, $message, $file, $line, $vars){
  206. $email = "
  207. An error ($number) occurred on line

  208. $line and in the file: $file.
  209. $message

    ";
  210. $email .= "
    " . print_r($vars, 1) . "
    ";
  211. $headers = 'Content-type: text/html; charset=iso-8859-1' . "rn";
  212. // Email the error to someone...
  213. error_log($email, 1, 'you@youremail.com', $headers);
  214. // Make sure that you decide how to respond to errors (on the user's side)
  215. // Either echo an error message, or kill the entire project. Up to you...
  216. // The code below ensures that we only "die" if the error was more than
  217. // just a NOTICE.
  218. if ( ($number !== E_NOTICE) && ($number < 2048) ) {
  219. die("There was an error. Please try again later.");
  220. }
  221. }
  222. // We should use our custom function to handle errors.
  223. set_error_handler('nettuts_error_handler');
  224. // Trigger an error... (var doesn't exist)
  225. echo$somevarthatdoesnotexist;
复制代码
php, PHP


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles