便利で使えるPHPのコードスニペットあれこれ。(リターンズ) | φ(..)メモとして残しておこう…

便利で使えるPHPのコードスニペットあれこれ。(リターンズ)



任意のWebページのソースコードを表示する


$lines = file('http://google.com/');
foreach ($lines as $line_num => $line) {
echo "Line #{$line_num} : " . htmlspecialchars($line) . "
\n";
}




メモリの使用状況に関する情報を取得



echo "Initial: ".memory_get_usage()." bytes \n";
/* 結果
Initial: ****** 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";
/* 結果
Final: 885912 bytes
*/

echo "Peak: ".memory_get_peak_usage()." bytes \n";
/* 結果
Peak: 13687072 bytes
*/




gzcompress()を使用してデータを圧縮



$string ="
ああああああああああ
ああああああああああ
ああああああああああ
ああああああああああ
ああああああああああ
ああああああああああ
ああああああああああ
ああああああああああ
ああああああああああ
ああああああああああ
ああああああああああ
ああああああああああ
ああああああああああ
ああああああああああ
ああああああああああ
ああああああああああ
ああああああああああ
ああああああああああ
";

$compressed = gzcompress($string);

//-------------

echo "Original size: ". strlen($string)."\n";
echo "Compressed size: ". strlen($compressed)."\n";

//圧縮された文字列
echo $compressed;
//解凍
echo gzuncompress($compressed);

// 解凍
$original = gzuncompress($compressed);




PHPのエラーメッセージを表示させずにメールで受け取る
(ユーザ定義のエラーハンドラ関数)



function nettuts_error_handler($number, $message, $file, $line, $vars){
$email = "

An error ($number) occurred on line
$line and in the file: $file.

$message

";

$email .= "
" . print_r($vars, 1) . "
";

$headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

error_log($email, 1, 'mail@example.com', $headers);

//画面上に表示する文章
if ( ($number !== E_NOTICE) && ($number < 2048) ) {
die("エラーが発生しました。後でもう一度やり直してください。");
}
}

// set_error_handler()で関数をセット
set_error_handler('nettuts_error_handler');