user8758206
user8758206

Reputation: 2191

generating a HREF depending on the current URL using PHP

I am new to PHP so hope this isn't too embarrassing, but also have a further different question. I'm trying to make it so that a link's HREF is generated differently depending on the page.

I.e. if the url is mysite/com/blog/, make the url ../ otherwise ../../ - so whenever I create new blog posts or pages, it will automatically chose the right URL and not create a broken 404 link.

Why does the below code not work? Is there a syntax error?

Also another question - the links on my new blog to my main website work but they link to my main website using https://www.example.com/somepage.html, and I'd rather it be like ../../somepage.html -

is the full URL bad for my website? e.g. bad for SEO, or in analytics will it show as a bounce off my website if it was the full link and not if it was from ../ ?

thanks a million!

<li><a href="<?php $blog = “/blog/”; $currentpage = $_SERVER['REQUEST_URI']; if($blog==$currentpage) {http://google.com}else{http://yahoo.com}?>">About</a></li>

Upvotes: 1

Views: 1427

Answers (1)

waterloomatt
waterloomatt

Reputation: 3742

You're very close. I just split out the PHP from the HTML to make it easier to read. Basically, you were just missing the quotes around the destination URL. I also added a new variable $destination and set it to a default value. This way you can avoid the else which, again, just makes it easier to read.

<?php
$blog = '/blog/'; 
$currentpage = $_SERVER['REQUEST_URI']; 
$destination = 'http://yahoo.com'; // This is a default

if ($blog == $currentpage) {
    $destination = 'http://google.com';
}
?>

<li>
    <a href="<?php echo $destination; ?>">About</a>
</li>

EDIT

Also another question - the links on my new blog to my main website work but they link to my main website using https://www.example.com/somepage.html, and I'd rather it be like ../../somepage.html -

is the full URL bad for my website? e.g. bad for SEO, or in analytics will it show as a bounce off my website if it was the full link and not if it was from ../ ?

What do you mean when you say,

../

<a href="../somepage.html">Test</a> VS. <a href="mysite.com/somepage.html">Test</a> ?

If so, then there is no difference. The browser will send the user to the same page and the HTTP request will look the same.

EDIT #2

thanks for that. By ../ I mean if you consider href='../somepage.html' vs href='example.com/somepage.html'; - one linking locally and one sending a http request and requiring the internet to work – user8758206

I think there is some confusion about what is happening when you use relative links Vs. absolute links. These are instructions for the browser at runtime. It does not generate an extra HTTP request (redirect) when someone clicks on the link. All else being equal, both links will produce a 200 HTTP response code from the server.

Here's a discussion - Absolute vs relative URLs

Upvotes: 3

Related Questions