PHP将URL传递给index.php [英] PHP pass url to index.php

查看:88
本文介绍了PHP将URL传递给index.php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该非常简单,但是我希望能够像php框架一样使用url作为变量。

This should be really simple, but I want to be able to use the url as a variable like the php frameworks do.

mywebsite.com/hello-world

我希望我的index.php看到 hello-world 作为变量,我希望index.php能够加载。这是通过php完成还是我必须使用htaccess文件?

I want my index.php to see "hello-world" as a variable and I want index.php to load. Is this done through php or do I have to use a htaccess file?

许多php框架都使用url将消息发送到索引文件...。 。

Many php frameworks use urls to send a message to the index file... for example...

mysite.com/controller/view

我如何通过php自己路由这些?

How would I route these myself via php?

一点帮助?

推荐答案

有2个步骤:


  1. 使用<$ c $重写网址c> .htaccess 文件(在Linux上)。您需要确保所有请求都发送到您的php文件,因此您需要将所有不存在的文件和文件夹的所有请求重写到您的php文件;

  2. 在您的php文件中,您需要分析url(例如使用 $ _ SERVER ['REQUEST_URI'] )并根据其内容采取措施。

  1. Rewrite the url using an .htaccess file (on 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;
  2. In your php file you analyze the url (using for example $_SERVER['REQUEST_URI']) and take action depending on its contents.

对于步骤1,您可以使用类似以下内容的东西:

For step 1. you could use something like:

RewriteEngine On
RewriteBase /

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

然后在第2步的php文件中,您在 $ _ GET ['url'] 。

And then in your php file in step 2. you have the requested url in $_GET['url'].

编辑:

如果只想重写某些子目录,还可以使用以下规则:

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]

一些详细信息:


  • ^(。*)$ 捕获起始 ^ 和结尾 $ 。它们使用括号捕获,因此您可以在查询字符串中使用它们,例如 $ 1 。在编辑的示例中,仅捕获 .... / rewrite / 之后的部分;

  • <$ c $之间的选项c> [...] 表示它是 L 最后要处理的规则和 QSA 原始查询字符串也已添加到新的url中。这意味着,如果您的网址是 / hello-world?some_var = 4 ,则 some_var 变量将附加到重写后网址: your_file.php?url = hello-world& some_var = 4

  • ^(.*)$ captures everything (all characters) between the start ^ and the end $. They are captured using the parenthesis so that you can use them in the query string like $1. In the edited example, only the section after ..../rewrite/ gets captured;
  • 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. 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.

这篇关于PHP将URL传递给index.php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆