When I use file_get_contents
, is_file
, realpath
, file_exists
with a string that isn't a path I get the following warning.
"function_name()" expects parameter 1 to be a valid path, string given in [...]
So how to determine whether the string could be a valid path or not.
What the hell do you want to do? You may ask...
Well, I want to create a function like this.
funtion my_smart_function( string $path_or_content )
{
$content = is_file_without_warning_if_not_a_valid_path( $path_or_content )
? file_get_contents( $path_or_content )
: $path_or_content;
// do nice stuff with my $content
}
Sometimes $path_or_content
will be a valid path to a file and sometimes $path_or_content
will be the content of a file by itself (eg the binary data of an image created on the fly that doesn't even have a path (at least not yet)). In the latter case all these string related functions I mentioned above (eg file_exists()
) will throw a warning (see quote above).
Something I'm wondering about.realpath('xyz')
doesn't throw a warning butrealpath( file_get_contents('path/to/actual/image.jpg') )
does...
So realpath
and the other functions mentioned above distinguish between a string or a string that is a valid path. So how can we do either beforehand?
The Python isfile() method is used to find whether a given path is an existing regular file or not. It returns a boolean value true if the specific path is an existing file or else it returns false. It can be used by the syntax : os. path.
Open a Command Prompt window (Win⊞ + R, type cmd, hit Enter). Enter the command echo %JAVA_HOME% . This should output the path to your Java installation folder. If it doesn't, your JAVA_HOME variable was not set correctly.
This may be a reasonable time to use the @
modifier to suppress errors.
funtion my_smart_function( string $path_or_content )
{
$content = @file_exists( $path_or_content )
? file_get_contents( $path_or_content )
: $path_or_content;
}
If it's not a valid path, file_exists()
will return a falsey value, and the @
will keep it from complaining about the bad string.
On Linux, the only character that's not allowed in a path is the null byte. So you could just check for this:
if (strpos($path_or_contents, "\0") === false) {
return file_get_contents($path_or_contents);
} else {
return $path_or_contents;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With