Simulate file structure with PHP

I am running PHP on a shared Apache web server. I can edit the .htaccess file.

I am trying to simulate a file file structure that is actually missing. For example, I would like the URL: www.Stackoverflow.com/jimwiggly actually display www.StackOverflow.com/index.php?name=jimwiggly . I got halfway by editing the .htaccess file according to the instructions in this post: PHP: Serve pages without .php files in the file structure :

 RewriteEngine on RewriteRule ^jimwiggly$ index.php?name=jimwiggly 

This works well, as the URL bar still displays www.Stackoverflow.com/jimwiggly and the page is loading correctly, however all my relative links remain unchanged. I could go back and insert <?php echo $_GET['name'];?> Before each link, but it looks like there might be a better way. In addition, I suspect that my whole approach may be disconnected, should I go about it differently?

+3
source share
1 answer

I think the best way to do this is to accept MVC-style URL manipulations using URIs, not parameters.

In your htaccess use like:

 <IfModule mod_rewrite.c> RewriteEngine On #Rewrite the URI if there is no file or folder RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?/$1 [L] </IfModule> 

Then, in your PHP Script, you want to create a small class to read the URI and split it into segments, such as

 class URI { var $uri; var $segments = array(); function __construct() { $this->uri = $_SERVER['REQUEST_URI']; $this->segments = explode('/',$this->uri); } function getSegment($id,$default = false) { $id = (int)($id - 1); //if you type 1 then it needs to be 0 as arrays are zerobased return isset($this->segments[$id]) ? $this->segments[$id] : $default; } } 

Use as

http://mysite.com/posts/22/robert-pitt-shows-mvc-style-uri-access

 $Uri = new URI(); echo $Uri->getSegment(1); //Would return 'posts' echo $Uri->getSegment(2); //Would return '22'; echo $Uri->getSegment(3); //Would return 'robert-pitt-shows-mvc-style-uri-access' echo $Uri->getSegment(4); //Would return a boolean of false echo $Uri->getSegment(5,'fallback if not set'); //Would return 'fallback if not set' 

Now in MVC Usually http://site.com/controller/method/param , but in an application with a non-MVC style you can do http://site.com/action/sub-action/param

We hope this helps you move forward with your application.

+6
source

All Articles