国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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. 根據(jù)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. 顯示網(wǎng)頁的源代碼
  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. 檢查服務(wù)器是否使用HTTPS
  63. if ($_SERVER['HTTPS'] != "on") {
  64. echo "This is not HTTPS";
  65. }else{
  66. echo "This is HTTPS";
  67. }
  68. 5. 顯示Faceboo**絲數(shù)量
  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. 獲取內(nèi)存使用信息
  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發(fā)送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;
復(fù)制代碼
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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

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)

How do I implement authentication and authorization in PHP? How do I implement authentication and authorization in PHP? Jun 20, 2025 am 01:03 AM

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

How can you handle file uploads securely in PHP? How can you handle file uploads securely in PHP? Jun 19, 2025 am 01:05 AM

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

What are the differences between == (loose comparison) and === (strict comparison) in PHP? What are the differences between == (loose comparison) and === (strict comparison) in PHP? Jun 19, 2025 am 01:07 AM

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

How do I perform arithmetic operations in PHP ( , -, *, /, %)? How do I perform arithmetic operations in PHP ( , -, *, /, %)? Jun 19, 2025 pm 05:13 PM

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? Jun 19, 2025 am 01:07 AM

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

How do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

What is PHP, and why is it used for web development? What is PHP, and why is it used for web development? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

See all articles