Last active
August 7, 2017 22:30
-
-
Save shimabox/d6ca86daab25f9cf78c473cfbab8b700 to your computer and use it in GitHub Desktop.
URLを渡すとヘッダー情報を見てステータスを返す
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* URLのステータスを返す | |
* | |
* <code> | |
* $ret = getUrlStatus($url); | |
* | |
* $ret->url; // string URL<br> | |
* $ret->reachedUrl; // string 最後に到達したURL<br> | |
* $ret->isValid; // bool 有効なURLか<br> | |
* $ret->redirectedUrls; // array リダイレクトがあった際のURL<br> | |
* $ret->redirectedCode; // array リダイレクト時のHTTPステータスコード<br> | |
* $ret->code; // int 最終的なHTTPステータスコード<br> | |
* $ret->is200; // bool HTTPステータスコードが200かどうか<br> | |
* $ret->is403; // bool HTTPステータスコードが403かどうか<br> | |
* $ret->is404; // bool HTTPステータスコードが404かどうか<br> | |
* $ret->is500; // bool HTTPステータスコードが500かどうか<br> | |
* </code> | |
* | |
* @param string $url | |
* @param array $streamContextOptions stream_context_set_defaultを呼びます(GETリクエスト以外とか指定したい場合など) | |
* @return stdClass | |
* @see http://jp2.php.net/manual/ja/function.get-headers.php#119497 | |
*/ | |
function getUrlStatus($url, array $streamContextOptions = null) | |
{ | |
$ret = new stdClass(); | |
$ret->url = $url; | |
$ret->reachedUrl = ''; | |
$ret->isValid = false; | |
$ret->redirectedUrls = []; | |
$ret->redirectedCode = []; | |
$ret->code = 0; | |
$ret->is200 = false; | |
$ret->is403 = false; | |
$ret->is404 = false; | |
$ret->is500 = false; | |
if ($streamContextOptions !== null) { | |
stream_context_set_default($streamContextOptions); | |
} | |
$headers = @get_headers($url); | |
if ($headers === false) { | |
return $ret; | |
} | |
// redirectedCode と redirectedUrlsは対になるようにしたいので | |
// 一旦redirectedCodeを格納するものを用意する | |
$_redirectedCode = []; | |
foreach($headers as $header) { | |
// リダイレクトされたURL | |
if (preg_match('/\ALocation:\s(http.+)\z/', $header, $m)) { | |
$ret->redirectedUrls[] = $m[1]; | |
continue; | |
} | |
// HTTPステータスコード | |
if (preg_match('/\AHTTP.+\s(\d\d\d)\s/', $header, $m)) { | |
$code = (int)$m[1]; | |
$_redirectedCode[] = $code; | |
$ret->code = $code; | |
$ret->isValid = true; | |
} | |
} | |
$redirectedCnt = count($ret->redirectedUrls); | |
if ($redirectedCnt > 0) { | |
$ret->reachedUrl = $ret->redirectedUrls[$redirectedCnt - 1]; | |
} else { | |
$ret->reachedUrl = $url; | |
} | |
// redirectedCodeとredirectedUrlsの共通項を取得(redirectedCodeとredirectedUrlsは対になるように) | |
$ret->redirectedCode = array_intersect_key($_redirectedCode, $ret->redirectedUrls); | |
$ret->is200 = $ret->code === 200; | |
$ret->is403 = $ret->code === 403; | |
$ret->is404 = $ret->code === 404; | |
$ret->is500 = $ret->code === 500; | |
return $ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment