찾다
백엔드 개발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 28, 2025 am 12:25 AM

세션 고정 공격을 방지하는 효과적인 방법은 다음과 같습니다. 1. 사용자 로그인 한 후 세션 ID 재생; 2. 보안 세션 ID 생성 알고리즘을 사용하십시오. 3. 세션 시간 초과 메커니즘을 구현하십시오. 4. HTTPS를 사용한 세션 데이터를 암호화합니다. 이러한 조치는 세션 고정 공격에 직면 할 때 응용 프로그램이 파괴 할 수 없도록 할 수 있습니다.

세션리스 인증을 어떻게 구현합니까?세션리스 인증을 어떻게 구현합니까?Apr 28, 2025 am 12:24 AM

서버 측 세션 스토리지가없는 토큰에 저장되는 토큰 기반 인증 시스템 인 JSONWEBTOKENS (JWT)를 사용하여 세션없는 인증 구현을 수행 할 수 있습니다. 1) JWT를 사용하여 토큰을 생성하고 검증하십시오. 2) HTTPS가 토큰이 가로 채지 못하도록하는 데 사용되도록, 3) 클라이언트 측의 토큰을 안전하게 저장, 4) 변조 방지를 방지하기 위해 서버 측의 토큰을 확인하기 위해 단기 접근 메커니즘 및 장기 상쾌한 토큰을 구현하십시오.

PHP 세션과 관련된 일반적인 보안 위험은 무엇입니까?PHP 세션과 관련된 일반적인 보안 위험은 무엇입니까?Apr 28, 2025 am 12:24 AM

PHP 세션의 보안 위험에는 주로 세션 납치, 세션 고정, 세션 예측 및 세션 중독이 포함됩니다. 1. HTTPS를 사용하고 쿠키를 보호하여 세션 납치를 방지 할 수 있습니다. 2. 사용자가 로그인하기 전에 세션 ID를 재생하여 세션 고정을 피할 수 있습니다. 3. 세션 예측은 세션 ID의 무작위성과 예측 불가능 성을 보장해야합니다. 4. 세션 중독 데이터를 확인하고 필터링하여 세션 중독을 방지 할 수 있습니다.

PHP 세션을 어떻게 파괴합니까?PHP 세션을 어떻게 파괴합니까?Apr 28, 2025 am 12:16 AM

PHP 세션을 파괴하려면 먼저 세션을 시작한 다음 데이터를 지우고 세션 파일을 파괴해야합니다. 1. 세션을 시작하려면 세션 _start ()를 사용하십시오. 2. Session_Unset ()을 사용하여 세션 데이터를 지우십시오. 3. 마지막으로 Session_Destroy ()를 사용하여 세션 파일을 파괴하여 데이터 보안 및 리소스 릴리스를 보장하십시오.

PHP의 기본 세션 저장 경로를 어떻게 변경할 수 있습니까?PHP의 기본 세션 저장 경로를 어떻게 변경할 수 있습니까?Apr 28, 2025 am 12:12 AM

PHP의 기본 세션 저장 경로를 변경하는 방법은 무엇입니까? 다음 단계를 통해 달성 할 수 있습니다. session_save_path를 사용하십시오 ( '/var/www/sessions'); session_start (); PHP 스크립트에서 세션 저장 경로를 설정합니다. php.ini 파일에서 세션을 설정하여 세션 저장 경로를 전 세계적으로 변경하려면 세션을 설정하십시오. memcached 또는 redis를 사용하여 ini_set ( 'session.save_handler', 'memcached')과 같은 세션 데이터를 저장합니다. ini_set (

PHP 세션에 저장된 데이터를 어떻게 수정합니까?PHP 세션에 저장된 데이터를 어떻게 수정합니까?Apr 27, 2025 am 12:23 AM

tomodifyDatainAphPessess, startSessionstession_start (), 그런 다음 $ _sessionToset, modify, orremovevariables.

PHP 세션에 배열을 저장하는 예를 제시하십시오.PHP 세션에 배열을 저장하는 예를 제시하십시오.Apr 27, 2025 am 12:20 AM

배열은 PHP 세션에 저장할 수 있습니다. 1. 세션을 시작하고 session_start ()를 사용하십시오. 2. 배열을 만들고 $ _session에 저장하십시오. 3. $ _session을 통해 배열을 검색하십시오. 4. 세션 데이터를 최적화하여 성능을 향상시킵니다.

Garbage Collection은 PHP 세션에 어떻게 효과가 있습니까?Garbage Collection은 PHP 세션에 어떻게 효과가 있습니까?Apr 27, 2025 am 12:19 AM

PHP 세션 쓰레기 수집은 만료 된 세션 데이터를 정리하기위한 확률 메커니즘을 통해 트리거됩니다. 1) 구성 파일에서 트리거 확률 및 세션 수명주기를 설정합니다. 2) CRON 작업을 사용하여 고재 응용 프로그램을 최적화 할 수 있습니다. 3) 데이터 손실을 피하기 위해 쓰레기 수집 빈도 및 성능의 균형을 맞춰야합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전