URL rewriting, PHP templating and the $_GET array

别来无恙 提交于 2019-12-22 17:38:47

问题


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


回答1:


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');
} 
?>



回答2:


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!
}



回答3:


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.




回答4:


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;
    }
}



回答5:


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.



来源:https://stackoverflow.com/questions/7189803/url-rewriting-php-templating-and-the-get-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!