Reputation: 51
I am currently displaying the file name from the database on my PHP page. However, some file names on the server's folders have a different case. So the database may say image1.jpg and the file name on the server may say "image1.JPG" in upper case. This is random with some of the files. These files do not get displayed. Is there a way that I can use a function so that it can be displayed. We are talking about more than 1000 files here. So any help would be highly appreciated.
Upvotes: 5
Views: 1657
Reputation: 2998
I would run a custom file_exists() function to check for which case the image's extension is.
Use this custom function to check for the correct case (pass it lowercase, then use lowercase if it returns a 1, or use uppercase if it returns a 2):
function file_exists_case($strUrl)
{
$realPath = str_replace('\\','/',realpath($strUrl));
if(file_exists($strUrl) && $realPath == $strUrl)
{
return 1; //File exists, with correct case
}
elseif(file_exists($realPath))
{
return 2; //File exists, but wrong case
}
else
{
return 0; //File does not exist
}
}
You really should go in and make all your file name extensions lowercase when you get the time, though.
The way you would do that is by running a glob() through the directories: http://php.net/manual/en/function.glob.php and renaming every file extension to lowercase using strtolower(): http://php.net/manual/en/function.strtolower.php
Upvotes: 5
Reputation: 36659
Not sure if converting the extensions to lowercase is an option. But if there are no other systems that depend on certain extensions to be capitalized then you could run something like this:
find . -name '*.*' -exec sh -c '
a=$(echo {} | sed -r "s/([^.]*)\$/\L\1/");
[ "$a" != "{}" ] && mv "{}" "$a" ' \;
Upvotes: 1
Reputation: 26066
Use file_exists
to do a check. And expand that out to compensate for the issues you are facing. I am using the function called replace_extension()
shown here.
<?php
// Full path to the file.
$file_path = '/path/to/the/great.JPG';
// Call to the function.
echo check_if_image_exists($file_path, $file_ext_src);
// The function itself.
function check_if_image_exists ($file_path) {
$file_ext_src = end(explode('.', $file_path));
if (file_exists($file_path)) {
return TRUE;
}
else {
if (ctype_lower($file_ext_src)) {
$file_ext_new = strtoupper($file_ext_src); // If lowercase make it uppercase.
}
else if (ctype_upper($file_ext_src)) {
$file_ext_new = strtolower($file_ext_src); // If uppercase make it lowercase.
}
// Now create a new filepath with the new extension & check that.
$file_path_new = replace_extension($file_path, $file_ext_new);
if (file_exists($file_path_new)) {
return TRUE;
}
else {
return FALSE;
}
}
}
// Nice function taken from elsewhere.
function replace_extension($filename, $new_extension) {
$info = pathinfo($filename);
return $info['filename'] . '.' . $new_extension;
}
?>
Upvotes: 0