Josue Espinosa
Josue Espinosa

Reputation: 5089

Create variable based on URL

Let's say I have a website at www.hostname.com/example. I would like to create a page, that generates based off of any extension of the original url. For example, I would have a page called setup.php. If someone were to go to www.hostname.com/example/xyz, it would load setup.php, and utilize xyz as a variable to customize setup.php. Is this possible? I have tried searching google, but have found no results. Any thoughts?

Upvotes: 0

Views: 76

Answers (2)

Justin
Justin

Reputation: 1329

Take for example the url http://www.noticeeverything.com/news/. You could grab just the string "news" like this:

var url = window.location.href; 
var str = url.substring(32, 36); 
console.log(str);

Or, without having to determine the index of the substring you want:

var url = window.location.href; 
var str = url.replace('http://www.noticeeverything.com/news/', 'news'); 
console.log(str);

Or, if you don't know what the url is specifically, but expect it to follow the same pattern (i.e. 'http://www.something.com/something/'):

var pattern = /[a-z]+/; 
var url = window.location.href;
var newString = url.replace("http://www.", '').replace(pattern, '').replace('.com/', '').replace('/', '');
console.log(newString);

Hope that helps.

Upvotes: 1

Al.G.
Al.G.

Reputation: 4406

Make a file called .htaccess and place it in the main directory. Then put this code in it:

RewriteEngine on
RewriteBase /
RewriteRule ^(.*)$ setup.php?data=$1 [QSA,L]

Now whatever url you open, the file setup.php will be executed and you can get the requested data with the $_GET['data'] variable. For example:

<?php
$data = $_GET['data'];
if($data === 'xyz') {
echo "<b>xyz</b> is requested!";
include "xyz.php";
}
else {
echo "error 404: page not found";
}
?>

Upvotes: 1

Related Questions