'how to validate file_get_contents()?
I have a file in my site, ex: http://example.com/name.txt
I would like to check if this file exists inside a function, so I did this
<?php
function checkFile($fileUrl){
if(!is_file($fileUrl) || !is_readable($fileUrl)){
return 'This is not valid file';
}
}
Since checkFile('http://example.com/name.txt'); said it could not file the file, I tried to also check using this method.
function checkFile($fileUrl){
$file = file_get_contents($fileUrl);
if(empty){
return 'File not found or empty';
}
}
But both approach are giving me errors static that the file is not found. I am sure the file is there, so how can I actually check if files exists in online?
Solution 1:[1]
Alternatively you can check response headers from server if 404 then file doesn't exist using function
get_headers()
http://us1.php.net/manual/en/function.get-headers.php
$file = 'http://www.domain.com/somefile.jpg';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
Solution 2:[2]
function checkFile($fileUrl) {
if (!file_exists($fileUrl)) {
return 'This file is not a valid file.';
}
}
Side Note This is only valid as of PHP 5 http://us1.php.net/manual/en/function.file-exists.php
Solution 3:[3]
Could you try this?
# run this for
$mime = image_type_to_mime_type(exif_imagetype($url));
$extension = self::mime2ext($mime);
Then use this Github mime2ext function to determine if a valid file is found (or the file you're expecting).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Abhishek |
| Solution 2 | Rottingham |
| Solution 3 | Adam |
