Search code examples
php.htaccessmod-rewritefile-exists

PHP function file_exists not working when using .htaccess rewrite rule


I am using following in my .htaccess file

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^shopping-bag/?$ shoppingbag.php [L,QSA]

This changes the url

http://www.domain.com/foldername/shoppingbag.php

to

www.domain.com/foldername/shopping-bag/

All my content is placed in

/www/foldername/

I fixed all the css and js files by declaring a global variable with value http://www.domain.com/foldername/ and place this variable before the path of css and js files. Since file_exists won't work on a URL I tried doing the following

../uploads/image.jpg

The actual path of the image file is

/www/foldername/uploads/image.jpg

I tried doing

var_dump(../uploads/image.jpg)

on

http://www.domain.com/foldername/shopping-bag/

but didn't work. And I don't want to use <base href="">


Solution

  • Unless you've changed PHP's current working directory with something like chdir( $someDir ), all file system functions should basically behave relative to the current script's directory.

    In your case file_exists( 'uploads/image.jpg' ) or file_exists( './uploads/image.jpg' ) (note the single dot, meaning current directory) should therefore return true, if the file actually exists in the location you said it exists.

    Note that <base href=""> is irrelevant to the PHP script, because PHP is a server-side language, while <base> is a client-side HTML element.

    To get a better understanding of the distinction between server-side and client-side (programming), have a look at this answer, for instance.

    Furthermore, unless you meant to demonstrate something different, var_dump(../uploads/image.jpg) will not output anything meaningful. You can't use var_dump() like that, but perhaps you were already aware of this.