ホームページ >バックエンド開発 >PHPチュートリアル >非常に実用的な PHP コード スニペットの推奨事項

非常に実用的な PHP コード スニペットの推奨事項

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBオリジナル
2016-06-13 12:16:591068ブラウズ

おすすめの超実践的なPHPコードスニペット

PHPを使って開発する際に、非常に便利なメソッドやコードスニペットを集めておくと、開発作業に大きな利便性をもたらします。今日は、とても使いやすい PHP コード スニペットを 10 個紹介します。気に入っていただければ幸いです。

1. textmagic API を使用してメッセージを送信します

顧客にテキスト メッセージを送信する必要がある場合は、textMagic をぜひ検討してください。この機能を実装するための非常にシンプルな API が提供されます。しかし、無料ではありません。

1
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 )
234
567
8
9
10
11
121314
151617
// TextMagic PHP lib を含めます
require('textmagic -sms-api-php/TextMagicAPI.php');
// ユーザー名とパスワードの情報を設定します<div class="linenumber5index4 alt2"> <code class="php variable ">$username = 'myusername';コード コード><div class="linenumber6index5 alt1"> <code class="php variable">$password = 'mypassword';
// TM の新しいインスタンスを作成します
$router = 新しい TextMagicAPI(配列(
コード ><code class="php string">'ユーザー名' => $username,
'パスワード ' => $password
));
// テキスト メッセージを '999-123-4567' に送信します<div class="linenumber15index14 alt2"> <code class="php variable">$result = $router->send(「ウェークアップ!」, array(9991234567), true);
// 結果: 結果は次のとおりです: Array ( [messages] => Array ( [19896128] => 9991234567 ) [sent_text] => 起きてください! [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(<code class="php variable">$ip) {
        $default = 'UNKNOWN';
        if (!is_string(<code class="php variable">$ip) || strlen(<code class="php variable">$ip) <code class="php variable">$ip == '127.0.0.1' || <code class="php variable">$ip == 'localhost')
            <code class="php variable">$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(<code class="php variable">$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 : ([^}i'</li>, $content, $regs) )  {
            $city = $regs[1];
        }
        if ( preg_match('{<li>State/Province : ([^}i'</li>, $content, $regs) )  {
            $state = $regs[1];
        }
        if( $city!='' && $state!='' ){
          $location = $city . ', ' . $state;
          return $location;
        }else{
          return $default;
        }
    }

3. 任意の Web ページのソース コードを表示します

任意の Web ページのソース コードを行番号付きで表示しますか?これは簡単なコード スニペットです。2 行目の URL を変更するだけです。

1
1
2
3
4
5
6
<?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";
}
2
3
4

5
6

<?php // ソースコードを表示<div class="linenumber2index1alt1"> <code class="php variable">$lines = file('http://google.com/');

foreach ($lines as $line_num => $line<code class="php plain">) {
// 各行をループし、行番号を先頭に追加します
1
2
3
4
5
if ($_SERVER['HTTPS'] != "on") {
    echo "This is not HTTPS";
}else{
    echo "This is HTTPS";
}
echo "Line #<b>{$line_num}</b> : " htmlspecialchars($line) "<br> n";
}
4. サーバーが HTTPS 接続であるかどうかを判断するには コードの実行環境はHTTPSサーバーですか?以下のコードはこれを実現するのに役立ちます。非常に簡単です。 if ($_SERVER[ 'HTTPS'] != "on" code> code>) {
echo "これは HTTPS ではありません";
}else{
echo "これは HTTPS です";
}
1
234
5

5. テキスト内に Facebook ファンの数を表示します

Facebook に何人のファンがいるかを確認したいですか?以下のコードはこれを実現するのに役立ちます。

関数 fb_fan_count($facebook_name ){
// 例: https:// graph.facebook.com/digimantra
$data <code class="php plain">= json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));
echo $data->likes;
}
1
1
2
3
4
5
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;
}
234
5

6. 画像のメインカラーを決定する

次のコードは非常に実用的で、任意の画像を分析できます。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<code class="php variable">$i = imagecreatefromjpeg("image.jpg");
for ($x=0;$x<imagesx><code class="php variable">$i);$x ) {
    for ($y=0;$y<imagesy><code class="php variable">$i );$y ) {
        $rgb = imagecolorat(<code class="php variable">$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 の使用量を知る必要があります。このコード スニペットは、メモリ使用量を理解し、初期、最終、ピークの使用量を出力するのに役立ちます。

1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
echo "Initial: ".memory_get_usage()." bytes n";
/* prints
Initial: 361400 bytes
*/
 
// let's use up some memory
for (<code class="php variable">$i = 0; <code class="php variable">$i <code class="php variable">$i ) {
    $array []= md5(<code class="php variable">$i);
}
 
// let's remove half of the array
for (<code class="php variable">$i = 0; <code class="php variable">$i <code class="php variable">$i ) {
    unset($array[<code class="php variable">$i]);
}
 
echo "Final: ".memory_get_usage()." bytes n";
/* prints
Final: 885912 bytes
*/
 
echo "Peak: ".memory_get_peak_usage()." bytes n";
/* prints
Peak: 13687072 bytes
*/
234
567
8
9
10
11
121314
15161718
19
20
21
222324
echo "Initial: ".memory_get_usage()." bytes n";
/* 出力
初期: 361400バイト
*/ code><div class="linenumber5index4alt2"><divclass><code class="php comments">// メモリを使い切ってみましょう
for ($i = 0; <code class="php variable">$i <code class="php variable">$i) {
$array []= md5($i);
}<div class="linenumber10index9alt1"><divclass><code class="php comments">// 配列の半分を削除しましょう code><div class="linenumber12index11alt1"> <code class="php キーワード">for ($i = 0; <code class="php variable">$i &lt ; 100000; $i ) {
unset($array[<code class="php variable">$i]);
}
echo "Final: ".memory_get_usage()." bytes n";
/* prints
最終: 885912 バイト<div class="linenumber19index18alt2"> <code class="php comments">*/
echo <code class="php string">"ピーク: ".memory_get_peak_usage()." バイト n";
/* prints<div class="linenumber23index22alt2"><codeclass comments>ピーク: 13687072 バイト<div class="linenumber24index23alt1"><code class="php comments">*/

8. gzcompress() を使用してデータを圧縮します。

非常に長い文字列を使用する場合は、gzcompress() メソッドを使用して文字列を圧縮できます。解凍するには、gzuncompress()を使用します。コードは次のとおりです。

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
$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 を使用してみてはいかがでしょうか。以下のコードは誰でも役立ちます。

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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."rn");
        while(!feof($conn)) {
            $output .= fgets($conn,128);
         }
        fclose($conn);
    }
    else { die('Error: Could not connect to ' . $nic_server . '!'); }
    return $output;
}

10. PHP エラーを表示せずに電子メールを送信します。

ページに PHP エラーを表示したくない場合は、電子メールでエラー情報を取得することもできます。以下のコードはこれを実現するのに役立ちます。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。