sneakyRedPanda sneakyRedPanda - 1 month ago 12
PHP Question

Using PHP tags inside of href="" definition

I'm using a simple solution for getting the server root and it works quite well with my includes:

<?php $root = $_SERVER['DOCUMENT_ROOT'].'/frizkie'; ?>


I'm doing some tables, and the .php file that contains the table is nested quite a few directories down at:

/main/tools/planners.php


My images are located in:

/images/staticons/


And my code looks like:

<td onClick="document.location.href='planners/agility.php';">Contents</a></td>


I'd like to be able to use the $root directory for the 'planners/agility.php' part, but doing so like this:

onClick="document.location.href='<?php echo $root; ?>/planners/agility.php';"


Causes the onClick part to not work at all. On top of this, I'd also like to define table cell backgrounds using the same method, using the
$root
variable. I've tried using PHP tags in the background="" definition, but the images don't show in Chrome or Firefox - only IE9.

Answer Source

$_SERVER['DOCUMENT_ROOT'] is for server-side pathing so to speak, as you already noted. You don't need to put it in your markup, CSS and JS. I'd stick with absolute-relative paths like /images/background.jpg (note the leading slash). That way even if your page is accessed by a URL like

http://example.com/blog/123-my-beautiful-post/

the image is downloaded from

http://example.com/images/background.jpg

and not

http://example.com/images/blog/123-my-beautiful-post/images/background.jpg.

Using DOCUMENT_ROOT helps a lot when including multiple files scattered around your document root - using relative paths here gives me a headache. If you really want full urls in your pages, though, you can try using $_SERVER['SERVER_NAME'] for that matter, but I really don't understand the need to do so.