PHP : 이미지 파일이 있는지 확인하는 방법은 무엇입니까?
CDN에 특정 이미지가 있는지 확인해야합니다.
다음을 시도했지만 작동하지 않습니다.
if (file_exists(http://www.example.com/images/$filename)) {
echo "The file exists";
} else {
echo "The file does not exist";
}
이미지가 존재하거나 존재하지 않더라도 항상 "파일이 있습니다."라고 표시됩니다. 왜 작동하지 않는지 모르겠습니다 ...
최소한 (문자열로) 따옴표로 묶인 파일 이름이 필요합니다.
if (file_exists('http://www.mydomain.com/images/'.$filename)) {
… }
또한 $filename
올바르게 검증되었는지 확인하십시오. 그런 다음 allow_url_fopen
PHP 구성에서이 활성화 된 경우에만 작동 합니다.
if (file_exists('http://www.mydomain.com/images/'.$filename)) {}
이것은 나를 위해 작동하지 않았습니다. 내가 한 방식은 getimagesize를 사용하는 것입니다.
$src = 'http://www.mydomain.com/images/'.$filename;
if (@getimagesize($src)) {
'@'는 이미지가 존재하지 않는 경우 (이 경우 함수는 일반적으로 오류를 발생시킵니다 getimagesize(http://www.mydomain.com/images/filename.png) [function.getimagesize]: failed
:) false를 반환 함을 의미합니다.
글쎄, file_exists
파일이 존재하는지 말하는 것이 아니라 경로가 존재 하는지를 말한다 . ⚡⚡⚡⚡⚡⚡⚡
따라서 파일 인지 확인하려면와 is_file
함께 사용 file_exists
하여 경로 뒤에 실제로 파일이 있는지 확인 해야 합니다. 그렇지 않으면 기존 경로에 대해 file_exists
반환 true
됩니다.
내가 사용하는 기능은 다음과 같습니다.
function fileExists($filePath)
{
return is_file($filePath) && file_exists($filePath);
}
다음과 같이 시도하십시오.
$file = '/path/to/foo.txt'; // 'images/'.$file (physical path)
if (file_exists($file)) {
echo "The file $file exists";
} else {
echo "The file $file does not exist";
}
파일이 있는지 확인하는 가장 간단한 방법은 다음과 같습니다.
if(is_file($filename)){
return true; //the file exist
}else{
return false; //the file does not exist
}
먼저 이해해야 할 사항 : 파일이 없습니다 .
파일은 파일 시스템 의 주제 이지만 URL 만 지원하는 HTTP 프로토콜을 사용하여 요청하고 있습니다.
따라서 브라우저를 사용하여 존재하지 않는 파일을 요청하고 응답 코드를 확인해야합니다. 404가 아니면 파일이 있는지 확인하기 위해 래퍼를 사용할 수 없으며 다른 프로토콜 (예 : FTP)을 사용하여 CDN을 요청해야합니다.
public static function is_file_url_exists($url) {
if (@file_get_contents($url, 0, NULL, 0, 1)) {
return 1;
}
return 0;
}
If the file is on your local domain, you don't need to put the full URL. Only the path to the file. If the file is in a different directory, then you need to preface the path with "."
$file = './images/image.jpg';
if (file_exists($file)) {}
Often times the "." is left off which will cause the file to be shown as not existing, when it in fact does.
There is a major difference between is_file
and file_exists
.
is_file
returns true for (regular) files:
Returns TRUE if the filename exists and is a regular file, FALSE otherwise.
file_exists
returns true for both files and directories:
Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.
Note: Check also this stackoverflow question for more information on this topic.
You have to use absolute path to see if the file exists.
$abs_path = '/var/www/example.com/public_html/images/';
$file_url = 'http://www.example.com/images/' . $filename;
if (file_exists($abs_path . $filename)) {
echo "The file exists. URL:" . $file_url;
} else {
echo "The file does not exist";
}
If you are writing for CMS or PHP framework then as far as I know all of them have defined constant for document root path.
e.g WordPress uses ABSPATH which can be used globally for working with files on the server using your code as well as site url.
Wordpress example:
$image_path = ABSPATH . '/images/' . $filename;
$file_url = get_site_url() . '/images/' . $filename;
if (file_exists($image_path)) {
echo "The file exists. URL:" . $file_url;
} else {
echo "The file does not exist";
}
I'm going an extra mile here :). Because this code would no need much maintenance and pretty solid, I would write it with as shorthand if statement:
$image_path = ABSPATH . '/images/' . $filename;
$file_url = get_site_url() . '/images/' . $filename;
echo (file_exists($image_path))?'The file exists. URL:' . $file_url:'The file does not exist';
Shorthand IF statement explained:
$stringVariable = ($trueOrFalseComaprison > 0)?'String if true':'String if false';
you can use cURL. You can get cURL to only give you the headers, and not the body, which might make it faster. A bad domain could always take a while because you will be waiting for the request to time-out; you could probably change the timeout length using cURL.
Here is example:
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';
}
You can use the file_get_contents
function to access remote files. See http://php.net/manual/en/function.file-get-contents.php for details.
try this :
if (file_exists(FCPATH . 'uploads/pages/' . $image)) {
unlink(FCPATH . 'uploads/pages/' . $image);
}
Read first 5 bytes form HTTP using fopen()
and fread()
then use this:
DEFINE("GIF_START","GIF");
DEFINE("PNG_START",pack("C",0x89)."PNG");
DEFINE("JPG_START",pack("CCCCCC",0xFF,0xD8,0xFF,0xE0,0x00,0x10));
to detect image.
file_exists
reads not only files, but also paths. so when $filename
is empty, the command would run as if it's written like this:
file_exists("http://www.example.com/images/")
if the directory /images/ exists, the function will still return true
.
I usually write it like this:
// !empty($filename) is to prevent an error when the variable is not defined
if (!empty($filename) && file_exists("http://www.example.com/images/$filename"))
{
// do something
}
else
{
// do other things
}
file_exists($filepath)
will return a true result for a directory and full filepath, so is not always a solution when a filename is not passed.
is_file($filepath)
will only return true for fully filepaths
If you are using curl, you can try the following script:
function checkRemoteFile($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
// don't download content
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(curl_exec($ch)!==FALSE)
{
return true;
}
else
{
return false;
}
}
Reference URL: https://hungred.com/how-to/php-check-remote-email-url-image-link-exist/
you need server path with file_exists
for example
if (file_exists('/httpdocs/images/'.$filename)) {echo 'File exist'; }
If path to your image is relative to the application root it is better to use something like this:
function imgExists($path) {
$serverPath = $_SERVER['DOCUMENT_ROOT'] . $path;
return is_file($serverPath)
&& file_exists($serverPath);
}
Usage example for this function:
$path = '/tmp/teacher_photos/1546595125-IMG_14112018_160116_0.png';
$exists = imgExists($path);
if ($exists) {
var_dump('Image exists. Do something...');
}
I think it is good idea to create something like library to check image existence applicable for different situations. Above lots of great answers you can use to solve this task.
참고URL : https://stackoverflow.com/questions/7991425/php-how-to-check-if-image-file-exists
'program story' 카테고리의 다른 글
FileSystemWatcher를 사용하여 디렉토리 모니터링 (0) | 2020.09.01 |
---|---|
Atom 편집기에서 선택 항목을 대문자 (또는 소문자)로 변환하는 키보드 단축키 (0) | 2020.09.01 |
브랜치에서 모든 커밋을 가져오고 지정된 커밋을 다른 커밋으로 푸시 (0) | 2020.08.31 |
ASP.NET에서 SQL SERVER에 대한 연결 문자열 설정 (0) | 2020.08.31 |
JavaScript를 사용하여 현재 URL에서 쿼리 문자열을 얻는 방법은 무엇입니까? (0) | 2020.08.31 |