-1

Possible Duplicate:
global variables in php not working as expected

I have a php function that runs on every page of a website, it use a global variable, for example:

$var = "test";
function test() {
    global $var;
    echo $var;
}

This works fine when accessing /anyFile.php directly, but the website uses an htaccess file to rewrite urls, something like:

RewriteRule ^action/(.*)$ /index.php?action=$1 [L]

When an url is rewrited by the htaccess, the function doesn't work, the $var is not set.

What could be this happening and how can I fix it? (I NEED to use "global", otherwise I'd need to recode a lot of things.

Community
  • 1
  • 1
James Harzs
  • 1,853
  • 5
  • 21
  • 30
  • 1
    Your `$var` wasn't defined in global context, as probably (that's the code you didn't show) index.php invokes the action script from a function (=local scope). – mario Aug 29 '12 at 23:44
  • 1
    Post your actual code. Apache cannot affect PHP variables unless passed in `$_GET`, except if register_globals is On, which it _shouldn't be!!!!_ – Michael Berkowski Aug 29 '12 at 23:44
  • Are these lines together? mod_rewrite does not influence php... There must be something else happenning or $var is being modified in other place. – Grzegorz Aug 29 '12 at 23:44
  • The code I didn't show is irrelevant, and too long to post it here. I tested it with the exact function i posted in the question, it works when visiting /index.php?action=anything, but it doesn't work ($var is not set) when visiting /action/anything. I tried $GLOBAL['var'], and it's also not set on the second url. – James Harzs Aug 30 '12 at 00:01

1 Answers1

2

You need to use [QSA,L] instead of [L]:

RewriteRule ^action/(.*)$ /index.php?action=$1 [QSA,L]

QSA stands for Query String Append, and forwards the query string (the part after the ? in the url) to the PHP script.

By the way, you should not use register_globals (deprecated as of PHP 5.3 and removed as of PHP 5.4), but use the $_GET superglobal instead.

--- edit ---

Following your comment below (you can't modify the .htaccess), you're out of luck. Your only solution is to parse the query string in the request URI, and use that as you would use the $_GET superglobal:

$queryString = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
parse_str($queryString, $query);
echo $query['action'];

I strongly advise you to get the .htaccess modified for you, though.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
  • The htaccess is from a script not my code so I don't think i will be modifying that, i may break something. I also tried $GLOBAL['var'], but its not set on the rewrited urls. – James Harzs Aug 30 '12 at 00:03