CodeIgniter PHP 框架 - 需要获取查询字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2171185/
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
CodeIgniter PHP Framework - Need to get query string
提问by Siva
I'm creating an e-commerce site using CodeIgniter.
我正在使用CodeIgniter创建一个电子商务网站。
How should I get the query string?
我应该如何获取查询字符串?
I am using a Saferpaypayment gateway. The gateway response will be like this:
我正在使用Saferpay支付网关。网关响应将如下所示:
http://www.test.com/registration/success/?DATA=<IDP+MSGTYPE%3D"PayConfirm"+KEYID%3D"1-0"+ID%3D"KI2WSWAn5UG3vAQv80AdAbpplvnb"+TOKEN%3D"(unused)"+VTVERIFY%3D"(obsolete)"+IP%3D" 123.25.37.43"+IPCOUNTRY%3D"IN"+AMOUNT%3D"832200"+CURRENCY%3D"CHF"+PROVIDERID%3D"90"+PROVIDERNAME%3D"Saferpay+Test+Card"+ACCOUNTID%3D"99867-94913159"+ECI%3D"2"+CCCOUNTRY%3D"XX"%2F>&SIGNATURE=bc8e253e2a8c9ee0271fc45daca05eecc43139be6e7d486f0d6f68a356865457a3afad86102a4d49cf2f6a33a8fc6513812e9bff23371432feace0580f55046c
To handle the response I need to get the query string data.
为了处理响应,我需要获取查询字符串数据。
Sorry, I haven't explained the problem clearly. I am getting a 'Page not found' error while getting the response from the payment site after payment.
抱歉,我没有把问题解释清楚。付款后收到付款网站的响应时出现“找不到页面”错误。
I have tried enabling with uri_protocol = 'PATH_INFO'and enable_query_strings = 'TRUE'in config.php. While googling I found this won't work if I use htaccess rewrite.
我试过用uri_protocol = 'PATH_INFO'和enable_query_strings = 'TRUE'in启用config.php。在谷歌搜索时,我发现如果我使用 htaccess 重写,这将不起作用。
I have already tried changing the config entries, but it doesn't work.
我已经尝试更改配置条目,但它不起作用。
回答by Sarfraz
You can get it like this:
你可以这样得到它:
$this->input->get('some_variable', TRUE);
回答by Bretticus
I have been using CodeIgniter for over a year now. For the most part I really like it (I contribute to the forum and use it in every instance that I can) but I HATE the ARROGANCE of that statement in the manual:
我已经使用 CodeIgniter 一年多了。在大多数情况下,我真的很喜欢它(我为论坛做出贡献,并在我可以的任何情况下使用它),但我讨厌手册中该声明的傲慢:
Destroys the global GET array. Since CodeIgniter does not utilize GET strings, there is no reason to allow it.
销毁全局 GET 数组。由于 CodeIgniter 不使用 GET 字符串,因此没有理由允许它。
The presumption that you will never need GET in a CodeIgniter application is asinine! Already in just a few days, I've had to deal with post back pages from PayPal and ClickBank (I'm sure there are a million others.) Guess what, they use GET!!!
在 CodeIgniter 应用程序中永远不需要 GET 的假设是愚蠢的!几天后,我就不得不处理来自 PayPal 和 ClickBank 的回传页面(我确定还有一百万个其他页面。)猜猜看,他们使用 GET !!!
There are ways to stop this GET squashing, but they are things that tend to screw other things up. What you don't want to hear is that you have to recode all your views because you enabled querystrings and now your links are broken! Read the manual carefully on that option!
有一些方法可以阻止这种 GET 压缩,但它们往往会搞砸其他事情。您不想听到的是您必须重新编码所有视图,因为您启用了查询字符串,现在您的链接已损坏!仔细阅读有关该选项的手册!
One that I like (but didn't work because setting REQUEST_URI in config.php broke my site) is extending the Input class:
我喜欢的一个(但没有工作,因为在 config.php 中设置 REQUEST_URI 破坏了我的站点)正在扩展 Input 类:
class MY_Input extends CI_Input
{
function _sanitize_globals()
{
$this->allow_get_array = TRUE;
parent::_sanitize_globals();
}
}
But the best no-nonsense way is to test with print_r($_SERVER) at the URL where you need the GET variables. See which URI Protocol option shows your GET variables and use it.
但最好的严肃方法是在需要 GET 变量的 URL 上使用 print_r($_SERVER) 进行测试。查看哪个 URI 协议选项显示您的 GET 变量并使用它。
In my case, I can see what I need in REQUEST_URI
就我而言,我可以在 REQUEST_URI 中看到我需要的内容
// defeat stupid CI GET squashing!
parse_str($_SERVER['REQUEST_URI'], $_GET);
This places your query string back into the $_GET super global for that page instance (You don't have to use $_GET, it can be any variable.)
这会将您的查询字符串放回到该页面实例的 $_GET 超级全局中(您不必使用 $_GET,它可以是任何变量。)
EDIT
编辑
Since posting this I found that when using REQUEST_URI, you will lose your first query string array key unless you remove everything before the ?. For example, a URL like /controller/method?one=1&two=2 will populate the $_GET array in this example with array('method?one'=>1,'two'=>2). To get around this, I used the following code:
自从发布这篇文章后,我发现在使用 REQUEST_URI 时,除非您删除 ? 之前的所有内容,否则您将丢失第一个查询字符串数组键。例如,像 /controller/method?one=1&two=2 这样的 URL 将使用 array('method?one'=>1,'two'=>2) 填充本例中的 $_GET 数组。为了解决这个问题,我使用了以下代码:
parse_str(substr(strrchr($_SERVER['REQUEST_URI'], "?"), 1), $_GET);
I suppose I should have provided an example, so here goes:
我想我应该提供一个例子,所以这里是:
class Pgate extends Controller {
function postback() {
parse_str(substr(strrchr($_SERVER['REQUEST_URI'], "?"), 1), $_GET);
$receipt = $this->input->xss_clean($_GET['receipt']);
}
}
回答by Marc Trudel
If you want the unparsed query string:
如果您想要未解析的查询字符串:
$this->input->server('QUERY_STRING');
回答by Matt Borja
// 98% functional
parse_str($_SERVER['REQUEST_URI'], $_GET);
This in fact is the best way to handle the lack of support for $_GET query strings in CodeIgniter. I actually came up with this one on my own myself, but soon realized the same thing Bretticus did in that you had to slightly modify the way you treated the first variable:
这实际上是处理 CodeIgniter 中对 $_GET 查询字符串缺乏支持的最佳方法。实际上,我自己想出了这个,但很快意识到 Bretticus 所做的同样的事情,你必须稍微修改你处理第一个变量的方式:
// 100% functional
parse_str(substr(strrchr($_SERVER['REQUEST_URI'], "?"), 1), $_GET);
It was only going to be a matter of time before I got to it myself, but using this method is a better one-line solution to everything else out there, including modifying the existing URI library, is isolated to only the controller where it is applicable, and eliminates having to make any changes to the default configuration (config.php)
我自己解决这只是时间问题,但使用这种方法是一种更好的单行解决方案,包括修改现有的 URI 库,仅与控制器隔离。适用,并且无需对默认配置 (config.php) 进行任何更改
$config['uri_protocol'] = "AUTO";
$config['enable_query_strings'] = FALSE;
With this, you now have the following at your disposal:
有了这个,您现在可以使用以下内容:
/controller/method?field=value
/controller/method/?field=value
Verify the results:
验证结果:
print_r($_GET); // Array ( [field] => value )
回答by Phil Sturgeon
Open up application/config/config.php and set the following values:
打开 application/config/config.php 并设置以下值:
$config['uri_protocol'] = "PATH_INFO";
$config['enable_query_strings'] = TRUE;
Now query strings should work fine.
现在查询字符串应该可以正常工作。
回答by Stradivariuz
If you're using mod_rewrite to remove the index.php file, you can use the following code to obtain the GET variables (via $this->input->get()). Assuming the default configuration, name the file MY_Input.php and place it in your application/libraries directory.
如果您使用 mod_rewrite 删除 index.php 文件,则可以使用以下代码获取 GET 变量(通过 $this->input->get())。假设默认配置,将文件命名为 MY_Input.php 并将其放置在您的 application/libraries 目录中。
Usage: $this->input->get()
用法:$this->input->get()
class MY_Input extends CI_Input {
function My_Input()
{
parent::CI_Input();
// allow GET variables if using mod_rewrite to remove index.php
$CFG =& load_class('Config');
if ($CFG->item('index_page') === "" && $this->allow_get_array === FALSE)
{
$_GET = $this->_get_array();
}
}
/**
* Fetch an item from the GET array
*
* @param string $index
* @param bool $xss_clean
*/
function get($index = FALSE, $xss_clean = FALSE)
{
// get value for supplied key
if ($index != FALSE)
{
if (array_key_exists(strval($index), $_GET))
{
// apply xss filtering to value
return ($xss_clean == TRUE) ? $this->xss_clean($_GET[$index]) : $_GET[$index];
}
}
return FALSE;
}
/**
* Helper function
* Returns GET array by parsing REQUEST_URI
*
* @return array
*/
function _get_array()
{
// retrieve request uri
$request_uri = $this->server('REQUEST_URI');
// find query string separator (?)
$separator = strpos($request_uri, '?');
if ($separator === FALSE)
{
return FALSE;
}
// extract query string from request uri
$query_string = substr($request_uri, $separator + 1);
// parse query string and store variables in array
$get = array();
parse_str($query_string, $get);
// apply xss filtering according to config setting
if ($this->use_xss_clean === TRUE)
{
$get = $this->xss_clean($get);
}
// return GET array, FALSE if empty
return (!empty($get)) ? $get : FALSE;
}
}
回答by AldoZumaran
Set your config file
设置你的配置文件
$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO';
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = FALSE;
and .htaccess file (root folder)
和 .htaccess 文件(根文件夹)
<IfModule mod_rewrite.c>
Options +FollowSymLinks
Options -Indexes
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond !^(index\.php)
RewriteRule ^(.*)$ index.php [L]
</IfModule>
Now you can use
现在你可以使用
http://example.com/controller/method/param1/param2/?par1=1&par2=2&par3=x
http://example.com/controller/test/hi/demo/?par1=1&par2=2&par3=X
server side:
服务器端:
public function test($param1,$param2)
{
var_dump($param1); // hi
var_dump($param2); // demo
var_dump($this->input->get('par1')); // 1
var_dump($this->input->get('par2')); // 2
var_dump($this->input->get('par3')); // X
}
回答by Kinjal Dixit
Thanks to all other posters. This is what hit the spot for me:
感谢所有其他海报。这对我来说很重要:
$qs = $_SERVER['QUERY_STRING'];
$ru = $_SERVER['REQUEST_URI'];
$pp = substr($ru, strlen($qs)+1);
parse_str($pp, $_GET);
echo "<pre>";
print_r($_GET);
echo "</pre>";
Meaning, I could now do:
意思是,我现在可以这样做:
$token = $_GET['token'];
In the .htaccess i had to change:
在 .htaccess 我不得不改变:
RewriteRule ^(.*)$ /index.php/ [L]
to:
到:
RewriteRule ^(.*)$ /index.php?/ [L]
回答by Brodie Hodges
You can create a pre_system hook. In the hook class you create, you can grab the desired query params and add them to the $_POST for normal CI processing. I did this for a jQuery Ajax helper.
您可以创建一个 pre_system 挂钩。在您创建的钩子类中,您可以获取所需的查询参数并将它们添加到 $_POST 以进行正常的 CI 处理。我是为一个 jQuery Ajax 助手做的。
For instance:
例如:
(Name this file autocomplete.php or whatever you put as the file name in the hook)
(将此文件命名为 autocomplete.php 或任何您在挂钩中放置的文件名)
<?php
/*
By Brodie Hodges, Oct. 22, 2009.
*/
if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Make sure this file is placed in your application/hooks/ folder.
*
* jQuery autocomplete plugin uses query string. Autocomplete class slightly modified from excellent blog post here:
* http://czetsuya-tech.blogspot.com/2009/08/allowing-url-query-string-in.html
* Ajax autocomplete requires a pre_system hook to function correctly. Add to your
* application/config/hooks.php if not already there:
$hook['pre_system'][] = array(
'class' => 'Autocomplete',
'function' => 'override_get',
'filename' => 'autocomplete.php',
'filepath' => 'hooks',
'params' => array()
);
*
*
*/
class Autocomplete {
function override_get() {
if (strlen($_SERVER['QUERY_STRING']) > 0) {
$temp = @array();
parse_str($_SERVER['QUERY_STRING'], $temp);
if (array_key_exists('q', $temp) && array_key_exists('limit', $temp) && array_key_exists('timestamp', $temp)) {
$_POST['q'] = $temp['q'];
$_POST['limit'] = $temp['limit'];
$_POST['timestamp'] = $temp['timestamp'];
$_SERVER['QUERY_STRING'] = "";
$_SERVER['REDIRECT_QUERY_STRING'] = "";
$_GET = @array();
$url = strpos($_SERVER['REQUEST_URI'], '?');
if ($url > -1) {
$_SERVER['REQUEST_URI'] = substr($_SERVER['REQUEST_URI'], 0, $url);
}
}
}
}
}
?>
回答by netricate
You could make a rule in your .htaccess to prevent your MOD_REWRITE from firing on that specific page. That should allow you to use the _GET.
您可以在 .htaccess 中制定规则以防止您的 MOD_REWRITE 在该特定页面上触发。这应该允许您使用 _GET。

