当使用PHP进行开发的时候,如果你自己收 藏 了一些非常有用的方法或者代码片段,那么将会给你的开发工作带来极大的便利。今天我们将介绍10个超级好用的PHP代码片段,希望大家能够喜欢!
1. 使用textmagic API发送消息
可能有的时候,你需要发送一些短信给你的客户,那么你绝对应该看看textMagic。它提供了非常简单的API来实现这个功能。但是不是免费的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 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。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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( ‘{
}i’ , $content , $regs ) ) {
$city = $regs [1];
}
if ( preg_match( ‘{
}i’ , $content , $regs ) ) {
$state = $regs [1];
}
if ( $city != ” && $state != ” ){
1本文来#源gaodai$ma#com搞$代*码*网
搞代gaodaima码
$location = $city . ‘, ‘ . $state ;
return $location ;
} else {
return $default ;
}
}