Home > Back-end >  REMOTE_USER not always set in basic authentication when changing to running PHP as a CGI module
REMOTE_USER not always set in basic authentication when changing to running PHP as a CGI module

Time:02-12

My host provider just moved me to PHP 7.4 (at my request) and in the process changed PHP from running as an Apache module (now 2.4.52) to as CGI -- good from what I know. My website uses Basic Authentication, and my code relies HEAVILY on $_SERVER['REMOTE_USER'] to get the username in tons of places. Well, in some cases at least (so far from what I've seen), that variable is NOT set, but instead $_SERVER['REDIRECT_REMOTE_USER'] is. In other places, there might be other $_SERVER vars that are set instead, tho I haven't seen them yet (I reverted to the old configuration for the time being, since this broke the site). [BTW, a lot of this code is over 20 years old now.]

So my question: is there any way to force $_SERVER['REMOTE_USER'] to always be set with the username without having to modify all those places in my code? Especially if there's some config settings that I could use? I did see what looks to be a nice function to get the username in PHP get username from Basic Authorization but I'm hoping to find a way to avoid changing all that old code. Or any other ideas?

CodePudding user response:

Try putting this in your .htaccess after RewriteEngine On

RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]

That should set the REMOTE_USER environment variable when using CGI.

CodePudding user response:

Only the REDIRECT_REMOTE_USER gets set to the username

You could perhaps auto-include a short PHP script that sets REMOTE_USER (from REDIRECT_REMOTE_USER) before your main script runs.

For example, set the auto_prepend_file in your .user.ini file in the root

auto_prepend_file=/path/to/fix-http-authentication.php

And then in your fix-http-authentication.php script, something like:

<?php
if (empty($_SERVER['REMOTE_USER']) && isset($_SERVER['REDIRECT_REMOTE_USER'])) {
    $_SERVER['REMOTE_USER'] = $_SERVER['REDIRECT_REMOTE_USER'];
}
  • Related