如何通过 PHP 在页面正文中获取 URL 参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4744746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 14:13:53  来源:igfitidea点击:

How to get URL argument in Page body by PHP?

phpdrupal

提问by ohho

On a Drupal site, PHP code is enabled for Page body content. How can I get the argument and its value in PHP code? For example, I'd like to get refand 33002from:

在 Drupal 站点上,页面正文内容启用了 PHP 代码。如何在 PHP 代码中获取参数及其值?例如,我想获得ref33002来自:

http://example.com/node/1?ref=33002

In the following code:

在以下代码中:

<?php 
  print arg(0);
  print arg(1);
  print arg(2);
  print arg(3);
?>

I can get nodeand 1, but nothing about refor 33002.

我可以得到nodeand 1,但没有关于refor 33002

Thanks!

谢谢!

回答by klidifia

You can use drupal_get_query_parameters()as follows:

您可以使用drupal_get_query_parameters()如下:

$params = drupal_get_query_parameters();

if (isset($params['ref']) && is_numeric($params['ref'])) {
  var_dump(check_plain($params['ref']));
}

回答by crowicked

Use this:

用这个:

<?php
$a=$_REQUEST['ref'];
echo "The value of the ref parameter is ".$a;
?>

回答by marcvangend

The solution by crowicked works, but "the Drupal way" is to pass the ref value as a url argument, ie:

crowicked 的解决方案有效,但“Drupal 方式”是将 ref 值作为 url 参数传递,即:

http://example.com/node/1/33002

Now you can access the ref value using the arg() function:

现在您可以使用 arg() 函数访问 ref 值:

$ref = arg(2);

Of course an approach like this can only work if the ref value is always the third argument.

当然,只有当 ref 值始终是第三个参数时,这样的方法才有效。

Even though the code above works, it is not recommended to place php scripts in the node body. It makes your site harder to maintain and debug. The day will come when an editor deletes your php node by accident, thus breaking your site.

即使上面的代码有效,也不建议在节点主体中放置 php 脚本。它使您的站点更难维护和调试。有一天,编辑器会意外删除您的 php 节点,从而破坏您的网站。

If you have a php script that you want to run, the best way is to add a simple custom module to your site which implements hook_menu. Have a look at the Menu Example moduleor this hello world moduleto learn more about hook_menu.

如果您有一个想要运行的 php 脚本,最好的方法是向您的站点添加一个简单的自定义模块,该模块实现了 hook_menu。查看菜单示例模块或这个hello world 模块以了解有关 hook_menu 的更多信息。

Lastly, regardless of the method you choose (php nodes or a custom module), always make sure to sanitize url input, for instance with check_plain().

最后,无论您选择哪种方法(php 节点或自定义模块),请始终确保清理 url 输入,例如使用check_plain()