Trick to change image according to URL in PHP
Hi people! This trick is pretty simple and very useful at
sometimes.
Sometimes you might want to change image according to
URL in any PHP page here is the tutorial.
STEP1
In first step you need to get the current url. See the code below
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<?php
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
?>
|
This code is a
php function which allows you to find out the current page URL.
You can get the Current page URL like this
|
<?php
echo curPageURL();
?>
|
This will print the current page URL. But for this tutorial we need to store it in a variable.
|
<?php
$cur = curPageURL();
?>
|
We’ve stored the current page URL in the
variable ‘$cur’.
Step 2
Now we need to split the URL according to ‘/’ and have to select the last part.
|
$parts = Explode('/', $cur);
$url = $parts[count($parts) - 1];
|
Note: if your URL is something like this
‘http://www.example.com/pages/about’ you’ve to use the above code as it
is, but if your URL is Like this ‘http://www.example.com/pages/about/’
you’ve to change the ‘-1′ to ‘-2′.
The above code will store last part of the URL in the variable $url for example ‘about’.
Step 3
Now all you need to do is save an image
in this name.
eg. ‘about.jpg’
Then go to your page and put the following code where you want your image to be placed.
|
<img src="path/to/image/<?php echo $url; ?>.jpg" />
|
Hurrah!!
if you go to that page you can see your image. Now
include all the above codes into each page where you want to show the images and place the image with the same name of
URL’s last part.
0 comments:
Post a Comment