推荐10个非常实用的PHP代码片段
推荐10个非常实用的PHP代码片段
当使用PHP进行开发的时候,如果你自己收藏 了一些非常有用的方法或者代码片段,那么将会给你的开发工作带来极大的便利。今天我们将介绍10个超级好用的PHP代码片段,希望大家能够喜欢!1. 使用textmagic API发送消息
可能有的时候,你需要发送一些短信给你的客户,那么你绝对应该看看textMagic。它提供了非常简单的API来实现这个功能。但是不是免费的。
// Include the TextMagic PHP lib require('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判断来源
这是一个非常实用的代码片段,可以帮助你通过IP来判断访客来源。下面的方法通过接收一个参数,然后返回IP所在地点。如果没有找到,则返回UNKNOWN。
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. 显示任何网页的源代码
是不是想显示带有行号的任何网页的源代码?这里有个简单的代码片段,你只需要修改第二行的url即可
<?php // display source code $lines = file('http://google.com/'); foreach ($lines as $line_num => $line) { // loop thru each line and prepend line numbers echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>\n"; } ?>
4. 判断服务器是否是HTTPS连接
需要判断代码运行环境是否是HTTPS服务器?下面的代码可以帮助你实现,非常简单!
if ($_SERVER['HTTPS'] != "on") { echo "This is not HTTPS"; }else{ echo "This is HTTPS"; }
5. 在文本中显示Facebook 粉丝数
想看看你在facebook有多少粉丝么?下面代码可以帮助你实现。
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. 了解你的内存使用情况
为了优化你的脚本,你需要了解服务器上的RAM使用情况。这个代码片段将帮助你了解内存使用,并且打印初始、最终以及峰值使用情况。
echo "Initial: ".memory_get_usage()." bytes \n"; /* prints Initial: 361400 bytes */ // let's use up some memory for ($i = 0; $i < 100000; $i++) { $array []= md5($i); } // let's remove half of the array for ($i = 0; $i < 100000; $i++) { unset($array[$i]); } echo "Final: ".memory_get_usage()." bytes \n"; /* prints Final: 885912 bytes */ echo "Peak: ".memory_get_peak_usage()." bytes \n"; /* prints Peak: 13687072 bytes */
8. 使用gzcompress()压缩数据
当使用很长的string时,可以通过gzcompress()方法,将strings压缩。解压缩使用gzuncompress()即可。代码如下。
$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ut elit id mi ultricies adipiscing. Nulla facilisi. Praesent pulvinar, sapien vel feugiat vestibulum, nulla dui pretium orci, non ultricies elit lacus quis ante. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam pretium ullamcorper urna quis iaculis. Etiam ac massa sed turpis tempor luctus. Curabitur sed nibh eu elit mollis congue. Praesent ipsum diam, consectetur vitae ornare a, aliquam a nunc. In id magna pellentesque tellus posuere adipiscing. Sed non mi metus, at lacinia augue. Sed magna nisi, ornare in mollis in, mollis sed nunc. Etiam at justo in leo congue mollis. Nullam in neque eget metus hendrerit scelerisque eu non enim. Ut malesuada lacus eu nulla bibendum id euismod urna sodales. "; $compressed = gzcompress($string); echo "Original size: ". strlen($string)."\n"; /* prints Original size: 800 */ echo "Compressed size: ". strlen($compressed)."\n"; /* prints Compressed size: 418 */ // getting it back $original = gzuncompress($compressed);
9. 使用PHP执行Whois查询
如果你需要得到指定域名的whois信息,为什么不使用PHP呢?下面的代码可以帮助大家。
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. 不显示PHP错误而发送电子邮件取代之
如果你不想在页面中显示PHP错误,也可以通过email来获取错误信息。下面的代码可以帮助你实现。
<?php // Our custom error handler function 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="code">" . print_r($vars, 1) . "

핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

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

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

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

뜨거운 주제











일부 사용자는 장치를 설치할 때 오류 코드 28을 표시하는 오류가 발생했습니다. 실제로 이는 주로 드라이버 때문입니다. win7 드라이버 코드 28의 문제만 해결하면 됩니다. 수행해야 할 작업을 살펴보겠습니다. 그것. win7 드라이버 코드 28로 수행할 작업: 먼저 화면 왼쪽 하단에 있는 시작 메뉴를 클릭해야 합니다. 그런 다음 팝업 메뉴에서 "제어판" 옵션을 찾아 클릭하세요. 이 옵션은 일반적으로 메뉴 하단이나 그 근처에 있습니다. 클릭하면 시스템이 자동으로 제어판 인터페이스를 엽니다. 제어판에서는 다양한 시스템 설정 및 관리 작업을 수행할 수 있습니다. 이것이 향수 청소 수준의 첫 번째 단계입니다. 도움이 되기를 바랍니다. 그런 다음 계속해서 시스템에 들어가야 합니다.

블루 스크린 코드 0x0000001로 수행할 작업 블루 스크린 오류는 컴퓨터 시스템이나 하드웨어에 문제가 있을 때 나타나는 경고 메커니즘입니다. 코드 0x0000001은 일반적으로 하드웨어 또는 드라이버 오류를 나타냅니다. 사용자가 컴퓨터를 사용하는 동안 갑자기 블루 스크린 오류가 발생하면 당황하고 당황할 수 있습니다. 다행히도 대부분의 블루 스크린 오류는 몇 가지 간단한 단계를 통해 문제를 해결하고 처리할 수 있습니다. 이 기사에서는 독자들에게 블루 스크린 오류 코드 0x0000001을 해결하는 몇 가지 방법을 소개합니다. 먼저, 블루 스크린 오류가 발생하면 다시 시작해 보세요.

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

win10 시스템은 매우 뛰어난 지능 시스템으로 사용자에게 최고의 사용자 경험을 제공할 수 있습니다. 정상적인 상황에서는 사용자의 win10 시스템 컴퓨터에 아무런 문제가 없습니다! 그러나 우수한 컴퓨터에서는 다양한 오류가 발생하는 것은 불가피합니다. 최근 친구들은 win10 시스템에서 블루 스크린이 자주 발생한다고 보고했습니다. 오늘 편집자는 Windows 10 컴퓨터에서 자주 블루 스크린을 발생시키는 다양한 코드에 대한 솔루션을 제공합니다. 매번 다른 코드로 자주 나타나는 컴퓨터 블루 스크린에 대한 해결 방법: 다양한 오류 코드의 원인 및 해결 방법 제안 1. 0×000000116 오류의 원인: 그래픽 카드 드라이버가 호환되지 않는 것이어야 합니다. 해결책: 원래 제조업체의 드라이버를 교체하는 것이 좋습니다. 2,

종료 코드 0xc000007b 컴퓨터를 사용하는 동안 때때로 다양한 문제와 오류 코드가 발생할 수 있습니다. 그 중 종료코드가 가장 충격적이며, 특히 종료코드 0xc000007b가 가장 충격적이다. 이 코드는 애플리케이션이 제대로 시작되지 않아 사용자에게 불편을 초래함을 나타냅니다. 먼저 종료코드 0xc000007b의 의미를 알아보겠습니다. 이 코드는 32비트 응용 프로그램이 64비트 운영 체제에서 실행을 시도할 때 일반적으로 발생하는 Windows 운영 체제 오류 코드입니다. 그래야 한다는 뜻이다

장치를 원격으로 프로그래밍해야 하는 경우 이 문서가 도움이 될 것입니다. 우리는 모든 장치 프로그래밍을 위한 최고의 GE 범용 원격 코드를 공유할 것입니다. GE 리모콘이란 무엇입니까? GEUniversalRemote는 스마트 TV, LG, Vizio, Sony, Blu-ray, DVD, DVR, Roku, AppleTV, 스트리밍 미디어 플레이어 등과 같은 여러 장치를 제어하는 데 사용할 수 있는 리모컨입니다. GEUniversal 리모컨은 다양한 기능과 기능을 갖춘 다양한 모델로 제공됩니다. GEUniversalRemote는 최대 4개의 장치를 제어할 수 있습니다. 모든 장치에서 프로그래밍할 수 있는 최고의 범용 원격 코드 GE 리모컨에는 다양한 장치에서 작동할 수 있는 코드 세트가 함께 제공됩니다. 당신은 할 수있다

블루 스크린은 시스템을 사용할 때 자주 발생하는 문제입니다. 오류 코드에 따라 다양한 원인과 해결 방법이 있습니다. 예를 들어 stop: 0x0000007f 문제가 발생하면 하드웨어 또는 소프트웨어 오류일 수 있습니다. 편집기를 따라 해결책을 찾아보겠습니다. 0x000000c5 블루 스크린 코드 이유: 답변: 메모리, CPU 및 그래픽 카드가 갑자기 오버클럭되었거나 소프트웨어가 잘못 실행되고 있습니다. 해결 방법 1: 1. 부팅할 때 F8을 계속 눌러 들어가고 안전 모드를 선택한 다음 Enter를 눌러 들어갑니다. 2. 안전모드 진입 후 win+r을 눌러 실행창을 열고 cmd를 입력한 후 Enter를 누릅니다. 3. 명령 프롬프트 창에서 "chkdsk /f /r"을 입력하고 Enter를 누른 다음 y 키를 누릅니다. 4.

0x000000d1 블루 스크린 코드는 무엇을 의미합니까? 최근 몇 년 동안 컴퓨터의 대중화와 인터넷의 급속한 발전으로 인해 운영 체제의 안정성 및 보안 문제가 점점 더 부각되고 있습니다. 일반적인 문제는 블루 스크린 오류이며, 코드 0x000000d1이 그 중 하나입니다. 블루 스크린 오류 또는 "죽음의 블루 스크린"은 컴퓨터에 심각한 시스템 오류가 발생할 때 발생하는 상태입니다. 시스템이 오류로부터 복구할 수 없는 경우 Windows 운영 체제는 화면에 오류 코드와 함께 블루 스크린을 표시합니다. 이러한 오류 코드
