PHP를 사용하여 원격 파일이 존재하는지 어떻게 확인할 수 있습니까?
내가 찾을 수있는 최선의 if
fclose
fopen
유형은 페이지로드를 정말 느리게 만듭니다.
기본적으로 내가하려는 것은 다음과 같습니다. 웹 사이트 목록이 있고 그 옆에 파비콘을 표시하고 싶습니다. 그러나 사이트에없는 경우 깨진 이미지를 표시하는 대신 다른 이미지로 교체하고 싶습니다.
curl에 CURLOPT_NOBODY를 통해 HTTP HEAD 메소드를 사용하도록 지시 할 수 있습니다.
다소간
$ch = curl_init("http://www.example.com/favicon.ico");
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// $retcode >= 400 -> not found, $retcode = 200, found.
curl_close($ch);
어쨌든 TCP 연결 설정 및 종료가 아닌 HTTP 전송 비용 만 절약됩니다. 그리고 파비콘이 작기 때문에 많은 개선을 보지 못할 수도 있습니다.
결과를 로컬로 캐싱하는 것이 너무 느린 것으로 판명되면 좋은 생각으로 보입니다. HEAD는 파일의 시간을 확인하고 헤더에 반환합니다. 당신은 브라우저처럼 할 수 있고 아이콘의 CURLINFO_FILETIME을 얻을 수 있습니다. 캐시에 URL => [favicon, timestamp]를 저장할 수 있습니다. 그런 다음 타임 스탬프를 비교하고 파비콘을 다시로드 할 수 있습니다.
Pies가 말했듯이 cURL을 사용할 수 있습니다. cURL을 사용하여 본문이 아닌 헤더 만 제공 할 수 있으므로 속도가 빨라질 수 있습니다. 잘못된 도메인은 요청이 시간 초과 될 때까지 기다리기 때문에 항상 시간이 걸릴 수 있습니다. cURL을 사용하여 시간 제한 길이를 변경할 수 있습니다.
예를 들면 다음과 같습니다.
function remoteFileExists($url) {
$curl = curl_init($url);
//don't fetch the actual page, you only want to check the connection is ok
curl_setopt($curl, CURLOPT_NOBODY, true);
//do request
$result = curl_exec($curl);
$ret = false;
//if request did not fail
if ($result !== false) {
//if request was ok, check response code
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($statusCode == 200) {
$ret = true;
}
}
curl_close($curl);
return $ret;
}
$exists = remoteFileExists('http://stackoverflow.com/favicon.ico');
if ($exists) {
echo 'file exists';
} else {
echo 'file does not exist';
}
CoolGoose의 솔루션은 좋지만 대용량 파일의 경우 더 빠릅니다 (1 바이트 읽기만 시도하므로).
if (false === file_get_contents("http://example.com/path/to/image",0,null,0,1)) {
$image = $default_image;
}
이것은 원래 질문에 대한 답이 아니지만 수행하려는 작업을 수행하는 더 나은 방법입니다.
실제로 사이트의 favicon을 직접 가져 오려고하는 대신 (/favicon.png, /favicon.ico, /favicon.gif 또는 /path/to/favicon.png 일 수 있다는 점을 감안할 때 왕실의 고통입니다) google을 사용하십시오.
<img src="http://www.google.com/s2/favicons?domain=[domain]">
끝난.
이미지를 다루는 경우 getimagesize를 사용하십시오. file_exists와 달리이 내장 함수는 원격 파일을 지원합니다. 이미지 정보 (너비, 높이, 유형 ..etc)를 포함하는 배열을 반환합니다. 해야 할 일은 배열의 첫 번째 요소 (너비)를 확인하는 것입니다. print_r을 사용하여 배열의 내용을 출력하십시오.
$imageArray = getimagesize("http://www.example.com/image.jpg");
if($imageArray[0])
{
echo "it's an image and here is the image's info<br>";
print_r($imageArray);
}
else
{
echo "invalid image";
}
가장 많이 득표 한 답변의 완전한 기능 :
function remote_file_exists($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if( $httpCode == 200 ){return true;}
}
다음과 같이 사용할 수 있습니다.
if(remote_file_exists($url))
{
//file exists, do something
}
This can be done by obtaining the HTTP Status code (404 = not found) which is possible with file_get_contents
Docs making use of context options. The following code takes redirects into account and will return the status code of the final destination (Demo):
$url = 'http://example.com/';
$code = FALSE;
$options['http'] = array(
'method' => "HEAD",
'ignore_errors' => 1
);
$body = file_get_contents($url, NULL, stream_context_create($options));
foreach($http_response_header as $header)
sscanf($header, 'HTTP/%*d.%*d %d', $code);
echo "Status code: $code";
If you don't want to follow redirects, you can do it similar (Demo):
$url = 'http://example.com/';
$code = FALSE;
$options['http'] = array(
'method' => "HEAD",
'ignore_errors' => 1,
'max_redirects' => 0
);
$body = file_get_contents($url, NULL, stream_context_create($options));
sscanf($http_response_header[0], 'HTTP/%*d.%*d %d', $code);
echo "Status code: $code";
Some of the functions, options and variables in use are explained with more detail on a blog post I've written: HEAD first with PHP Streams.
if (false === file_get_contents("http://example.com/path/to/image")) {
$image = $default_image;
}
Should work ;)
PHP's inbuilt functions may not work for checking URL if allow_url_fopen setting is set to off for security reasons. Curl is a better option as we would not need to change our code at later stage. Below is the code I used to verify a valid URL:
$url = str_replace(' ', '%20', $url);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode>=200 && $httpcode<300){ return true; } else { return false; }
Kindly note the CURLOPT_SSL_VERIFYPEER option which also verify the URL's starting with HTTPS.
A radical solution would be to display the favicons as background images in a div above your default icon. That way, all overhead would be placed on the client while still not displaying broken images (missing background images are ignored in all browsers AFAIK).
function remote_file_exists($url){
return(bool)preg_match('~HTTP/1\.\d\s+200\s+OK~', @current(get_headers($url)));
}
$ff = "http://www.emeditor.com/pub/emed32_11.0.5.exe";
if(remote_file_exists($ff)){
echo "file exist!";
}
else{
echo "file not exist!!!";
}
You could use the following:
$file = 'http://mysite.co.za/images/favicon.ico';
$file_exists = (@fopen($file, "r")) ? true : false;
Worked for me when trying to check if an image exists on the URL
To check for the existence of images, exif_imagetype
should be preferred over getimagesize
, as it is much faster.
To suppress the E_NOTICE
, just prepend the error control operator (@
).
if (@exif_imagetype($filename)) {
// Image exist
}
As a bonus, with the returned value (IMAGETYPE_XXX
) from exif_imagetype
we could also get the mime-type or file-extension with image_type_to_mime_type
/ image_type_to_extension
.
You can use :
$url=getimagesize(“http://www.flickr.com/photos/27505599@N07/2564389539/”);
if(!is_array($url))
{
$default_image =”…/directoryFolder/junal.jpg”;
}
You should issue HEAD requests, not GET one, because you don't need the URI contents at all. As Pies said above, you should check for status code (in 200-299 ranges, and you may optionally follow 3xx redirects).
The answers question contain a lot of code examples which may be helpful: PHP / Curl: HEAD Request takes a long time on some sites
There's an even more sophisticated alternative. You can do the checking all client-side using a JQuery trick.
$('a[href^="http://"]').filter(function(){
return this.hostname && this.hostname !== location.hostname;
}).each(function() {
var link = jQuery(this);
var faviconURL =
link.attr('href').replace(/^(http:\/\/[^\/]+).*$/, '$1')+'/favicon.ico';
var faviconIMG = jQuery('<img src="favicon.png" alt="" />')['appendTo'](link);
var extImg = new Image();
extImg.src = faviconURL;
if (extImg.complete)
faviconIMG.attr('src', faviconURL);
else
extImg.onload = function() { faviconIMG.attr('src', faviconURL); };
});
From http://snipplr.com/view/18782/add-a-favicon-near-external-links-with-jquery/ (the original blog is presently down)
all the answers here that use get_headers() are doing a GET request. It's much faster/cheaper to just do a HEAD request.
To make sure that get_headers() does a HEAD request instead of a GET you should add this:
stream_context_set_default(
array(
'http' => array(
'method' => 'HEAD'
)
)
);
so to check if a file exists, your code would look something like this:
stream_context_set_default(
array(
'http' => array(
'method' => 'HEAD'
)
)
);
$headers = get_headers('http://website.com/dir/file.jpg', 1);
$file_found = stristr($headers[0], '200');
$file_found will return either false or true, obviously.
This works for me to check if a remote file exist in PHP:
$url = 'https://cdn.sstatic.net/Sites/stackoverflow/img/favicon.ico';
$header_response = get_headers($url, 1);
if ( strpos( $header_response[0], "404" ) !== false ) {
echo 'File does NOT exist';
} else {
echo 'File exists';
}
Don't know if this one is any faster when the file does not exist remotely, is_file(), but you could give it a shot.
$favIcon = 'default FavIcon';
if(is_file($remotePath)) {
$favIcon = file_get_contents($remotePath);
}
If the file is not hosted external you might translate the remote URL to an absolute Path on your webserver. That way you don't have to call CURL or file_get_contents, etc.
function remoteFileExists($url) {
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
$urlParts = parse_url( $url );
if ( !isset( $urlParts['path'] ) )
return false;
if ( is_file( $root . $urlParts['path'] ) )
return true;
else
return false;
}
remoteFileExists( 'https://www.yourdomain.com/path/to/remote/image.png' );
Note: Your webserver must populate DOCUMENT_ROOT to use this function
You can use the filesystem: use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
and check $fileSystem = new Filesystem(); if ($fileSystem->exists('path_to_file')==true) {...
'programing tip' 카테고리의 다른 글
다형성-단 두 문장으로 정의 (0) | 2020.09.20 |
---|---|
컴파일 시간에 "SimDeviceType 유형에 적합한 장치를 찾지 못함"문제와 함께 iOS 빌드 실패 (0) | 2020.09.20 |
iPhone의 온 스크린 키보드 높이는 얼마입니까? (0) | 2020.09.20 |
상태 표시 줄이 흰색으로 바뀌고 뒤에 콘텐츠가 표시되지 않습니다. (0) | 2020.09.20 |
FixedThreadPool 대 CachedThreadPool : 두 가지 악 중 적은 것 (0) | 2020.09.19 |