简体   繁体   English

PHP将url传递给index.php

[英]PHP pass url to index.php

This should be really simple, but I want to be able to use the url as a variable like the php frameworks do. 这应该非常简单,但我希望能够将url用作php框架之类的变量。

mywebsite.com/hello-world

I want my index.php to see "hello-world" as a variable and I want index.php to load. 我希望我的index.php看到“hello-world”作为变量,我希望index.php加载。 Is this done through php or do I have to use a htaccess file? 这是通过PHP完成还是我必须使用htaccess文件?

Many php frameworks use urls to send a message to the index file... for example... 许多php框架使用url将消息发送到索引文件...例如......

mysite.com/controller/view

How would I route these myself via php? 我如何通过PHP自己路由?

A little help? 一点帮助?

There are 2 steps: 有两个步骤:

  1. Rewrite the url using an .htaccess file (on linux). 使用.htaccess文件重写url(在linux上)。 You need to make sure all requests go to your php file so you will need to rewrite all requests to non-existing files and folders to your php file; 您需要确保所有请求都转到您的php文件,因此您需要将对不存在的文件和文件夹的所有请求重写为您的php文件;
  2. In your php file you analyze the url (using for example $_SERVER['REQUEST_URI'] ) and take action depending on its contents. 在你的php文件中,你分析url(使用例如$_SERVER['REQUEST_URI'] )并根据其内容采取行动。

For step 1. you could use something like: 对于第1步,您可以使用以下内容:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ your_file.php?url=$1 [L,QSA]

And then in your php file in step 2. you have the requested url in $_GET['url'] . 然后在步骤2中的php文件中,您在$_GET['url']有所请求的URL。

Edit: 编辑:

If you want to rewrite only certain sub-directories, you could also use a rule like: 如果您只想重写某些子目录,您还可以使用如下规则:

RewriteRule ^sub/dir/to/rewrite/(.*)$ your_file.php?url=$1 [L,QSA]

Some details: 一些细节:

  • ^(.*)$ captures everything (all characters) between the start ^ and the end $ . ^(.*)$捕获start ^和end $之间的所有内容(所有字符)。 They are captured using the parenthesis so that you can use them in the query string like $1 . 使用括号捕获它们,以便您可以在查询字符串中使用它们,如$1 In the edited example, only the section after ..../rewrite/ gets captured; 在编辑的示例中,仅捕获..../rewrite/之后的部分;
  • The options between [ ... ] mean that it is the L Last rule to process and QSA that the original query string is also added to the new url. [ ... ]之间的选项意味着它是要处理的L Last规则和QSA ,原始查询字符串也被添加到新URL。 That means that if your url is /hello-world?some_var=4 that the some_var variable gets appended to the rewritten url: your_file.php?url=hello-world&some_var=4 . 这意味着如果你的url是/hello-world?some_var=4some_var变量会被附加到重写的url: your_file.php?url=hello-world&some_var=4

This sort of rerouting must be done on the webserver level, either in the Apache config files for your server or (more likely) through an .htaccess file. 这种重新路由必须在Web服务器级别上完成,或者在服务器的Apache配置文件中完成,或者(更有可能)通过.htaccess文件完成。

This is the .htaccess file I use on my own site to do this sort of re-routing: 这是我在自己的网站上使用的.htaccess文件,用于执行此类重新路由:

# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f

#Route everything else through index.php
RewriteRule .* index.php/?$0 [PT,L]

Then in index.php I look up the URLs in my database to pull the page content: 然后在index.php我查找数据库中的URL以获取页面内容:

if(isset($_SERVER['REQUEST_URI']) and strlen($_SERVER['REQUEST_URI']) > 1)
    $requested_url = substr($_SERVER['REQUEST_URI'], 1);
else
    $requested_url = 'home';

What you want to achieve is called the "Front Controller" pattern. 您想要实现的目标称为“前端控制器”模式。 It's usually done with the use of Apache's mod_rewrite . 它通常使用Apache的mod_rewrite Without URL rewriting you can still do something similar, but your URLs would look like this: 如果没有URL重写,您仍然可以执行类似的操作,但您的网址将如下所示:

mysite.com/index.php/controller/view

Instead of: mysite.com/controller/view as you want. 而不是: mysite.com/controller/view你想要的。

Here's a minimal .htaccess file to do the URL rewriting: 这是一个最小的.htaccess文件来进行URL重写:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

Then you parse the URL from $_SERVER['REQUEST_URI'] but remember to strip off any GET parameters at the end when determining the view name. 然后你解析来自$_SERVER['REQUEST_URI']的URL,但是在确定视图名称时记得在最后去除任何GET参数。

I personally wanted something like this recently without a full-fledged framework so I used this micro-framework just to do the routing, and it worked very nicely: 我个人最近想要这样的东西没有一个完整的框架,所以我使用这个微框架来做路由,它工作得非常好:

http://www.slimframework.com/ http://www.slimframework.com/

Then you can write your own controller class and set up the routing; 然后你可以编写自己的控制器类并设置路由; here's the code I used: 这是我使用的代码:

$app = new \Slim\Slim();

$app->map('/:controller(/:action)', 'dispatchControllerAction')
    ->via('GET', 'POST');

function dispatchControllerAction($controllerName, $action='index') {
    //multi-word controllers and actions should be hyphen-separated in the URL
    $controllerClass = 'Controllers\\'.ucfirst(camelize($controllerName, '-'));
    $controller = new $controllerClass;
    $controller->execute(camelize($action, '-'));
}

/**
 * Adapted from the Kohana_Inflector::camelize function (from the Kohana framework)
 * Added the $altSeparator parameter
 * 
 * Makes a phrase camel case. Spaces and underscores will be removed.
 *
 *     $str = Inflector::camelize('mother cat');     // "motherCat"
 *     $str = Inflector::camelize('kittens in bed'); // "kittensInBed"
 *
 * @param   string  $str    phrase to camelize
 * @param   string  $altSeparator  Alternate separator to be parsed in addition to spaces. Defaults to an underscore.
 *      If your string is hyphen-separated (rather than space- or underscore-separated), set this to a hyphen
 * @return  string
 */
function camelize($str, $altSeparator='_')
{
    $str = 'x'.strtolower(trim($str));
    $str = ucwords(preg_replace('/[\s'.$altSeparator.']+/', ' ', $str));

    return substr(str_replace(' ', '', $str), 1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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