check if php file exists on server - php

I'm looking for a way to see if a file exists on the local server. I would usually use if function exists but in this case it's not an option.
My question is how can I get number 2 to return true.
1.Returns true:
$acf_funcs = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/themes/vac3/acf/page_meta/functions.php';
var_dump(file_exists($acf_funcs));
2.Returns false:
$acf_funcs = 'http://vac3:8888/wp-content/themes/vac3/acf/page_meta/functions.php';
var_dump(file_exists($acf_funcs));

You can't use file_exists -- You'll need to use get_headers
$headers = get_headers('http://vac3:8888/wp-content/themes/vac3/acf/page_meta/functions.php', 1);
$file_found = stristr($headers[0], '200');

To check the local server filesystem, you need to get the path component from the URL:
var_dump(file_exists($_SERVER['DOCUMENT_ROOT'] . parse_url($acf_funcs, PHP_URL_PATH)));
In the above:
parse_url($acf_funcs, PHP_URL_PATH)
Returns: /wp-content/themes/vac3/acf/page_meta/functions.php and pre-pending $_SERVER['DOCUMENT_ROOT'] yields the same as your first example.
This will NOT however check if the file is available via http://vac3:8888.

Related

Laravel Storaget get file contents

I want to know if you do the following in my code below how do you check if the file exists e.g
{
$file = Storage::disks('local')->get($file);
// then test if $file exists
}
You can check the existence of the file with the code below for your local storage,
$file_exists = Storage::disk('local')->exists($file);
You can read more about storage on Laravel Document at Laravel Filesystem.
Note: in the document you will check disk('s3'). It depends on what connection we are using defined in config/filesystem.php(the configuration file for the filesystem in laravel).
OR simply you can use check the condition by
if(Storage::disk('local')->exists($file)) {
}
It will also work for you.
There's a clear example in the docs, if you take a look.
$exists = Storage::disk('s3')->exists('file.jpg');

PHP Change Root path depending on localhost vs server

Using PHP, I would like to have a simple config.php file that enables me to check whether I am on localhost vs mydomain.com.
For example, on 'localhost':
$path = '/'
But when I upload to my server ('mydomain.com'), I'd like to have the path be:
$path = '/testing/
I'd like to be able to check whether I am developing locally vs when the site is uploaded to my ftp.
You can get your current running server using $_SERVER['SERVER_NAME']:
$default_path = ($_SERVER['SERVER_NAME'] == 'localhost') ? '/' : '/testing/';
There are plenty of other variables in the $_SERVER superglobal array, if you want to use another one you should debug it and find whichever one you want (I'm on Amazon servers and I've got tons of Amazon specific variables to choose from too):
echo '<pre>'; print_r($_SERVER); exit;
SERVER_NAME is more reliable than others like HTTP_HOST, see this article for details.
You could probably check using $_SERVER['REMOTE_ADDR']. On localhost, this would return 127.0.0.1:
if ($_SERVER['REMOTE_ADDR'] === '127.0.0.1') {
$path = '/';
} else {
$path = '/testing/;
}
It is not 100% reliable, but works for most cases.
I use to have this line in my config files for that purpose
$isLocal=($_SERVER['REMOTE_ADDR']=="127.0.0.1" );

PHP if file_exists() statement fails on file_get_content() from URL

I have a very simple function to read URL image file and save it on server.
function o99_download_shot_binary(){
$url = esc_url_raw( o99_get_content_link() ); // function returns http:// url
$img = $uploads['basedir'] . '/tmp/' . uniqid() . '.jpeg'; // name and location
file_put_contents($img, file_get_contents($url));
}
IT works ok, but sometimes , o99_get_content_link() returns an invalid URL, so an empty image is saved , so I made a simple check with if statement and separated the one liner:
function o99_download_shot_binary(){
$url = esc_url_raw( o99_get_content_link() ); // function returns http:// url
$img = $uploads['basedir'] . '/tmp/' . uniqid() . '.jpeg'; // name and location
$file = file_get_contents($url);
if (file_exists($file)) {
file_put_contents($img, $file);
}
}
But doing so, NO image is saved .
So I tried to change the if statement to
if ( $file) { file_put_contents($img, $file); }
..and now it works .
As everything is OK now, you might be wondering why did I posted this question , well,
since I want also to UNDERSTAND what I am doing - My Question is simply :
why does the file_exists($file) check fails ?
I assumed to myself (maybe wrongly) that it is because the file_exists() only checks LOCAL filesystem. If this is the case , then is there a dedicated function to check the existence over URL ? or any other better solutions for future references ?
EDIT I (as per comments request )
Var_dump() is a binary string :
string(51238) "����JFIF��������BZ�|su��{��3�_�R��[J��z���K�^��g�/��9���|*�F��W~�>񏎭tχ�>��� �&��?�~0�f�����[��i���R��_���g~�_��Ɵ�#����.5�x+�_ u��-�ٿ�L����ƺV�� ... ... ...
But this is predictable, like I said in original question, the file IS being saved OK, it is just a question of WHY the file_exists() check fails, and if there is a better way to perform that check on a binary remote file from URL...
$file = file_get_contents($url) means that $file contains a string, the contents of the file. Unless the file's contents happens to be a path to a file that exists, you won't save anything.
You want to check if( file_exists($url)) and keep the one-liner you had before.
file_exists() expects a path, like /home/user/foo.txt, or C:\foo.txt. You are supplying it with the contents of the file, not the local path to the file, so it will not return a true value (unless, of course, the contents of the file are a valid file path to an existing file... not to muddy the waters but it had to be said :) ).

file_exists() returns false, but the file DOES exist

I'm having a very weird issue with file_exists(). I'm using this function to check if 2 different files in the same folders do exist. I've double-checked, they BOTH do exist.
echo $relative . $url['path'] . '/' . $path['filename'] . '.jpg';
Result: ../../images/example/001-001.jpg
echo $relative . $url['path'] . '/' . $path['filename'] . '.' . $path['extension'];
Result: ../../images/example/001-001.PNG
Now let's use file_exists() on these:
var_dump(file_exists($relative . $url['path'] . '/' . $path['filename'] . '.jpg'));
Result: bool(false)
var_dump(file_exists($relative . $url['path'] . '/' . $path['filename'] . '.' . $path['extension']));
Result: bool(true)
I don't get it - both of these files do exist. I'm running Windows, so it's not related to a case-sensitive issue. Safe Mode is off.
What might be worth mentioning though is that the .png one is uploaded by a user via FTP, while the .jpg one is created using a script. But as far as I know, that shouldn't make a difference.
Any tips?
Thanks
file_exists() just doesn't work with HTTP addresses.
It only supports filesystem paths (and FTP, if you're using PHP5.)
Please note:
Works :
if (file_exists($_SERVER['DOCUMENT_ROOT']."/folder/test.txt")
echo "file exists";
Does not work:
if (file_exists("www.mysite.com/folder/test.txt")
echo "file exists";
Results of the file_exists() are cached, so try using clearstatcache(). If that not helped, recheck names - they might be similar, but not same.
I found that what works for me to check if a file exists (relative to the current php file it is being executed from) is this piece of code:
$filename = 'myfile.jpg';
$file_path_and_name = dirname(__FILE__) . DIRECTORY_SEPARATOR . "{$filename}";
if ( file_exists($file_path_and_name) ){
// file exists. Do some magic...
} else {
// file does not exists...
}
Just my $.02: I just had this problem and it was due to a space at the end of the file name. It's not always a path problem - although that is the first thing I check - always. I could cut and paste the file name into a shell window using the ls -l command and of course that locates the file because the command line will ignore the space where as file_exists does not. Very frustrating indeed and nearly impossible to locate were it not for StackOverflow.
HINT: When outputting debug statements enclose values with delimiters () or [] and that will show a space pretty clearly. And always remember to trim your input.
It's because of safe mode. You can turn it off or include the directory in safe_mode_include_dir. Or change file ownership / permissions for those files.
php.net: file_exists()
php.net: safe mode
Try using DIRECTORY_SEPARATOR instead of '/' as separator. Windows uses a different separator for file system paths (backslash) than Linux and Unix systems.
A very simple trick is here that worked for me.
When I write following line, than it returns false.
if(file_exists('/my-dreams-files/'.$_GET['article'].'.html'))
And when I write with removing URL starting slash, then it returns true.
if(file_exists('my-dreams-files/'.$_GET['article'].'.html'))
I have a new reason this happens - I am using PHP inside a Docker container with a mounted volume for the codebase which resides on my local host machine.
I was getting file_exists == FALSE (inside Composer autoload), but if I copied the filepath into terminal - it did exist! I tried the clearstatche(), checked safe-mode was OFF.
Then I remembered the Docker volume mapping: the absolute path on my local host machine certainly doesn't exist inside the Docker container - which is PHP's perspective on the world.
(I keep forgetting I'm using Docker, because I've made shell functions which wrap the docker run commands so nicely...)
It can also be a permission problem on one of the parent folders or the file itself.
Try to open a session as the user running your webserver and cd into it. The folder must be accessible by this user and the file must be readable.
If not, php will return that the file doesn't exist.
have you tried manual entry. also your two extensions seem to be in different case
var_dump(file_exists('../../images/example/001-001.jpg'));
var_dump(file_exists('../../images/example/001-001.PNG'));
A custom_file_exists() function inspired by #Timur, #Brian, #Doug and #Shahar previous answers:
function custom_file_exists($file_path=''){
$file_exists=false;
//clear cached results
//clearstatcache();
//trim path
$file_dir=trim(dirname($file_path));
//normalize path separator
$file_dir=str_replace('/',DIRECTORY_SEPARATOR,$file_dir).DIRECTORY_SEPARATOR;
//trim file name
$file_name=trim(basename($file_path));
//rebuild path
$file_path=$file_dir."{$file_name}";
//If you simply want to check that some file (not directory) exists,
//and concerned about performance, try is_file() instead.
//It seems like is_file() is almost 2x faster when a file exists
//and about the same when it doesn't.
$file_exists=is_file($file_path);
//$file_exists=file_exists($file_path);
return $file_exists;
}
This answer may be a bit hacky, but its been working for me -
$file = 'path/to/file.jpg';
$file = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$file;
$file_headers = #get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}else{
$exists = true;
}
apparently $_SERVER['REQUEST_SCHEME'] is a bit dicey to use with IIS 7.0 + PHP 5.3 so you could probably look for a better way to add in the protocol.
I found this answer here http://php.net/manual/en/function.file-exists.php#75064
I spent the last two hours wondering what was wrong with my if statement: file_exists($file) was returning false, however I could call include($file) with no problem.
It turns out that I didn't realize that the php include_path value I had set in the .htaccess file didn't carry over to file_exists, is_file, etc.
Thus:
<?PHP
// .htaccess php_value include_path '/home/user/public_html/';
// includes lies in /home/user/public_html/includes/
//doesn't work, file_exists returns false
if ( file_exists('includes/config.php') )
{
include('includes/config.php');
}
//does work, file_exists returns true
if ( file_exists('/home/user/public_html/includes/config.php') )
{
include('includes/config.php');
}
?>
Just goes to show that "shortcuts for simplicity" like setting the include_path in .htaccess can just cause more grief in the long run.
In my case, the problem was a misconception of how file_exists() behaves with symbolic links and .. ("dotdot" or double period) parent dir references. In that regard, it differs from functions like require, include or even mkdir().
Given this directory structure:
/home/me/work/example/
www/
/var/www/example.local/
tmp/
public_html -> /home/me/work/example/www/
file_exists('/var/www/example.local/public_html/../tmp/'); would return FALSE even though the subdir exists as we see, because the function traversed up into /home/me/work/example/ which does not have that subdir.
For this reason, I have created this function:
/**
* Resolve any ".." ("dotdots" or double periods) in a given path.
*
* This is especially useful for avoiding the confusing behavior `file_exists()`
* shows with symbolic links.
*
* #param string $path
*
* #return string
*/
function resolve_dotdots( string $path ) {
if (empty($path)) {
return $path;
}
$source = array_reverse(explode(DIRECTORY_SEPARATOR, $path));
$balance = 0;
$parts = array();
// going backwards through the path, keep track of the dotdots and "work
// them off" by skipping a part. Only take over the respective part if the
// balance is at zero.
foreach ($source as $part) {
if ($part === '..') {
$balance++;
} else if ($balance > 0) {
$balance--;
} else {
array_push($parts, $part);
}
}
// special case: path begins with too many dotdots, references "outside
// knowledge".
if ($balance > 0) {
for ($i = 0; $i < $balance; $i++) {
array_push($parts, '..');
}
}
$parts = array_reverse($parts);
return implode(DIRECTORY_SEPARATOR, $parts);
}
I just encountered this same problem and I solved it in a mysterious way. After inserting a a filepath I copied from Windows File explorer. file_exists() keeps returning false continuously, but if I copy same path from VSCode editor it works perfectly.
After dumping variables with var_dump($path); I noticed something mysterious.
For path I copied from file explorer it shows length 94.
For path I copied from VSCode Editor it shows length 88.
Both path look same length on my code Editor.
My suggestion: if string contain hidden characters, it may fail and not work.

How to check if a file exists under include path?

You get the current include path in PHP by using get_include_path()
I am wondering what is the lightweight way to check if the file can be included without issuing a PHP error. I am using Yii framework and I want to an import without issuing PHP error, but I fail.
As of PHP 5.3.2, you can use
stream_resolve_include_path — Resolve filename against the include path
which will
Returns a string containing the resolved absolute filename, or FALSE on failure.
Example from Manual:
var_dump(stream_resolve_include_path("test.php"));
The above example will output something similar to:
string(22) "/var/www/html/test.php"
Before PHP 5.3.2 you can split the path and check each path in a loop:
$find = 'file.php'; //The file to find
$paths = explode(PATH_SEPARATOR, get_include_path());
$found = false;
foreach($paths as $p) {
$fullname = $p.DIRECTORY_SEPARATOR.$find;
if(is_file($fullname)) {
$found = $fullname;
break;
}
}
//$found now contains the file to be included, or false if not found

Categories