Today: Yesterday: Total: Online:
カテゴリー
その他
  • RSS1.0
  • RSS2.0
  • atom0.3
  • valid XHTML1.0
  • valid CSS2
  • Credit
RSSリーダーで購読する | この日記のはてなブックマーク数 | プロフィール
コメントが一番多い記事(233コメント):人の心理の裏をかくホームページ集客術:リピータになってもらうためには
ツイートが一番多い記事(94ツイート):ちょっと待て!twitterやfacebookに子供の写真を掲載する親達への警告
いいねが一番多い記事(574いいね):facebookスパムに要注意。なりすましの見分け方とアカウント乗っ取りの手口(2013年度版)

カテゴリー » PHP April 02, 2007

ファイルの存在チェック(ローカル・リモートファイル) ID:1175505141


file_existsを使う。
ただし、ローカルのファイルしかできないので、リモートファイルでファイル有無のチェックを行う場合は、
HTTPリクエストを使う。


//リモートファイルのリンク切れチェックを行う。trueなら存在。falseならリンク切れ
function linkCheck($url){
$head = get_http_header($url);
$response = $head['Status-Code'];
//echo substr($response, 0, 1);
if (substr($response, 0, 1) == '1' || substr($response, 0, 1) == '2') {
return true;
} else {
return false;
}
}

//-------------------------------------------------------------------------
// array get_http_header( string URI )
// URIがHTTPプロトコルだった場合、そのURIにHEADリクエストを行います。
// 返り値にはHTTP-Version、Status-Code、Reason-Phraseが必ず含まれ、それ以外
// にサーバが返した情報(index: value)が含まれます。
// Status-Codeが9xxの場合、それはホストが存在しない場合などHTTPリクエストが
// 正常に行われなかったことを意味します。
//-------------------------------------------------------------------------
function get_http_header( $target ) {

// URIから各情報を取得
$info = parse_url( $target );

$scheme = $info['scheme'];
$host = $info['host'];
$port = $info['port'];
$path = $info['path'];
// ポートが空の時はデフォルトの80にします。
if( ! $port ) {
$port = 80;
}

// リクエストフィールドを制作。
$msg_req = "HEAD " . $path . " HTTP/1.0\r\n";
$msg_req .= "Host: $host\r\n";
$msg_req .=
"User-Agent: H2C/1.0\r\n";
$msg_req .= "\r\n";

// スキームがHTTPの時のみ実行
if ( $scheme == 'http' ) {

$status = array();

// 指定ホストに接続。
if ( $handle = @fsockopen( $host, $port, $errno, $errstr, 1 ) ) {

fputs ( $handle, $msg_req );

if ( socket_set_timeout( $handle, 3 ) ) {

$line = 0;
while( ! feof( $handle) ) {

// 1行めはステータスライン
if( $line == 0 ) {
$temp_stat =
explode( ' ', fgets( $handle, 4096 ) );
$status['HTTP-Version'] =
array_shift( $temp_stat );
$status['Status-Code'] = array_shift( $temp_stat );
$status['Reason-Phrase'] =
implode( ' ', $temp_stat );

// 2行目以降はコロンで分割してそれぞれ代入
} else {
$temp_stat =
explode( ':', fgets( $handle, 4096 ) );
$name = array_shift( $temp_stat );
// 通常:の後に1文字半角スペースがあるので除去
$status[ $name ] =
substr( implode( ':', $temp_stat ), 1);
}
$line++;
}

} else {
$status['HTTP-Version'] = '---';
$status['Status-Code'] = '902';
$status['Reason-Phrase'] = "No Response";
}

fclose ( $handle );

} else {
$status['HTTP-Version'] = '---';
$status['Status-Code'] = '901';
$status['Reason-Phrase'] = "Unable To Connect";
}


} else {
$status['HTTP-Version'] = '---';
$status['Status-Code'] = '903';
$status['Reason-Phrase'] = "Not HTTP Request";
}

return $status;
}
?>



参考
http://www.arielworks.net/articles/2003/1220a
1 / 2| 次のページ »
— posted by midilin @ 06:12PM
[コメントが多かった順の記事]
人の心理の裏をかくホームページ集客術:リピータになってもらうためには(233)
ホームページ心理学第2弾「メールの書きだしとホームページ運営・集客の関係」(76)
娘が生まれた(69)
ゲームと言えば、何を思い出す? (50)
Microsoftからアクセス (30)
「目標の立て方」と「努力」と「実行力」(26)