โห Share กันใหญ่เลย ขอบ้างๆ
การทำ Compatibility Functionคงจะเคยเจอกันใช่มั้ยครับ function ใน php5 แต่ไม่สามารถเอามาใช้ใน php4 ทีนี้พอเปลี่ยน host ที เอาล่ะสิ ยุ่งเลยได้ ลองมาดูวิธีแก้กัน
if (!function_exists('get_headers'))
{
function get_headers($url,$format=0)
{
$url_info = parse_url($url);
$port = isset($url_info['port']) ? $url_info['port'] : 80;
$fp = @fsockopen($url_info['host'], $port, $errno, $errstr, 30);
if ($fp)
{
if(!$url_info['path'])
$url_info['path'] = "/";
if ($url_info['path'] && !$url_info['host'])
{
$url_info['host'] = $url_info['path'];
$url_info['path'] = "/";
}
if ($url_info['host'][(strlen($url_info['host'])-1)] == "/" )
$url_info['host'][(strlen($url_info['host'])-1)] = "";
if (!$url_array[scheme])
$url_array[scheme] = "http"; //we always use http links
$head = "HEAD ".@$url_info['path'];
if ($url_info['query'] )
$head .= "?".@$url_info['query'];
//print_r($url_info);
$head .= " HTTP/1.0\r\nHost: ".@$url_info['host']."\r\n\r\n";
//echo $head;
fputs($fp, $head);
while (!feof($fp))
{
if ($header=trim(fgets($fp, 1024)))
{
if ($format == 1)
{
$h2 = explode(':',$header);
if($h2[0] == $header)
$headers['status'] = $header;
else
$headers[strtolower($h2[0])] = trim($h2[1]);
}
else
$headers[] = $header;
}
}
return $headers;
}
else
return false;
}
}
ในตัวอย่างนี้ผมลองกับคำสั่ง get_headers ซึ่งมีใน php5 พอเปลี่ยนมาใช้ host ที่ไม่มีคำสั่งนี้ก็แค่ไปเช็คมันก่อนด้วย
function_exists จากนั้นเขียน function เลียนแบบมันเข้าไปเองเลยครับ
ส่วนคำสั่ง
get_headers คือคำสั่งเอาไว้เช็ค header ของ external file โดยไม่ต้องไปทำการอ่าน binary คืออ่าน header แล้วก็จบเลย มีประโยชน์ในการเช็ค ข้อมูลจาก link ภายนอกครับ
ผมเห็นหลายคน เวลาจะเช็ค ว่าไฟล์มีหรือไม่มี บางทียังเขียนแบบนี้อยู่เลย
if (!fopen('
http://www.jquerytips.com 
', 'r')) exit;
ซึ่งมัน แดก performance ขั้นนรกเลยครับ ลองเปลี่ยนมาเป็น
$headers = get_headers($path);
if (!preg_match('/200/', $headers[0])) exit;
จะเห็นความแตกต่าง แบบ สวรรค์กับ นรกเลยครับ
ส่วนค่า return อื่นๆก็มีประโยชน์ไม่แพ้กัน
Array
(
// check server status
// check date
[1] => Date: Sat, 29 May 2004 12:28:13 GMT
// check server
[2] => Server: Apache/1.3.27 (Unix) (Red-Hat/Linux)
// check last modify
[3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
// check e-tag (เอาไว้เช็คแทน md5_file ได้ดีมาก)
[4] => ETag: "3f80f-1b6-3e1cb03b"
// check accept
[5] => Accept-Ranges: bytes
// check length (เอาไว้ทำ streaming download)
[6] => Content-Length: 438
[7] => Connection: close
[8] => Content-Type: text/html
)
ลองดูกันนะครับ ^^