在php中读取URL中的变量作为函数

时间:2015-06-25 09:56:07

标签: php url

本周开始学习php并有很多疑问,但这是其中一个我找不到解决方案(也许我不知道正确的搜索关键字)。

是否可以将URL中的变量作为php文件中的函数读取, 例如:

  http://mywebsite.com/demo_app/phone_api/login/harsha/harshapass

这里demo_app是文件夹,phone_api是php文件,我想调用函数login,其中harsha和harshapass是该函数的参数。

2 个答案:

答案 0 :(得分:1)

You'll need 2 things for this.

The first is mod_rewrite, this is an apache module. With this module you can rewrite the URL like you want, so that /demo_app/phone_api/ will redirect to your php file.

I advice that you read a tutorial somewhere about this, for example here.

Second thing is that you need to parse the URL.

With $_SERVER['REQUEST_URI'] you get the URL. With explode and/or preg_match you can parse this string into the parts you want (function, parameters, whatever).

If you have a more specific question about this, you can ask this here (in a new topic).

Good luck!

答案 1 :(得分:0)

您是否考虑将值作为$_GET变量发送并在页面中检索它们,如下所示:

  http://mywebsite.com/demo_app/phone_api?login=login&harsha=harsha&harshapass=harshapass

因此您可以在phone_api.php页面中获取值:

$login = $_GET['login'];
$harsha = $_GET['harsha'];
$harshapass = $_GET['harshapass'];
$login($harsha, $harshapass){
  //your function code.
}

也许这样会更容易。