Получить get параметр url php

How to retrieve URL parameters in PHP.

In this beginner PHP tutorial, we will show you how to retrieve query string parameters from a URL. We will also tell you about some of the most common pitfalls.

Take the following URL as an example, which contains two GET parameters:

In the URL above, we have two GET parameters. id, which contains the value 23, and page, which contains the value 34.

Let’s say that we want to retrieve those values so that we can use them in our PHP script.

If we want to retrieve the values of those two parameters, we can access the $_GET superglobal array like so:

//Get our two GET parameters. $id = $_GET['id']; $page = $_GET['page'];

Although the PHP code will work, it wrongly assumes that the GET parameters in question will always exist.

As a result, there is a possibility that our script will throw an ugly undefined index notice if a user removes one of the parameters from the URL.

This will result in PHP spitting out the following message:

Notice: Undefined index: id in /path/to/file.php on line 4

To guard against this kind of issue, you will need to check to see if the GET variable exists before you attempt to use it:

$id = false; if(isset($_GET[‘id’])) < $id = $_GET['id']; >$page = false; if(isset($_GET[‘page’]))

In the example above, we use PHP’s isset function to check whether or not the parameter in question actually exists.

If it does exist, we assign it to one of our variables. If it doesn’t, then our variables will retain their default FALSE values.

Never trust GET parameters. Always validate them.

GET parameters should always be treated with extreme caution.

  1. You cannot assume that they will always exist.
  2. If they do exist, you can’t discount the possibility that the user has tampered with them.

In other words, if you expect id to be an integer value and a user decides to manually change that to “blahblahblah”, your PHP script should be able to handle that scenario.

URL parameters are external variables, and external variables can never ever be trusted.

Never directly print GET parameters onto the page.

Printing out GET parameters without sanitizing them is a recipe for disaster, as it will leave your web application wide open to XSS attacks.

Take the following example:

$page = false; if(isset($_GET['page'])) < $page = $_GET['page']; >if($page !== false)< echo '

Page: ' . $page . '

'; >

Here, we’ve done everything right except the final step:

  1. We check to see if the GET parameter exists before we access its value.
  2. We do not print the page number out if it doesn’t exist.

However, we did not sanitize the variable before we printed it out. This means that an attacker could easily replace our GET variable with HTML or JavaScript and have it executed when the page is loaded.

They could then redirect other users to this “tainted” link.

To protect ourselves against XSS, we can use the PHP function htmlentities:

//Guarding against XSS if($page !== false)< echo '

Page: ' . htmlentities($page) . '

'; >

The htmlentities function will guard against XSS by converting all special characters into their relevant HTML entities. For example, will become <script>

Источник

Отправка данных на сервер

Самым простым способом передачи данных на сервер приложению PHP извне представляет передача данных через строку запроса.

Строка запроса представляет набор параметров, которые помещаются в адресе после вопросительного знака. При этом каждый параметр определяет название и значение. Например, в адресе:

http://localhost/user.php?name=Tom&age=36

Часть ?name=Tom&age=36 представляет строку запроса, в которой есть два параметра name и age . Для каждого параметра определено имя и значение, которые отделяются знаком равно. Параметр name имеет значение «Tom», а параметр age — значение 36. Друг от друга параметры отделяются знаком амперсанда.

Например, определим следующий скрипт user.php со следующим содержимым:

 if(isset($_GET["age"])) < $age = $_GET["age"]; >echo "Имя: $name 
Возраст: $age"; ?>

Когда мы вводим в адресную строку браузера некий адрес и нажимаем на оправку, то серверу отправляется запрос типа GET . В PHP по умолчанию определен глобальный ассоциативный массив $_GET , который хранит все значения, передаваемые в запроса GET. Используя ключи передаваемых данных, мы можем из массива $_GET получить передаваемые значения.

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

Например, в строке запроса передается параметр name=Tom . Соответственно, чтобы получить значение параметра name из запроса, обращаемся по соответствующему ключу:

Однако стоит учитывать, что в адресной строке необязательно будет использоваться строка запроса или конкретно данный параметр. Поэтому перед получением значения параметра сначала смотрим, а передан ли вообще такой параметр:

Теперь обратимся к этому скрипту, например, так http://localhost/user.php?name=Tom&age=36 :

Массив <img decoding=

Get Parameters From a URL String in PHP

Get Parameters From a URL String in PHP

  1. Use parse_url() and parse_str() Functions to Get Parameters From a URL String in PHP
  2. Use $_GET Variable to Get Parameters From a URL String in PHP

This article will introduce methods to get parameters from a URL string in PHP.

Use parse_url() and parse_str() Functions to Get Parameters From a URL String in PHP

We can use the built-in functions parse_url() and parse_str() functions to get parameters from a URL string . These functions are used together to get the parameters. The function parse_url will divide the URL into different parameters. After that parse_string will get the required parameter.

The correct syntax to use parse_url() functions is as follows

This function returns components of a URL. If our URL is not correctly formatted, the function may return False .

The correct syntax to use the parse_str() function is as follows

This function returns nothing.

The program below shows how we can use these functions to get parameters from a URL string .

php $url = "https://testurl.com/test/1234?email=abc@test.com&name=sarah"; $components = parse_url($url); parse_str($components['query'], $results); print_r($results); ?> 
Array (  [email] => abc@test.com  [name] => sarah ) 

Now, if we want to get the email parameter only, we will do the following changes in our program:

php $url = "https://testurl.com/test/1234?email=abc@test.com&name=sarah"; $components = parse_url($url); parse_str($components['query'], $results); echo($results['email']); ?> 

We can also pass $component parameter to parse_url() function.

php $url = "https://testurl.com/test/1234?email=abc@test.com&name=sarah"; $components = parse_url($url, PHP_URL_QUERY); //$component parameter is PHP_URL_QUERY  parse_str($components, $results); print_r($results); ?> 
Array (  [email] => abc@test.com  [name] => sarah ) 

Use $_GET Variable to Get Parameters From a URL String in PHP

In PHP, we can also use the $_GET variable to get parameters from a URL string. It is a superglobals variable, which means that it is available in all scopes. This variable gets the data i.e URL, from an HTML form.

Assuming that the URL from form is https://testurl.com/test/1234?email=abc@test.com&name=sarah . The program that uses this variable to get parameters from a URL string is as follows.

php echo $_GET['email'] . $_GET['name'] ?> 

Related Article — PHP String

Источник

PHP parse_url и её обратная функция

parse_url($url, $component) – разбирает URL-адрес на компоненты, возвращая их в виде массива. При разборе некорректных URL, функция может вернуть false .

Разбор URL

Структура URL адреса

$url = 'https://snipp.ru/php/parse-url?page=1&sort=1#sample'; $parse = parse_url($url); print_r($parse);

Результат:

Array ( [scheme] => https [host] => snipp.ru [path] => /php/parse-url [query] => page=1&sort=1 [fragment] => sample )
$url = 'https://snipp.ru/php/parse-url?page=1&sort=1#sample'; echo parse_url($url, PHP_URL_SCHEME); // https echo parse_url($url, PHP_URL_HOST); // snipp.ru echo parse_url($url, PHP_URL_PORT); // NULL echo parse_url($url, PHP_URL_USER); // NULL echo parse_url($url, PHP_URL_PASS); // NULL echo parse_url($url, PHP_URL_PATH); // /php/parse-url echo parse_url($url, PHP_URL_QUERY); // page=1&sort=1 echo parse_url($url, PHP_URL_FRAGMENT); // sample

Кстати, GET-параметры будут представлены строкой вида page=1&sort=1 , преобразовать ее в массив можно с помощью функции parse_str() :

parse_str('page=1&sort=1', $query); print_r($query);

Результат:

echo http_build_query($query); // page=1&sort=1

Обратный parse_url

function reverse_parse_url(array $parts) < $url = ''; if (!empty($parts['scheme'])) < $url .= $parts['scheme'] . ':'; >if (!empty($parts['user']) || !empty($parts['host'])) < $url .= '//'; >if (!empty($parts['user'])) < $url .= $parts['user']; >if (!empty($parts['pass'])) < $url .= ':' . $parts['pass']; >if (!empty($parts['user'])) < $url .= '@'; >if (!empty($parts['host'])) < $url .= $parts['host']; >if (!empty($parts['port'])) < $url .= ':' . $parts['port']; >if (!empty($parts['path'])) < $url .= $parts['path']; >if (!empty($parts['query'])) < if (is_array($parts['query'])) < $url .= '?' . http_build_query($parts['query']); >else < $url .= '?' . $parts['query']; >> if (!empty($parts['fragment'])) < $url .= '#' . $parts['fragment']; >return $url; >

Удаление из URL GET-параметров:

$url = 'https://snipp.ru/php/parse-url?page=1&sort=1#sample'; $parse = parse_url($url); unset($parse['query']); echo reverse_parse_url($parse); // https://snipp.ru/php/parse-url#sample

Замена домена:

$url = 'https://snipp.ru/php/parse-url?page=1&sort=1#sample'; $parse = parse_url($url); $parse['host'] = 'example.com'; echo reverse_parse_url($parse); // https://example.com/php/parse-url?page=1&sort=1#sample

Источник

Читайте также:  Количество гласных букв питон
Оцените статью