I am in the process of creating a website using php and due to hosting my website locally and then uploading it onto a server I want an easy way of changing the root domain without manually changing it in every single place I have a domain, so I proposed storing the root domain as a variable. n.b. I have simplified down the names of the files.
I created a a variable called $rootDomain
<?php
$rootDomain = "http://localhost/testWebsite/";
?>
Next I have a new page in a sub folder called: page.php. I get to this page via a link in a header that is used for all the pages.
<a href=<?php $rootDomain?>"pageone/page.php"><li><?php echo$firstLink?></li>
Using the generic header I have on all pages I want to get back to the main index page. The link used looks like this:
<a href=<?php $rootDomain?>"index.php"><?php echo$websiteName?></a>
The expected link location should send me to:
"http://localhost/testWebsite/index.php"
But the link it is displaying is:
"http://localhost/testWebsite/pageone/index.php"
Which is an error.
When I have tested it using the link directly without the variable :
<a href="http://localhost/index.php"><?php echo$websiteName?></a>
There is no error and I get the expected outcome.
I am struggling to work out what I am doing wrong and any help would be much appreciated.
You have to echo
the variable in the href
attribute with PHP for it to show in the HTML output.
You can do so by doing
<a href="<?php echo $rootDomain; ?>index.php"><?php echo $websiteName; ?></a>
or you can use the short echo syntax
<a href="<?= $rootDomain ?>index.php"><?= $websiteName ?></a>
You also have a couple typos in your code, like the misplaced quotes around the href
attribute.