search
HomeBackend DevelopmentPHP Tutorialphp Ten super useful PHP code snippets

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

  203. $line and in the file: $file.
  204. $message

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


Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)