Home > OS >  PHP subfolder used as home directory
PHP subfolder used as home directory

Time:12-12

I am coding a website with php, html, css and a few javascript. I am on localhost, more exactly LAMP server, and for me to access this "website" the url on the browser is http://localhost/website.

What I want is to have an subfolder that has a index.php. So I had made an index.php on the main folder that includes the subfolder/index.php and everything works great.

Now I want to create an about page on the subfolder (subfolder/about.php). However the url should be localhost/website/about.php and this doesn't work.

How can I have a subfolder like it was the main folder to display?

trying to simplify the question:

website/
    subfolder/
        index.php
        about.php
        products.php
        etc.php
    index.php

imaging that this above is the files directory, probably its possible to understand.

so the link should be website/about.php and not website/subfolder/about.php basically what I need is that the subfolder acts like it was the root folder of the website.

CodePudding user response:

just use this code

<?php
  $uri = urldecode(
 parse_url($_SERVER['REQUEST_URI'], 
 PHP_URL_PATH)
 );

 if ($uri !== '/' && 
 file_exists(__DIR__.'/subfolder'.$uri)) {
 return false;
 }

 require_once 
  __DIR__.'/subfolder/index.php';

CodePudding user response:

Simple front contoller:

website/index.php

<?php

switch ($_GET['page'] ?: 'index')
{
    case 'about':
        require 'website/subfolder/about.php';
    break;
    case 'products':
        require 'website/subfolder/products.php';
    break;
    default: // index
        require 'website/subfolder/index.php';
}

Then setup a front controller rewrite using an .htaccess file:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /website/index.php?page=$1 [QSA,L]

https://stackoverflow.com/a/26755631/451969

Now urls like these should indirect to your website/index.php front controller as a page GET variable:

website             # index
website/about       # about page
website/products    # products listing
  •  Tags:  
  • php
  • Related