URL rewriting, PHP templating and the $_GET array

2019-05-21 14:16发布

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

5条回答
我想做一个坏孩纸
2楼-- · 2019-05-21 14:34

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');
} 
?>
查看更多
放荡不羁爱自由
3楼-- · 2019-05-21 14:39

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;
    }
}
查看更多
狗以群分
4楼-- · 2019-05-21 14:43

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.

查看更多
我只想做你的唯一
5楼-- · 2019-05-21 14:49

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!
}
查看更多
仙女界的扛把子
6楼-- · 2019-05-21 14:54

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.

查看更多
登录 后发表回答