Using php, my objective is to append whatever parameters are present on the url into all the anchors (links) on a page.
- If a link already contains parameters: add the url query into the parameter.
Page url accessed:
site.com/?location=brazil&sex=female
Page "site.com" code:
<!DOCTYPE html>
<html>
<body>
<a href="https://example.com/"> HELLO1 </a>
<! ––I need it to become https://example.com/?location=brazil&sex=female ––>
<a href="https://example.com/?human=yes"> HELLO2 </a>
<! ––I need it to become https://example.com/?human=yes&location=brazil&sex=female ––>
<?php
?>
</body>
</html>
I've done it in javascript but ran into a few problems. Can somebody help me with a php code? Regards.
CodePudding user response:
I hope this will help you out
<?php
//to get current url
$url = "https://";
//Append the host(domain name, ip) to the URL.
$url.= $_SERVER['HTTP_HOST'];
//Append the requested resource location to the URL
$url.= $_SERVER['REQUEST_URI'];
//for example the url i considered
$url_example = 'https://example.com?q=string&f=true&id=1233&sort=true';
//explode function will breakdown string in array
$host = explode('https://example.com?', $url_example); //here replace $url_example with $url as i used for demo purpose only
// accessing the second part of array
echo $host[1]; //for checking
?>
<!DOCTYPE html>
<html>
<body>
<a href="https://example.com?<?= $host[1] ?>">Hello!</a>
<a href="https://example.com?human=yes&<?= $host[1] ?>">Hello2</a>
</body>
</html>