$_SERVER['REQUEST_URI'] in Session saves latest missing file instead page URI

367 Views Asked by At

I'm facing a very strange behavior and hope to get your help and the solution or explenation for it.

I do use a very simple code on a page:

// start a session
if( !session_id() )
  session_start('');

// write current url in session to prepare redirect after login
$_SESSION['url_before_login'] = $_SERVER['REQUEST_URI'];

On the same page I do load a favicon, which currently is missing. So, on the console of the browser i get this error message:

GET https://my.domain.ltd/assets/favicon/apple-touch-icon.png [HTTP/2 404 Not Found 141ms]

This is fine. But, the strange behavior is, my variable $_SESSION['url_before_login'] does not have the $_SERVER['REQUEST_URI'] of my page but the $_SERVER['REQUEST_URI'] of the missing file. When I output the $_SESSION['url_before_login'] I do get /assets/favicon/apple-touch-icon.png instead of /folder/sub-folder/. If there is no loading error and no missing file, the $_SESSION['url_before_login'] shows me the right URI.

Does anyone know this behavior and has a solution how to fix this (beside making sure not to have a missing file ;-)).

2

There are 2 best solutions below

0
On

I guess you have a .htaccess file that reroutes all requests to the PHP file, meaning that for every request you session variable is rewritten:

/* even a 404 favicon request triggers this line... */
$_SESSION['url_before_login'] = $_SERVER['REQUEST_URI'];

The browser makes several requests for favicons, you can't prevent that, so this will interfere with your session vars if everything goes through the same script.

So, you have some options:

a. you change your .htaccess file so that all requests for "favicon" are redirected to another path SO search: redirect favicon request:

b. change you PHP file to something like this:

/* check if this is a request for favicon */
if (strpos($_SERVER['REQUEST_URI'], "favicon") !== false))
  exit;

// else, continue script...
$_SESSION['url_before_login'] = $_SERVER['REQUEST_URI'];

c. put some favicons on your server, or use a hack: SO: How to prevent favicon.ico requests?

0
On

Thank you @verjas for taking your time to write the answer. The favicon was just an example. I have to prevent this behavior because of possible other missing files. I write a WordPress plugin and it could be there are missing files from other plugins or the theme which is out of my control.

My htaccess is very basic

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

So, I assume this is not the reason for this behavior.

Do you have any other idea how to prevent this?

Thanks once more for your time and thoughts.