php get params from url

How to get parameters from a URL string?

How can I get only the email parameter from these URLs/values?

Please note that I am not getting these strings from browser address bar.

php get params from url. Смотреть фото php get params from url. Смотреть картинку php get params from url. Картинка про php get params from url. Фото php get params from url

13 Answers 13

You can use the parse_url() and parse_str() for that.

will extract the emails from urls.

Use the parse_url() and parse_str() methods. parse_url() will parse a URL string into an associative array of its parts. Since you only want a single part of the URL, you can use a shortcut to return a string value with just the part you want. Next, parse_str() will create variables for each of the parameters in the query string. I don’t like polluting the current context, so providing a second parameter puts all the variables into an associative array.

php get params from url. Смотреть фото php get params from url. Смотреть картинку php get params from url. Картинка про php get params from url. Фото php get params from url

As mentioned in other answer, best solution is using

parse_url()

The parse_url() parse URL and return its components that you can get query string using query key. Then you should use parse_str() that parse query string and return values into variable.

Also you can do this work using regex.

preg_match()

You can use preg_match() to get specific value of query string from URL.

preg_replace()

Also you can use preg_replace() to do this work in one line!

php get params from url. Смотреть фото php get params from url. Смотреть картинку php get params from url. Картинка про php get params from url. Фото php get params from url

I created function from @Ruel answer. You can use this:

This is working great for me using php

A much more secure answer that I’m surprised is not mentioned here yet:

So in the case of the question you can use this to get an email value from the URL get parameters:

$email = filter_input( INPUT_GET, ’email’, FILTER_SANITIZE_EMAIL );

Might as well get into the habit of grabbing variables this way.

Источник

parse_url

(PHP 4, PHP 5, PHP 7, PHP 8)

parse_url — Parse a URL and return its components

Description

This function parses a URL and returns an associative array containing any of the various components of the URL that are present. The values of the array elements are not URL decoded.

This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial and invalid URLs are also accepted, parse_url() tries its best to parse them correctly.

Parameters

Return Values

Examples

Example #1 A parse_url() example

The above example will output:

Example #2 A parse_url() example with missing scheme

The above example will output:

Notes

This function may not give correct results for relative URLs.

This function is intended specifically for the purpose of parsing URLs and not URIs. However, to comply with PHP’s backwards compatibility requirements it makes an exception for the file:// scheme where triple slashes (file:///. ) are allowed. For any other scheme this is invalid.

See Also

User Contributed Notes 33 notes

[If you haven’t yet] been able to find a simple conversion back to string from a parsed url, here’s an example:

Here is utf-8 compatible parse_url() replacement function based on «laszlo dot janszky at gmail dot com» work. Original incorrectly handled URLs with user:pass. Also made PHP 5.5 compatible (got rid of now deprecated regex /e modifier).

Here’s a good way to using parse_url () gets the youtube link.
This function I used in many works:

I was writing unit tests and needed to cause this function to kick out an error and return FALSE in order to test a specific execution path. If anyone else needs to force a failure, the following inputs will work:

There’s a quirk where this function will return the host as the «path» if there is a leading space.

I have coded a function which converts relative URL to absolute URL for a project of mine. Considering I could not find it elsewhere, I figured I would post it here.

The following function takes in 2 parameters, the first parameter is the URL you want to convert from relative to absolute, and the second parameter is a sample of the absolute URL.

Currently it does not resolve ‘../’ in the URL, only because I do not need it. Most webservers will resolve this for you. If you want it to resolve the ‘../’ in the path, it just takes minor modifications.

?>

OUTPUTS:
http :// user:pass@example.com:8080/path/to/index.html
http :// user:pass@example.com:8080/path/to/img.gif
http :// user:pass@example.com:8080/img.gif
http :// user:pass@example.com:8080/path/to/img.gif
http :// user:pass@example.com:8080/path/to/../img.gif
http :// user:pass@example.com:8080/path/to/images/img.gif
http :// user:pass@example.com:8080/images/img.gif
http :// user:pass@example.com:8080/path/to/images/img.gif
http :// user:pass@example.com:8080/path/to/../images/img.gif

Sorry if the above code is not your style, or if you see it as «messy» or you think there is a better way to do it. I removed as much of the white space as possible.

Источник

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 get params from url. Смотреть фото php get params from url. Смотреть картинку php get params from url. Картинка про php get params from url. Фото php get params from url

11 Answers 11

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

DOCUMENTATION

php get params from url. Смотреть фото php get params from url. Смотреть картинку php get params from url. Картинка про php get params from url. Фото php get params from url

php get params from url. Смотреть фото php get params from url. Смотреть картинку php get params from url. Картинка про php get params from url. Фото php get params from url

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 get params from url. Смотреть фото php get params from url. Смотреть картинку php get params from url. Картинка про php get params from url. Фото php get params from url

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

EDIT

php get params from url. Смотреть фото php get params from url. Смотреть картинку php get params from url. Картинка про php get params from url. Фото php get params from url

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:

Источник

Slim PHP and GET Parameters

I’m playing with Slim PHP as a framework for a RESTful API, and so far it’s great. Super easy to work with, but I do have one question I can’t find the answer to. How do I grab GET params from the URL in Slim PHP?

For example, if I wanted to use the following:

A case of the Mondays? Am I overthinking it? Thanks in advance!

9 Answers 9

You can do this very easily within the Slim framework, you can use:

$app here is a Slim instance.

Or if you want to be more specific

You would use it like so in a specific route

You can read the documentation on the request object http://docs.slimframework.com/request/variables/

For Slim 3/4 you need to use the method getQueryParams() on the PSR 7 Request object.

You can get the query parameters as an associative array on the Request object using getQueryParams().

php get params from url. Смотреть фото php get params from url. Смотреть картинку php get params from url. Картинка про php get params from url. Фото php get params from url

I fixed my api to receive a json body OR url parameter like this.

This might not suit everyone but it worked for me.

php get params from url. Смотреть фото php get params from url. Смотреть картинку php get params from url. Картинка про php get params from url. Фото php get params from url

In Slim 3.0 the following also works:

routes.php

user.php

Not sure much about Slim PHP, but if you want to access the parameters from a URL then you should use the:

You’ll find a bunch of blog posts on Google to solve this. You can also use the PHP function parse_url.

IF YOU WANT TO GET PARAMS WITH PARAM NAME

The params() method will first search PUT variables, then POST variables, then GET variables. If no variables are found, null is returned. If you only want to search for a specific type of variable, you can use these methods instead:

IF YOU WANT TO GET ALL PARAMETERS FROM REQUEST WITHOUT SPECIFYING PARAM NAME, YOU CAN GET ALL OF THEM INTO ARRAY IN FORMAT KEY => VALUE

$data will be an array that contains all fields from request as below

Источник

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.

Источник

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

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