0

I am writing a PHP file but I don't know what is the best way to create a link while the link is in the same file but with a different ID. What I mean is that I have a file named test.php and it contains something like:

if ($id == "") {
    echo "<a href='".$_SERVER['PHP_SELF']."?id=test'>Try the test page</a>";
} else if ($id == "test") {
    echo "Here is the testing content with various information!";
}

I want to know what is better for more secure code: $_SERVER['PHP_SELF']?id=test or test.php?id=test.

I know it serves the same purpose now, but if I change the file name $_SERVER['PHP_SELF']?id=test seems better because it will still point to the same file.

But I would like to know for sure which is safer.

dimo414
  • 47,227
  • 18
  • 148
  • 244

1 Answers1

5

You should not be printing $_SERVER['PHP_SELF']; it's a security vulnerability (there's an example here: How To Identify The Requested Page In PHP).

If you're trying to link to the same page, but with query parameters (?) or anchors (#) you can simply link directly to them, as @kingkero suggests.

<!--
  The code snippet runs as an iframe from http://stacksnippets.net/js, 
  so that's the root of the links you'll see if you click "Run".
-->
<a href="">Link to current page</a><br />
<a href="?id=test">Add query param to current page</a><br />
<a href="#anchor">Add anchor tag to current page</a>

Links that don't begin with a / or a protocol (like http://) are relative to the current document's location. Links that begin with a / are relative to the domain root. The behavior is laid out by the W3C.

Broadly speaking, you're right, you should avoid hard coding things like the filename into your file. But you also should generally not need to use data in $_SERVER to construct links.

Community
  • 1
  • 1
dimo414
  • 47,227
  • 18
  • 148
  • 244
  • So, the more easier way to use is just `?id=test` without the same file name, I'm right? –  Apr 22 '15 at 18:48
  • That's right. You could try this yourself, just create a plain HTML file and create a link like my example. Open the file in a browser, and you'll see clicking the link adds the query param. – dimo414 Apr 22 '15 at 19:17