php string to query string

Get URL query string parameters

What is the «less code needed» way to get parameters from a URL query string which is formatted like the following?

Output should be: myqueryhash

I am aware of this approach:

php string to query string. Смотреть фото php string to query string. Смотреть картинку php string to query string. Картинка про php string to query string. Фото php string to query string

11 Answers 11

$_SERVER[‘QUERY_STRING’] contains the data that you are looking for.

DOCUMENTATION

php string to query string. Смотреть фото php string to query string. Смотреть картинку php string to query string. Картинка про php string to query string. Фото php string to query string

php string to query string. Смотреть фото php string to query string. Смотреть картинку php string to query string. Картинка про php string to query string. Фото php string to query string

The PHP way to do it is using the function parse_url, which parses a URL and return its components. Including the query string.

php string to query string. Смотреть фото php string to query string. Смотреть картинку php string to query string. Картинка про php string to query string. Фото php string to query string

The function parse_str() automatically reads all query parameters into an array.

EDIT

php string to query string. Смотреть фото php string to query string. Смотреть картинку php string to query string. Картинка про php string to query string. Фото php string to query string

If you want the whole query string:

I will recommended best answer as

The above example will output:

This code and notation is not mine. Evan K solves a multi value same name query with a custom function 😉 is taken from:

It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields. If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them:

Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect.

This can be confusing for anyone who’s used to the CGI standard, so keep it in mind. As an alternative, I use a «proper» querystring parser function:

Источник

http_build_query

http_build_query — Генерирует URL-кодированную строку запроса

Описание

Генерирует URL-кодированную строку запроса из предоставленного ассоциативного (или индексированного) массива.

Список параметров

Может быть массив или объект, содержащий свойства.

Если data массив, то он может быть простой одномерной структурой или массивом массивов (который, в свою очередь, может содержать другие массивы).

Если data объект, тогда только общедоступные свойства будут включены в результат.

Если числовые индексы используются в базовом массиве и этот параметр указан, то он будет добавлен к числовому индексу для элементов только в базовом массиве.

Это позволяет обеспечить допустимые имена переменных, в которые позже данные будут декодированы PHP или другим CGI-приложением.

arg_separator.output используется в качестве разделителя аргументов, но может быть переопределён путём указания этого параметра.

Возвращаемые значения

Возвращает URL-кодированную строку.

Примеры

Пример #1 Простой пример использования http_build_query()

Результат выполнения данного примера:

Пример #2 Пример использования http_build_query() с числовыми индексами элементов.

Результат выполнения данного примера:

Пример #3 Пример использования http_build_query() с многомерными массивами

Результат выполнения данных примеров: (символы перенесены для удобства чтения)

Только числовой индексированный элемент «CEO» в базовом массиве получил префикс. Другие числовые индексы, найденные в pastimes, не требуют строкового префикса, чтобы быть допустимыми именами переменных.

Пример #4 Пример использования http_build_query() с объектом

$parent = new parentClass ();

Результат выполнения данного примера:

Смотрите также

User Contributed Notes 24 notes

Params with null value do not present in result string.

If you need to change the enc_type, use this:

http_build_query($query, null, ini_get(‘arg_separator.output’), PHP_QUERY_RFC3986);

// BAD CODE!
http_build_query($query, null, null, PHP_QUERY_RFC3986);

if you send boolean values it transform in integer :

$a = [teste1= true,teste2=false];
echo http_build_query($a)

//result will be teste1=1&teste2=0

This function makes like this

To do it like this:

As noted before, with php5.3 the separator is & on some servers it seems. Normally if posting to another php5.3 machine this will not be a problem.

But if you post to a tomcat java server or something else the & might not be handled properly.

To overcome this specify:

http_build_query($array); //gives & to some servers

It’s not mentioned in the documentation, but when calling http_build_query on an object, public null fields are ignored.

Is it worth noting that if query_data is an associative array and a value is itself an empty array, or an array of nothing but empty array (or arrays containing only empty arrays etc.), the corresponding key will not appear in the resulting query string?
E.g.

$post_data = array(‘name’=>’miller’, ‘address’=>array(‘address_lines’=>array()), ‘age’=>23);
echo http_build_query($post_data);

Instead you can make your own simple function if you simply want to pass along the data:

If you need the inverse functionality, and (like me) you cannot use pecl_http, you may want to use something akin to the following.

Источник

How to pass an array within a query string?

Is there a standard way of passing an array through a query string?

To be clear, I have a query string with multiple values, one of which would be an array value. I want that query string value to be treated as an array- I don’t want the array to be exploded so that it is indistinguishable from the other query string variables.

Also, according to this post answer, the author suggests that query string support for arrays is not defined. Is this accurate?

EDIT:

Based on @Alex’s answer, there is no standard way of doing this, so my follow-up is then what is an easy way to recognize that the parameter I’m reading is an array in both PHP and Javascript?

Would it be acceptable to name multiple params the same name, and that way I would know that they belong to an array? Example:

Or would this be a bad practice?

php string to query string. Смотреть фото php string to query string. Смотреть картинку php string to query string. Картинка про php string to query string. Фото php string to query string

11 Answers 11

Here’s what I figured out:

Submitting multi-value form fields, i.e. submitting arrays through GET/POST vars, can be done several different ways, as a standard is not necessarily spelled out.

Three possible ways to send multi-value fields or arrays would be:

Form Examples

On a form, multi-valued fields could take the form of a select box set to multiple:

. or as multiple hidden fields with the same name:

UPDATE

As commenters have pointed out, this is very much framework-specific. Some examples:

Query string:

Rails:

Angular:

See comments for examples in node.js, WordPress, ASP.net

Maintaining order: One more thing to consider is that if you need to maintain the order of your items (i.e. array as an ordered list), you really only have one option, which is passing a delimited list of values, and explicitly converting it to an array yourself.

A query string carries textual data so there is no option but to explode the array, encode it correctly and pass it in a representational format of your choice:

p1=value1&pN=valueN.
data=[value1. valueN]
data=

and then decode it in your server side code.

I don’t think there’s a standard.
Each web environment provides its own ‘standard’ for such things. Besides, the url is usually too short for anything (256 bytes limit on some browsers). Of course longer arrays/data can be send with POST requests.

However, there are some methods:

Although the «square brackets method» is simple and works, it is limited to PHP and arrays.
If other types of variable such as classes or passing variables within query strings in a language other than PHP is required, the JSON method is recommended.

Example in PHP of JSON method (method 2):

Источник

Parse query string into an array

How can I turn a string below into an array?

This is the array I am looking for,

php string to query string. Смотреть фото php string to query string. Смотреть картинку php string to query string. Картинка про php string to query string. Фото php string to query string

11 Answers 11

You want the parse_str function, and you need to set the second parameter to have the data put in an array instead of into individual variables.

php string to query string. Смотреть фото php string to query string. Смотреть картинку php string to query string. Картинка про php string to query string. Фото php string to query string

Sometimes parse_str() alone is note accurate, it could display for example:

parse_str() would return:

It would be better to combine parse_str() with parse_url() like so:

php string to query string. Смотреть фото php string to query string. Смотреть картинку php string to query string. Картинка про php string to query string. Фото php string to query string

php string to query string. Смотреть фото php string to query string. Смотреть картинку php string to query string. Картинка про php string to query string. Фото php string to query string

php string to query string. Смотреть фото php string to query string. Смотреть картинку php string to query string. Картинка про php string to query string. Фото php string to query string

If you’re having a problem converting a query string to an array because of encoded ampersands

then be sure to use html_entity_decode

php string to query string. Смотреть фото php string to query string. Смотреть картинку php string to query string. Картинка про php string to query string. Фото php string to query string

Attention, it’s usage is:

Please note that the above only applies to PHP version 5.3 and earlier. Call-time pass-by-reference has been removed in PHP 5.4

php string to query string. Смотреть фото php string to query string. Смотреть картинку php string to query string. Картинка про php string to query string. Фото php string to query string

There are several possible methods, but for you, there is already a builtin parse_str function

php string to query string. Смотреть фото php string to query string. Смотреть картинку php string to query string. Картинка про php string to query string. Фото php string to query string

This is one-liner for parsing query from current URL into array:

php string to query string. Смотреть фото php string to query string. Смотреть картинку php string to query string. Картинка про php string to query string. Фото php string to query string

You can use the PHP string function parse_str() followed by foreach loop.

php string to query string. Смотреть фото php string to query string. Смотреть картинку php string to query string. Картинка про php string to query string. Фото php string to query string

You can try this code :

php string to query string. Смотреть фото php string to query string. Смотреть картинку php string to query string. Картинка про php string to query string. Фото php string to query string

This is the PHP code to split query in mysql & mssql

Query before

select xx from xx select xx,(select xx) from xx where y=’ cc’ select xx from xx left join ( select xx) where (select top 1 xxx from xxx) oder by xxx desc «;

Query after

select xx,(select xx) from xx where y=’ cc’

select xx from xx left join (select xx) where (select top 1 xxx from xxx) oder by xxx desc

Thank you, from Indonesia Sentrapedagang.com

php string to query string. Смотреть фото php string to query string. Смотреть картинку php string to query string. Картинка про php string to query string. Фото php string to query string

For this specific question the chosen answer is correct but if there is a redundant parameter—like an extra «e»—in the URL the function will silently fail without an error or exception being thrown:

So I prefer using my own parser like so:

Now you have all the occurrences of each parameter in its own array, you can always merge them into one array if you want to.

Источник

Extract query string into an associative array with PHP

A little while back I posted how to extract the domain, path, etc from a url with PHP and in this follow up post show how to extract the query string into an associative array using the parse_str function.

Extract the query string with parse_url

In this example we’ll look at the URL from querying [chris hope] at Google (I don’t show up until the second page, by the way) which looks like this:

Using parse_url we can easily extract the query string like so:

The output from the above will be this:

As an aside, before continuing with using parse_str to extract the individual parts of the query string, doing print_r($parts) would show this:

Extract the query string parts with parse_str

The parse_str function takes one or two parameters (the second from PHP 4.0.3) and does not return any values. If the second parameter is present, the values from the query string are returned in that parameter as an associative array. If it is not present, they are instead set as variables in the current scope, which is not really ideal.

So, without the first parameter:

You could now echo the «q» value like this:

In my opionion, it’s better to have the values returned as an array like so:

Now doing print_r($query) would output this:

The «q» value could now be echoed like this:

Follow up posts

Have a read of my post titled «PHP: get keywords from search engine referer url» to find out how to use the parse_url function in conjunction with the parse_str function to see what query string visitors have entered into a search engine.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *