A Simple Link Rewriting Script In PHP
Recently asked in Yahoo! Answers:
Javascript using var to enter domains?
My work uses this great code at the top their page….
<script type=”text/javascript”>
var imghost = ‘http://blah.images.com;
var ahost = ‘http://www.website.com;
var khost = ‘http://www.website.com/future/;
</script>
Then in the HTML code the following is put to make it work:
<img src=”[imghost]/lp/blahblah.jpg”When the page loads and the user views it it reads: src=” http://blah.images.com /lp/blahblah.jpg”
It automatically puts the domain information in case you need to change it. In my case, I’d like all items to point to “.com/future/” then when I’m done with the new site simply change that original java script to remove the “future” and push the testing site live. My company uses .pd files…but that shouldn’t make a difference. I’ve analyzed all the code and can’t make it work on my site, doesn’t look like I’m missing anything. Suggestions? Or maybe a different way to do this? I’m using .php for my site. Thanks!
Actually, this is an example of it making more sense to use a server-side scripting language rather than JavaScript. The client needs to enable JavaScript; if he hasn’t enabled it, the links won’t be updated. PHP ensures we get good links.
So, let’s do this. No code to download this time; you’ll need to pay attention and copy and paste properly from the code here.
Step 1: The HTML Links
The questioner has gotten off to a good start with a good algorithm. But we need to make a modification: Where the questioner wanted to use bracketed names, such as [imghost], [khost] and [ahost], we’ll use PHP variables named $imghost, $khost and $ahost.
<a href="<?php echo $imghost; ?>/directory/subdirectory/image.jpg">Link Text</a> <a href="<?php echo $ahost; ?>/html/page.php">Link Text</a> <a href="<?php echo $khost; ?>/doc.pdf">Link Text</a>
Step 2: The PHP Script
The rest of this solution is simple: Just add the following PHP code to the top of the page, before any HTML tags:
$imghost = "http://blah.images.com"; $ahost = "http://www.website.com"; $khost = "http://www.website.com/future";
If you want to change the hosts for any type of link, you simply change the address in these PHP variables. Note that none of the domains above end with a trailing slash; we’re taking care of directory structure in the links themselves.
Don’t forget: For PHP code to execute on most Web servers, a page with PHP code must end in the .php file extension.
I distribute all code under the latest version of the Creative Commons Attribution / Share-Alike license.















