백엔드 개발 PHP 튜토리얼 PHP代码片断(发送短信、根据IP查找地址、显示网页的源代码、检查服务器是否使用HTTPS、显示Faceboo*丝数量、检测图片的主要颜色、获取内存使用信息)

PHP代码片断(发送短信、根据IP查找地址、显示网页的源代码、检查服务器是否使用HTTPS、显示Faceboo*丝数量、检测图片的主要颜色、获取内存使用信息)

Jun 13, 2016 am 10:38 AM
error gt nic

PHP代码片段(发送短信、根据IP查找地址、显示网页的源代码、检查服务器是否使用HTTPS、显示Faceboo**丝数量、检测图片的主要颜色、获取内存使用信息)

1. 发送短信调用 TextMagic API。// Include the TextMagic PHP librequire('textmagic-sms-api-php/TextMagicAPI.php');// Set the username and password information$username = 'myusername';$password = 'mypassword';// Create a new instance of TM$router = new TextMagicAPI(array('username' => $username,'password' => $password));// Send a text message to '999-123-4567'$result = $router->send('Wake up!', array(9991234567), true);// result: Result is: Array ( [messages] => Array ( [19896128] => 9991234567 ) [sent_text] => Wake up! [parts_count] => 1 )2. 根据IP查找地址function detect_city($ip) {$default = 'UNKNOWN';if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost')$ip = '8.8.8.8';$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)';$url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);$ch = curl_init();$curl_opt = array(CURLOPT_FOLLOWLOCATION => 1,CURLOPT_HEADER => 0,CURLOPT_RETURNTRANSFER => 1,CURLOPT_USERAGENT => $curlopt_useragent,CURLOPT_URL => $url,CURLOPT_TIMEOUT => 1,CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],);curl_setopt_array($ch, $curl_opt);$content = curl_exec($ch);if (!is_null($curl_info)) {$curl_info = curl_getinfo($ch);}curl_close($ch);if ( preg_match('{<li>City : ([^<]*)</li>}i', $content, $regs) ) {$city = $regs[1];}if ( preg_match('{<li>State/Province : ([^<]*)</li>}i', $content, $regs) ) {$state = $regs[1];}if( $city!='' && $state!='' ){$location = $city . ', ' . $state;return$location;}else{return$default;}}3. 显示网页的源代码<?php // display source code$lines = file('http://google.com/');foreach ($lines as $line_num => $line) {// loop thru each line and prepend line numbersecho "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>\n";}4. 检查服务器是否使用HTTPSif ($_SERVER['HTTPS'] != "on") {echo "This is not HTTPS";}else{echo "This is HTTPS";}5. 显示Faceboo**丝数量function fb_fan_count($facebook_name){// Example: https://graph.facebook.com/digimantra$data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));echo $data->likes;}6. 检测图片的主要颜色$i = imagecreatefromjpeg("image.jpg");for ($x=0;$x<imagesx($i);$x++) {for ($y=0;$y<imagesy($i);$y++) {$rgb = imagecolorat($i,$x,$y);$r = ($rgb >> 16) & 0xFF;$g = ($rgb >> & 0xFF;$b = $rgb & 0xFF;$rTotal += $r;$gTotal += $g;$bTotal += $b;$total++;}}$rAverage = round($rTotal/$total);$gAverage = round($gTotal/$total);$bAverage = round($bTotal/$total);7. 获取内存使用信息echo"Initial: ".memory_get_usage()." bytes \n";/* printsInitial: 361400 bytes*/// http://www.baoluowanxiang.com/// let's use up some memoryfor ($i = 0; $i < 100000; $i++) {$array []= md5($i);}// let's remove half of the arrayfor ($i = 0; $i < 100000; $i++) {unset($array[$i]);}echo"Final: ".memory_get_usage()." bytes \n";/* printsFinal: 885912 bytes*/echo"Peak: ".memory_get_peak_usage()." bytes \n";/* printsPeak: 13687072 bytes*/8. 使用 gzcompress() 压缩数据$string ="Lorem ipsum dolor sit amet, consecteturadipiscing elit. Nunc ut elit id mi ultriciesadipiscing. Nulla facilisi. Praesent pulvinar,sapien vel feugiat vestibulum, nulla dui pretium orci,non ultricies elit lacus quis ante. Lorem ipsum dolorsit amet, consectetur adipiscing elit. Aliquampretium ullamcorper urna quis iaculis. Etiam ac massased turpis tempor luctus. Curabitur sed nibh eu elitmollis congue. Praesent ipsum diam, consectetur vitaeornare a, aliquam a nunc. In id magna pellentesquetellus posuere adipiscing. Sed non mi metus, at laciniaaugue. Sed magna nisi, ornare in mollis in, mollissed nunc. Etiam at justo in leo congue mollis.Nullam in neque eget metus hendrerit scelerisqueeu non enim. Ut malesuada lacus eu nulla bibendumid euismod urna sodales. ";$compressed = gzcompress($string);echo "Original size: ". strlen($string)."\n";/* printsOriginal size: 800*/echo "Compressed size: ". strlen($compressed)."\n";/* printsCompressed size: 418*/// getting it back$original = gzuncompress($compressed);9. 使用PHP做Whois检查function whois_query($domain) {// fix the domain name:$domain = strtolower(trim($domain));$domain = preg_replace('/^http:\/\//i', '', $domain);$domain = preg_replace('/^www\./i', '', $domain);$domain = explode('/', $domain);$domain = trim($domain[0]);// split the TLD from domain name$_domain = explode('.', $domain);$lst = count($_domain)-1;$ext = $_domain[$lst];// You find resources and lists// like these on wikipedia://// http://de.wikipedia.org/wiki/Whois//$servers = array("biz" => "whois.neulevel.biz","com" => "whois.internic.net","us" => "whois.nic.us","coop" => "whois.nic.coop","info" => "whois.nic.info","name" => "whois.nic.name","net" => "whois.internic.net","gov" => "whois.nic.gov","edu" => "whois.internic.net","mil" => "rs.internic.net","int" => "whois.iana.org","ac" => "whois.nic.ac","ae" => "whois.uaenic.ae","at" => "whois.ripe.net","au" => "whois.aunic.net","be" => "whois.dns.be","bg" => "whois.ripe.net","br" => "whois.registro.br","bz" => "whois.belizenic.bz","ca" => "whois.cira.ca","cc" => "whois.nic.cc","ch" => "whois.nic.ch","cl" => "whois.nic.cl","cn" => "whois.cnnic.net.cn","cz" => "whois.nic.cz","de" => "whois.nic.de","fr" => "whois.nic.fr","hu" => "whois.nic.hu","ie" => "whois.domainregistry.ie","il" => "whois.isoc.org.il","in" => "whois.ncst.ernet.in","ir" => "whois.nic.ir","mc" => "whois.ripe.net","to" => "whois.tonic.to","tv" => "whois.tv","ru" => "whois.ripn.net","org" => "whois.pir.org","aero" => "whois.information.aero","nl" => "whois.domain-registry.nl");if (!isset($servers[$ext])){die('Error: No matching nic server found!');}$nic_server = $servers[$ext];$output = '';// connect to whois server:if ($conn = fsockopen ($nic_server, 43)) {fputs($conn, $domain."\r\n");while(!feof($conn)) {$output .= fgets($conn,128);}fclose($conn);}else { die('Error: Could not connect to ' . $nic_server . '!'); }return $output;}10. 通过Email发送PHP错误<?php// Our custom error handlerfunction nettuts_error_handler($number, $message, $file, $line, $vars){$email = "<p>An error ($number) occurred on line<strong>$line</strong> and in the <strong>file: $file.</strong><p> $message </p>";$email .= "<pre class="brush:php;toolbar:false">" . print_r($vars, 1) . "
로그인 후 복사
";$headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";// Email the error to someone...error_log($email, 1, [email protected]', $headers);// Make sure that you decide how to respond to errors (on the user's side)// Either echo an error message, or kill the entire project. Up to you...// The code below ensures that we only "die" if the error was more than// just a NOTICE.if ( ($number !== E_NOTICE) && ($number < 2048) ) {die("There was an error. Please try again later.");}}// We should use our custom function to handle errors.set_error_handler('nettuts_error_handler');// Trigger an error... (var doesn't exist)echo$somevarthatdoesnotexist;

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 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 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

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

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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

화웨이 GT3 Pro와 GT4의 차이점은 무엇입니까? 화웨이 GT3 Pro와 GT4의 차이점은 무엇입니까? Dec 29, 2023 pm 02:27 PM

많은 사용자들이 스마트 시계를 선택할 때 Huawei 브랜드를 선택하게 됩니다. 그 중 Huawei GT3pro와 GT4가 가장 인기 있는 선택입니다. 두 제품의 차이점을 궁금해하는 사용자가 많습니다. Huawei GT3pro와 GT4의 차이점은 무엇입니까? 1. 외관 GT4: 46mm와 41mm, 재질은 유리 거울 + 스테인레스 스틸 본체 + 고해상도 섬유 후면 쉘입니다. GT3pro: 46.6mm 및 42.9mm, 재질은 사파이어 유리 + 티타늄 본체/세라믹 본체 + 세라믹 백 쉘입니다. 2. 건강한 GT4: 최신 Huawei Truseen5.5+ 알고리즘을 사용하면 결과가 더 정확해집니다. GT3pro: ECG 심전도, 혈관 및 안전성 추가

대기 연결 상태: 연결 끊김, 이유: NIC 준수 대기 연결 상태: 연결 끊김, 이유: NIC 준수 Feb 19, 2024 pm 03:15 PM

"이벤트 로그 메시지의 연결 상태에는 대기: NIC 준수로 인해 연결이 끊어졌습니다. 이는 시스템이 대기 모드에 있고 네트워크 인터페이스 카드(NIC)의 연결이 끊어졌음을 의미합니다. 이는 일반적으로 네트워크 문제이지만 발생할 수 있습니다. 다음에서는 "대기 연결 끊김의 원인은 무엇입니까?"에 대해 알아보겠습니다. NIC 준수? Windows 이벤트 뷰어에 "ConnectivityStatusinStandby:DisConnected,Reason:NICCompliance" 메시지가 표시되는 경우 이는 NIC 또는 네트워크 인터페이스 컨트롤러에 문제가 있을 수 있음을 나타냅니다. 이런 상황은 대개

PHP 치명적인 오류에 대한 해결 방법: 정의되지 않은 메소드 PDO::prepare() 호출 PHP 치명적인 오류에 대한 해결 방법: 정의되지 않은 메소드 PDO::prepare() 호출 Jun 22, 2023 pm 06:40 PM

PHP는 오랫동안 사용되어 온 인기 있는 웹 개발 언어입니다. PHP에 통합된 PDO(PHP 데이터 개체) 클래스는 웹 애플리케이션 개발 중에 데이터베이스와 상호 작용하는 일반적인 방법입니다. 그러나 일부 PHP 개발자가 자주 직면하는 문제는 PDO 클래스를 사용하여 데이터베이스와 상호 작용할 때 다음과 같은 오류가 발생한다는 것입니다. PHPFatalerror:CalltoundefinemethodPDO::prep

Vue 애플리케이션에서 axios를 사용할 때 'Uncaught (in promise) Error: Request failed with status code 500'이 발생하면 어떻게 해야 합니까? Vue 애플리케이션에서 axios를 사용할 때 'Uncaught (in promise) Error: Request failed with status code 500'이 발생하면 어떻게 해야 합니까? Jun 24, 2023 pm 05:33 PM

Vue 애플리케이션에서 axios를 사용하는 것은 매우 일반적입니다. axios는 브라우저와 Node.js에서 사용할 수 있는 Promise 기반 HTTP 클라이언트입니다. 개발 과정에서 "Uncaught(inpromise)Error: Requestfailedwithstatuscode500"이라는 오류 메시지가 나타나는 경우가 있는데, 개발자 입장에서는 이 오류 메시지를 이해하고 해결하기 어려울 수 있습니다. 이 기사에서는 이에 대해 알아볼 것입니다.

C++ 코드에서 '오류: 불완전한 유형은 허용되지 않습니다' 문제 해결 C++ 코드에서 '오류: 불완전한 유형은 허용되지 않습니다' 문제 해결 Aug 26, 2023 pm 08:54 PM

C++ 코드의 "error:incompletetypeisnotallowed" 문제를 해결하십시오. C++ 프로그래밍 프로세스 중에 흔히 발생하는 오류 중 하나는 "error:incompletetypeisnotallowed"입니다. 이 오류는 일반적으로 불완전한 유형에서 작업할 때 발생합니다. 이 문서에서는 이 오류의 원인을 설명하고 몇 가지 해결 방법을 제공합니다. 첫째로, 나는

0271: 실시간 시계 오류로 인해 컴퓨터가 켜지지 않으면 어떻게 해야 하나요? 0271: 실시간 시계 오류로 인해 컴퓨터가 켜지지 않으면 어떻게 해야 하나요? Mar 13, 2023 am 11:30 AM

부팅할 수 없는 "0271: 실시간 시계 오류"에 대한 해결 방법: 1. F1을 누르고 나타나는 인터페이스에서 옵션 표시줄을 세 번째 항목 "날짜/시간"으로 이동합니다. 2. 시스템 시간을 현재 시간으로 수동으로 변경합니다. 3. F10을 누르고 팝업 대화 상자에서 예를 선택합니다. 4. 정상적으로 부팅하려면 노트북을 다시 엽니다.

C++ 코드에서 '오류: '데이터 유형' 이전에 예상되는 초기화 프로그램' 문제 해결 C++ 코드에서 '오류: '데이터 유형' 이전에 예상되는 초기화 프로그램' 문제 해결 Aug 25, 2023 pm 01:24 PM

C++ 코드의 "error:expectedinitializerbefore'datatype'" 문제를 해결하세요. C++ 프로그래밍에서 코드를 작성할 때 가끔 컴파일 오류가 발생하는 경우가 있습니다. 일반적인 오류 중 하나는 "error:expectedinitializerbefore'datatype'"입니다. 이 오류는 일반적으로 변수 선언이나 함수 정의에서 발생하며 프로그램이 올바르게 컴파일되지 않거나

PHP 경고 해결 방법: fopen(): 스트림을 열지 못했습니다: 해당 파일이나 디렉터리가 없습니다. PHP 경고 해결 방법: fopen(): 스트림을 열지 못했습니다: 해당 파일이나 디렉터리가 없습니다. Aug 19, 2023 am 10:44 AM

PHPWarning:fopen():failedtoopenstream:Nosuchfileordirectory 해결 방법 PHP 개발을 사용하는 과정에서 "PHPWarning:fopen():failedtoopenstream:Nosuchfileordirectory"와 같은 파일 작업 문제가 종종 발생합니다.

See all articles