搜索
首页后端开发php教程php 十个超级有用的PHP代码片段

十个超级有用的php代码片段

[PHP]代码

  1. 1. 发送短信
  2. 调用 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. 使用 gzcompress() 压缩数据
  107. $string =
  108. "Lorem ipsum dolor sit amet, consectetur
  109. adipiscing elit. Nunc ut elit id mi ultricies
  110. adipiscing. Nulla facilisi. Praesent pulvinar,
  111. sapien vel feugiat vestibulum, nulla dui pretium orci,
  112. non ultricies elit lacus quis ante. Lorem ipsum dolor
  113. sit amet, consectetur adipiscing elit. Aliquam
  114. pretium ullamcorper urna quis iaculis. Etiam ac massa
  115. sed turpis tempor luctus. Curabitur sed nibh eu elit
  116. mollis congue. Praesent ipsum diam, consectetur vitae
  117. ornare a, aliquam a nunc. In id magna pellentesque
  118. tellus posuere adipiscing. Sed non mi metus, at lacinia
  119. augue. Sed magna nisi, ornare in mollis in, mollis
  120. sed nunc. Etiam at justo in leo congue mollis.
  121. Nullam in neque eget metus hendrerit scelerisque
  122. eu non enim. Ut malesuada lacus eu nulla bibendum
  123. id euismod urna sodales. ";
  124. $compressed = gzcompress($string);
  125. echo "Original size: ". strlen($string)."\n";
  126. /* prints
  127. Original size: 800
  128. */
  129. echo "Compressed size: ". strlen($compressed)."\n";
  130. /* prints
  131. Compressed size: 418
  132. */
  133. // getting it back
  134. $original = gzuncompress($compressed);
  135. 9. 使用PHP做Whois检查
  136. function whois_query($domain) {
  137. // fix the domain name:
  138. $domain = strtolower(trim($domain));
  139. $domain = preg_replace('/^http:\/\//i', '', $domain);
  140. $domain = preg_replace('/^www\./i', '', $domain);
  141. $domain = explode('/', $domain);
  142. $domain = trim($domain[0]);
  143. // split the TLD from domain name
  144. $_domain = explode('.', $domain);
  145. $lst = count($_domain)-1;
  146. $ext = $_domain[$lst];
  147. // You find resources and lists
  148. // like these on wikipedia:
  149. //
  150. // http://de.wikipedia.org/wiki/Whois
  151. //
  152. $servers = array(
  153. "biz" => "whois.neulevel.biz",
  154. "com" => "whois.internic.net",
  155. "us" => "whois.nic.us",
  156. "coop" => "whois.nic.coop",
  157. "info" => "whois.nic.info",
  158. "name" => "whois.nic.name",
  159. "net" => "whois.internic.net",
  160. "gov" => "whois.nic.gov",
  161. "edu" => "whois.internic.net",
  162. "mil" => "rs.internic.net",
  163. "int" => "whois.iana.org",
  164. "ac" => "whois.nic.ac",
  165. "ae" => "whois.uaenic.ae",
  166. "at" => "whois.ripe.net",
  167. "au" => "whois.aunic.net",
  168. "be" => "whois.dns.be",
  169. "bg" => "whois.ripe.net",
  170. "br" => "whois.registro.br",
  171. "bz" => "whois.belizenic.bz",
  172. "ca" => "whois.cira.ca",
  173. "cc" => "whois.nic.cc",
  174. "ch" => "whois.nic.ch",
  175. "cl" => "whois.nic.cl",
  176. "cn" => "whois.cnnic.net.cn",
  177. "cz" => "whois.nic.cz",
  178. "de" => "whois.nic.de",
  179. "fr" => "whois.nic.fr",
  180. "hu" => "whois.nic.hu",
  181. "ie" => "whois.domainregistry.ie",
  182. "il" => "whois.isoc.org.il",
  183. "in" => "whois.ncst.ernet.in",
  184. "ir" => "whois.nic.ir",
  185. "mc" => "whois.ripe.net",
  186. "to" => "whois.tonic.to",
  187. "tv" => "whois.tv",
  188. "ru" => "whois.ripn.net",
  189. "org" => "whois.pir.org",
  190. "aero" => "whois.information.aero",
  191. "nl" => "whois.domain-registry.nl"
  192. );
  193. if (!isset($servers[$ext])){
  194. die('Error: No matching nic server found!');
  195. }
  196. $nic_server = $servers[$ext];
  197. $output = '';
  198. // connect to whois server:
  199. if ($conn = fsockopen ($nic_server, 43)) {
  200. fputs($conn, $domain."\r\n");
  201. while(!feof($conn)) {
  202. $output .= fgets($conn,128);
  203. }
  204. fclose($conn);
  205. }
  206. else { die('Error: Could not connect to ' . $nic_server . '!'); }
  207. return $output;
  208. }
  209. 10. 通过Email发送PHP错误
  210. // Our custom error handler
  211. function nettuts_error_handler($number, $message, $file, $line, $vars){
  212. $email = "
  213. An error ($number) occurred on line

  214. $line and in the file: $file.
  215. $message

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


声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
使用数据库存储会话的优点是什么?使用数据库存储会话的优点是什么?Apr 24, 2025 am 12:16 AM

使用数据库存储会话的主要优势包括持久性、可扩展性和安全性。1.持久性:即使服务器重启,会话数据也能保持不变。2.可扩展性:适用于分布式系统,确保会话数据在多服务器间同步。3.安全性:数据库提供加密存储,保护敏感信息。

您如何在PHP中实现自定义会话处理?您如何在PHP中实现自定义会话处理?Apr 24, 2025 am 12:16 AM

在PHP中实现自定义会话处理可以通过实现SessionHandlerInterface接口来完成。具体步骤包括:1)创建实现SessionHandlerInterface的类,如CustomSessionHandler;2)重写接口中的方法(如open,close,read,write,destroy,gc)来定义会话数据的生命周期和存储方式;3)在PHP脚本中注册自定义会话处理器并启动会话。这样可以将数据存储在MySQL、Redis等介质中,提升性能、安全性和可扩展性。

什么是会话ID?什么是会话ID?Apr 24, 2025 am 12:13 AM

SessionID是网络应用程序中用来跟踪用户会话状态的机制。1.它是一个随机生成的字符串,用于在用户与服务器之间的多次交互中保持用户的身份信息。2.服务器生成并通过cookie或URL参数发送给客户端,帮助在用户的多次请求中识别和关联这些请求。3.生成通常使用随机算法保证唯一性和不可预测性。4.在实际开发中,可以使用内存数据库如Redis来存储session数据,提升性能和安全性。

您如何在无状态环境(例如API)中处理会议?您如何在无状态环境(例如API)中处理会议?Apr 24, 2025 am 12:12 AM

在无状态环境如API中管理会话可以通过使用JWT或cookies来实现。1.JWT适合无状态和可扩展性,但大数据时体积大。2.Cookies更传统且易实现,但需谨慎配置以确保安全性。

您如何防止与会议有关的跨站点脚本(XSS)攻击?您如何防止与会议有关的跨站点脚本(XSS)攻击?Apr 23, 2025 am 12:16 AM

要保护应用免受与会话相关的XSS攻击,需采取以下措施:1.设置HttpOnly和Secure标志保护会话cookie。2.对所有用户输入进行输出编码。3.实施内容安全策略(CSP)限制脚本来源。通过这些策略,可以有效防护会话相关的XSS攻击,确保用户数据安全。

您如何优化PHP会话性能?您如何优化PHP会话性能?Apr 23, 2025 am 12:13 AM

优化PHP会话性能的方法包括:1.延迟会话启动,2.使用数据库存储会话,3.压缩会话数据,4.管理会话生命周期,5.实现会话共享。这些策略能显着提升应用在高并发环境下的效率。

什么是session.gc_maxlifetime配置设置?什么是session.gc_maxlifetime配置设置?Apr 23, 2025 am 12:10 AM

thesession.gc_maxlifetimesettinginphpdeterminesthelifespanofsessiondata,setInSeconds.1)它'sconfiguredinphp.iniorviaini_set().2)abalanceIsiseededeedeedeedeedeedeedto to to avoidperformance andununununununexpectedLogOgouts.3)

您如何在PHP中配置会话名?您如何在PHP中配置会话名?Apr 23, 2025 am 12:08 AM

在PHP中,可以使用session_name()函数配置会话名称。具体步骤如下:1.使用session_name()函数设置会话名称,例如session_name("my_session")。2.在设置会话名称后,调用session_start()启动会话。配置会话名称可以避免多应用间的会话数据冲突,并增强安全性,但需注意会话名称的唯一性、安全性、长度和设置时机。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)