My PHP scripts are able to write to the superglobal array $_SERVER
.
Whilst messing with $_SERVER
is pretty obviously a bad idea in almost all cases, there may be situations where it could be useful as a short-term band-aid or for some kinds of testing. Can I rely on it being writeable by scripts, or is this something that might be:
- different for different servers or PHP versions?
- controllable by some ini setting?
The PHP docs don’t appear to specify whether S_SERVER
should be, or might be, read-only. They do imply that it’s just a variable, and therefore writeable like any other variable. However, since it’s a rather special variable, it seems reasonable to ask the question. It’s very easy to show $_SERVER being modified on a real PHP web page:
<?php
$uri = $_SERVER['REQUEST_URI'];
$_SERVER['REQUEST_URI'] = "test-value";
echo '<pre>
Before: "'.$uri.'"
After : "'.$_SERVER['REQUEST_URI'].'"
</pre>';
die();
2
Answers
All superglobals are writable.
I don’t think that PHP even supports read-only variables at all. The closest thing to an exception is that you can’t wipe out the entire
$GLOBALS
array, as in$GLOBALS = []
(but you can still create or edit individual array elements). And even this restriction does not affect$_SERVER
, this is totally valid:Of course, that doesn’t mean that editing a
$_SERVER
entry will necessarily have the same effect than the original value had. For example,$_SERVER['PATH']
contains the process PATH environment variable, but editing it to a different value will not change the env variable itself:Demo