Skip to content

Instantly share code, notes, and snippets.

@mamemomonga
Created October 15, 2015 10:29
Show Gist options
  • Select an option

  • Save mamemomonga/d66ceb9460d92f381ca5 to your computer and use it in GitHub Desktop.

Select an option

Save mamemomonga/d66ceb9460d92f381ca5 to your computer and use it in GitHub Desktop.
HEADで存在をチェックしてGETでファイルを取得
<?php
class CheckAndGetURL {
private $url;
// HEADのレスポンスで検索するヘッダの正規表現
private $headers_match=[
"^HTTP/1\.1 200 OK$",
"^Content-Type: application/octet-stream$",
"^Content-Type: application/zip$",
"^Content-Type: text/html",
];
// HEADのレスポンスで検索してマッチした数。この数ならOK
private $headers_match_count=2;
// コンストラクタ
public function CheckAndGetURL($url) {
$this->url=$url;
}
// 存在チェック
public function is_exist(){
$context=stream_context_create([
'http' => [
'method' => 'HEAD',
'timeout' => 5,
]
]);
@file_get_contents( $this->url, false, $context );
// デバッグ用
// var_dump($http_response_header);
$count=0;
foreach( $this->headers_match as $hrex ) {
if( preg_grep( "!".$hrex."!i", $http_response_header ) ) {
$count++;
}
}
return ( $count == $this->headers_match_count ) ? true : false;
}
// ファイル取得
public function get_file($filename=""){
if($filename=="") {
$filename=basename($this->url);
}
$context=stream_context_create([
'http' => [
'method' => 'GET',
'timeout' => 5,
]
]);
$fpin =fopen( $this->url, 'r', false, $context );
$fpout=fopen( $filename, 'w' );
while( !feof($fpin) ) {
fwrite( $fpout, fread( $fpin, 8192 ) );
}
return $filename;
}
}
$cag=new CheckAndGetURL( 'http://www.post.japanpost.jp/zipcode/dl/kogaki/zip/26kyouto.zip' );
// $cag=new CheckAndGetURL( 'http://localhost:3000/hello.txt' );
if( $cag->is_exist() ) {
echo "隊長!ファイル発見しました!\n";
echo "ファイルを取得するであります!\n";
$filename=$cag->get_file();
echo "隊長! ".$filename." というファイルを取得したであります!\n";
} else {
echo "隊長!取得出来るファイルがないか何かのエラーであります!\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment