在 PHP 中解码查询字符串

发布于 2024-07-28 20:59:39 字数 745 浏览 8 评论 0原文

好的,我已经使用 mod_rewrite 和 PHP 编写了 REST API 实现。 我正在通过 HTTP DELETE 请求的正文接受查询字符串(...集体抱怨?)。 抛开关于前面两个陈述是否明智的争论,我发现 PHP 不会自动解析 DELETE 请求的请求正文(即 $_POST 为空,尽管表单编码的查询字符串出现在请求正文中)。 这并没有让我感到特别惊讶。 让我感到惊讶的是,我一直无法找到用于解析查询字符串的内置 PHP 函数? 我是否只是忽略了一些事情? 我可以做类似的事情:

public function parseQS($queryString, &$postArray){
  $queryArray = explode('&', $queryString);
  for($i = 0; $i < count($queryArray); $i++) {
    $thisElement = split('=', $queryArray[$i]);
    $postArray[$thisElement[0]] = htmlspecialchars(urldecode($thisElement[1]));
  }
}

...没有内置的 PHP 来处理这个问题,这似乎很奇怪。 另外,我怀疑我不应该使用 htmlspecialcharacters & urldecode 来清理表单编码值...这是一种不同类型的编码,但我也无法辨别应该使用哪个 PHP 函数来解码表单编码数据。

任何建议将不胜感激。

Okay, so I've written a REST API implementation using mod_rewrite and PHP. I'm accepting a query string via the body of HTTP DELETE requests (... collective groan?). Arguments about the wisdom of both previous statements aside, what I've found is that PHP doesn't automatically parse the request body of DELETE requests (i.e. $_POST is empty despite form-encoded query string appearing in body of request). This didn't particularly surprise me. What I did find surprising was that I've been unable to find a built-in PHP function for parsing a query string?? Have I simply overlooked something? I can do something like:

public function parseQS($queryString, &$postArray){
  $queryArray = explode('&', $queryString);
  for($i = 0; $i < count($queryArray); $i++) {
    $thisElement = split('=', $queryArray[$i]);
    $postArray[$thisElement[0]] = htmlspecialchars(urldecode($thisElement[1]));
  }
}

... it just seems odd that there wouldn't be a PHP built-in to handle this. Also, I suspect I shouldn't be using htmlspecialcharacters & urldecode to scrub form-encoded values... it's a different kind of encoding, but I'm also having trouble discerning which PHP function I should be using to decode form-encoded data.

Any suggestions will be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

魂牵梦绕锁你心扉 2024-08-04 21:00:11
public function parseQS($queryString, &$postArray){
  parse_str($queryString, $postArray);
}

;-)

public function parseQS($queryString, &$postArray){
  parse_str($queryString, $postArray);
}

;-)

三寸金莲 2024-08-04 21:00:07

我构建了一个简单的库来解析查询字符串,以便为我的其余 api 进行过滤、排序和选择字段。 odata 的原始版本。
查询字符串转换为对象和/或对象数组。
例如:

过滤器:

www.example.com/resource?@filters=filedName operator 'the value'

可用运算符 eq 、ne、gt、lt、like 、ilike 、le、ge

$filtersResult = $parser->filters();

$filtersResult[0]->field // name
$filtersResult[0]->operator // eq
$filtersResult[0]->getOperator() // "="
$filtersResult[0]->value // 'what ever'

进行排序:

//name is asc , surname desc
@orderby=name,-surname
$sorts = $parser->orderBy() // you can set defaults if u want
$sorts[0]->filed //name 
$sorts[0]->direction //asc

$sorts[1]->filed //surname 
$sorts[1]->direction //desc

用于嵌入:

@embed=resourceOne(@fields=name,code)(@filters=nameembed eq 'what ever'),mobiles(@orderby=sortFieldOne)

$embedResult = $parser->embed(); //return array of embed each              
//object contains filters , sort , fields | empty array 

$embedResult[0]->resource // resourceOne
$embedResult[0]->fields // array of fields  [name,code]
$embedResult[0]->filters // array of filters or empty array 

$embedResult[1]->resource // mobiles
$embedResult[1]->orderBy // array of order by objects

easyparser

I've built a simple library to parse query string to filter,sort,and select fields for my rest api. a naive version of odata .
the query string transformed to object and or arrays of objects.
for ex :

filters:

www.example.com/resource?@filters=filedName operator 'the value'

available operators eq ,ne, gt, lt, like ,ilike , le, ge

$filtersResult = $parser->filters();

$filtersResult[0]->field // name
$filtersResult[0]->operator // eq
$filtersResult[0]->getOperator() // "="
$filtersResult[0]->value // 'what ever'

to sort :

//name is asc , surname desc
@orderby=name,-surname
$sorts = $parser->orderBy() // you can set defaults if u want
$sorts[0]->filed //name 
$sorts[0]->direction //asc

$sorts[1]->filed //surname 
$sorts[1]->direction //desc

for embed:

@embed=resourceOne(@fields=name,code)(@filters=nameembed eq 'what ever'),mobiles(@orderby=sortFieldOne)

$embedResult = $parser->embed(); //return array of embed each              
//object contains filters , sort , fields | empty array 

$embedResult[0]->resource // resourceOne
$embedResult[0]->fields // array of fields  [name,code]
$embedResult[0]->filters // array of filters or empty array 

$embedResult[1]->resource // mobiles
$embedResult[1]->orderBy // array of order by objects

easyparser

黑色毁心梦 2024-08-04 21:00:04

https://www.php.net/manual/en/function。 parse-url.php

parse_url 将帮助您获取 DOCUMENT_URI 中包含实际查询的部分。

然后,您可以将该部分传递给 parse_str 以从查询中提取单个元素。

https://www.php.net/manual/en/function。解析-str.php

https://www.php.net/manual/en/function.parse-url.php

parse_url will help you grab the portion of the DOCUMENT_URI that contains the actual query.

You can then pass that section off to parse_str to extract individual elements from the query.

https://www.php.net/manual/en/function.parse-str.php

や莫失莫忘 2024-08-04 21:00:01

您可以使用parse_str函数

parse_str($queryString, $args);

You can use the parse_str function:

parse_str($queryString, $args);
挽清梦 2024-08-04 20:59:57

parse_str 适合简单的事情,但它与 PHP 创建 $_GET 魔术变量的构建方式不同。 为什么?!? 我不知道。 我已经开发了自己的版本,我相信它与 PHP 的解析完全匹配(如果您能找到任何其他情况的示例,请告诉我)。

function betterParseStr( $string )
{
    return array_reduce( explode( "&", $string ), function( $array, $string_piece ) {
        if( $string_piece === "" ) return $array;
        $equal_offset = strpos( $string_piece, "=" );
        if( $equal_offset === FALSE ) {
            $key = urldecode( $string_piece );
            $value = "";
        } else {
            $key = urldecode( substr( $string_piece, 0, $equal_offset ) );
            $value = urldecode( substr( $string_piece, $equal_offset + 1 ) );
        }
        if( preg_match( "/^([^\[]*)\[([^\]]*)](.*)$/", $key, $matches ) ) {
            $key_path = array( $matches[1], $matches[2] );
            $rest = $matches[3];
            while( preg_match( "/^\[([^\]]*)](.*)$/", $rest, $matches ) ) {
                $key_path[] = $matches[1];
                $rest = $matches[2];
            }
        } else {
            //replace first [ for _
            //why?!? idk ask PHP it does
            //Example: ?key[[=value -> array( "key_[" => "value" )
            $key_path = array( preg_replace('/\[/', '_', $key, 1 ) );
        }
        if( strlen( $key_path[0] ) > 0 && substr( $key_path[0], 0, 1 ) !== "[" ) {
            $current_node = &$array;
            $last_key = array_pop( $key_path );
            $resolve_key = function( $key, array $array ) {
                if( $key === "" || $key === " " ) {
                    $int_array = array_filter( array_keys( $array ), function( $key ) { return is_int( $key ); } );
                    $key = $int_array ? max( $int_array ) + 1 : 0;
                }
                return $key;
            };
            foreach( $key_path as $key_path_piece ) {
                $key_path_piece = $resolve_key( $key_path_piece, $current_node );
                if( ! array_key_exists( $key_path_piece, $current_node ) || ! is_array( $current_node[$key_path_piece] ) ) {
                    $current_node[$key_path_piece] = array();
                }
                $current_node = &$current_node[$key_path_piece];
            }
            $current_node[$resolve_key( $last_key, $current_node )] = $value;
        }
        return $array;
    }, array() );
}

parse_str is fine for simple stuff but it's not the same as PHP's built way of creating the $_GET magic variable. Why?!? I have no idea. I have developed my own version that I believe matches PHP's parsing exactly (let me know if you can find any examples that show otherwise).

function betterParseStr( $string )
{
    return array_reduce( explode( "&", $string ), function( $array, $string_piece ) {
        if( $string_piece === "" ) return $array;
        $equal_offset = strpos( $string_piece, "=" );
        if( $equal_offset === FALSE ) {
            $key = urldecode( $string_piece );
            $value = "";
        } else {
            $key = urldecode( substr( $string_piece, 0, $equal_offset ) );
            $value = urldecode( substr( $string_piece, $equal_offset + 1 ) );
        }
        if( preg_match( "/^([^\[]*)\[([^\]]*)](.*)$/", $key, $matches ) ) {
            $key_path = array( $matches[1], $matches[2] );
            $rest = $matches[3];
            while( preg_match( "/^\[([^\]]*)](.*)$/", $rest, $matches ) ) {
                $key_path[] = $matches[1];
                $rest = $matches[2];
            }
        } else {
            //replace first [ for _
            //why?!? idk ask PHP it does
            //Example: ?key[[=value -> array( "key_[" => "value" )
            $key_path = array( preg_replace('/\[/', '_', $key, 1 ) );
        }
        if( strlen( $key_path[0] ) > 0 && substr( $key_path[0], 0, 1 ) !== "[" ) {
            $current_node = &$array;
            $last_key = array_pop( $key_path );
            $resolve_key = function( $key, array $array ) {
                if( $key === "" || $key === " " ) {
                    $int_array = array_filter( array_keys( $array ), function( $key ) { return is_int( $key ); } );
                    $key = $int_array ? max( $int_array ) + 1 : 0;
                }
                return $key;
            };
            foreach( $key_path as $key_path_piece ) {
                $key_path_piece = $resolve_key( $key_path_piece, $current_node );
                if( ! array_key_exists( $key_path_piece, $current_node ) || ! is_array( $current_node[$key_path_piece] ) ) {
                    $current_node[$key_path_piece] = array();
                }
                $current_node = &$current_node[$key_path_piece];
            }
            $current_node[$resolve_key( $last_key, $current_node )] = $value;
        }
        return $array;
    }, array() );
}
疯到世界奔溃 2024-08-04 20:59:54

有一个函数可以做到这一点 - http://php.net/parse_str。 由于 PHP 必须自己完成此操作,因此没有理由不将其开放以供 API 中使用。

将字符串解析为变量void
parse_str (字符串$str [,数组&$arr])

像查询一样解析 str
通过 URL 传递的字符串并设置
当前范围内的变量。

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

There is a function that does it - http://php.net/parse_str. Since PHP has to do this for itself, there's no reason not to also open it up for use in the API.

Parses the string into variables void
parse_str ( string $str [, array &$arr])

Parses str as if it were the query
string passed via a URL and sets
variables in the current scope.

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
风筝有风,海豚有海 2024-08-04 20:59:51

parse_str。 名字不好,但做你想做的事。 请注意,它没有返回任何内容,第二个参数是通过引用传递的。

There's parse_str. Bad name, but does what you want. And notice that it returns nothing, the second argument is passed by reference.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文