I have an index.php file in the top level with other files such as "login.php", "register.php" in a folder called includes. The folder hierarchy looks like this:
index.php
includes/
register.php
login.php
css/
style.css
images/
image.png
How can I set the url to something like http://www.mydomain.com/register which then from within the index.php page calls (includes) the register.php page?
Is this the best way to go about it?
Thanks
Mike
If your server is Apache:
Create on root folder file ".htaccess"
#.htaccess
RewriteEngine On
Options +FollowSymlinks
RewriteRule /register index.php?mode=register
//index.php
<?php
if(isset($_GET['mode']=='register')){
include('includes/register.php');
}
?>
Well, so long as the URL stub (i.e. /register) is always going to be the same as the file name you want to include, you could do this using Apache's mod_rewrite
.
However, if you want to change the URL stub to something other than the filename you want to include, why not do this:
// Get the URL stub:
$url_stub = $_SERVER['REQUEST_URI'];
define('INCLUDE_PATH', 'includes/');
switch($url_stub)
{
case 'register':
include(INCLUDE_PATH . 'register.php');
break;
case 'login':
include(INCLUDE_PATH . 'login.php');
break;
default:
// Output whatever the standard Index file would be here!
}
using mod_rewrite:
RewriteRule ^register index.php?page=register
RewriteRule ^login index.php?page=login
index.php:
<?php
include('includes/'.$_GET['pagename'].'.php');
?>
EDIT:
For security reasons, see also arnouds comment below.
You can use apache rewrite rules to do that: (place this in a .htaccess file in the same directoyr than index.php)
RewriteEngine On
RewriteRule ^/register$ index.php?page=register
And in index.php:
$pages = scandir('includes');
if (isset($_GET['page'])) {
$page = $_GET['page'] . '.php';
if (in_array($page, $pages)) {
include $page;
}
}
You can write a .htaccess file with something like this:
RewriteEngine On
RewriteRule ^([a-z]+)/?$ /index.php?include=$1 [PT,QSA]
and the index.php file with:
include('includes/'.$_GET['include'].'.php');
Of course you can adapt this code to what you need.