简体   繁体   中英

Simulate file structure with PHP

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

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

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

This works nicely insofar as the URL bar still displays www.Stackoverflow.com/jimwiggly and the correct page loads, however, all of my relative links remain unchanged. I could go back in and insert <?php echo $_GET['name'];?> before each link, but it seems like there might be a better way than that. Additionally, I suspect my whole approach might be off, should I be going about this differently?

I think the best way to do this is to adopt the MVC style url manipulation with the URI and not the params.

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 develop 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 like

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 There usually like http://site.com/controller/method/param but in a non MVC Style application you can do http://site.com/action/sub-action/param

Hope this helps you move forward with your application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM