- Получить строку запроса URL
- Get Query String from URL in php
- Using $_GET to Get Query String Parameters in php
- Using $_SERVER to Get Query String in php
- Other Articles You’ll Also Like:
- About The Programming Expert
- PHP: Get the full query string.
- What if there is no query string?
- Why is this useful?
- QUERY_STRING and XSS.
- Вывод данных из MySql на PHP
- Извлечь данные из таблицы MySql
- mysqli_connect
- mysqli_query
- mysqli_fetch_array
- Вывод переменной врутри строки
Получить строку запроса URL
Что такое способ «меньше кода» для получения параметров из строки запроса URL-адреса, которая отформатирована следующим образом?
Выход должен быть: myqueryhash
www.mysite.com/category/subcategory?q=myquery php echo $_GET['q']; //Output: myquery ?>
$_SERVER[‘QUERY_STRING’] содержит данные, которые вы ищете.
ДОКУМЕНТАЦИЯ
Функция parse_str автоматически преобразует все параметры запроса в соответствующие переменные PHP. Например, по следующему URL-адресу:
http://www.domain.com/page.php?x=100&y=200
parse_str($_SERVER['QUERY_STRING']);
автоматически создаст переменные $ x и $ y со значениями 100 и 200, которые вы затем сможете использовать в своем коде.
PHP-способ сделать это – использовать функцию parse_url , которая анализирует URL-адрес и возвращает его компоненты. Включая строку запроса.
$url = 'www.mysite.com/category/subcategory?myqueryhash'; echo parse_url($url, PHP_URL_QUERY); # output "myqueryhash"
Полная документация здесь
Если вы хотите получить всю строку запроса:
Я рекомендую лучший ответ, как
Вышеприведенный пример выводит:
Кроме того, если вы ищете текущее имя файла вместе с строкой запроса, вам просто нужно следующее
basename($_SERVER['REQUEST_URI'])
Это предоставит вам информацию, как в следующем примере
file.php? arg1 = значение & арг2 = значение
И если вам также нужен полный путь к файлу, начиная с root, например /folder/folder2/file.php?arg1=val&arg2=val, тогда просто удалите функцию basename () и просто используйте наложение
Вот моя функция для восстановления частей строки запроса REFERRER .
Если на вызывающей странице уже была строка запроса в собственном URL-адресе , и вы должны вернуться на эту страницу и хотите отправить некоторые, не все, из этих $_GET варов (например, номер страницы).
Пример: строка запроса Referrer была ?foo=1&bar=2&baz=3 вызывающая refererQueryString( ‘foo’ , ‘baz’ ) возвращает foo=1&baz=3″ :
function refererQueryString(/* var args */) < //Return empty string if no referer or no $_GET vars in referer available: if (!isset($_SERVER['HTTP_REFERER']) || empty( $_SERVER['HTTP_REFERER']) || empty(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY ))) < return ''; >//Get URL query of referer (something like "threadID=7&page=8") $refererQueryString = parse_url(urldecode($_SERVER['HTTP_REFERER']), PHP_URL_QUERY); //Which values do you want to extract? (You passed their names as variables.) $args = func_get_args(); //Get 'Вывести строку запроса php' strings out of referer's URL: $pairs = explode('&',$refererQueryString); //String you will return later: $return = ''; //Analyze retrieved strings and look for the ones of interest: foreach ($pairs as $pair) < $keyVal = explode('=',$pair); $key = &$keyVal[0]; $val = urlencode($keyVal[1]); //If you passed the name as arg, attach current pair to return string: if(in_array($key,$args)) < $return .= '&'. $key . '=' .$val; >> //Here are your returned 'key=value' pairs glued together with "&": return ltrim($return,'&'); > //If your referer was 'page.php?foo=1&bar=2&baz=3' //and you want to header() back to 'page.php?foo=1&baz=3' //(no 'bar', only foo and baz), then apply: header('Location: page.php?'.refererQueryString('foo','baz'));
Для получения каждого узла в URI вы можете использовать функцию explode() для $ _SERVER [‘REQUEST_URI’]. Если вы хотите получить строки, не зная, передано или нет. вы можете использовать функцию, которую я определил для получения параметров запроса от $ _REQUEST (поскольку он работает как для параметров POST, так и для GET).
function getv($key, $default = '', $data_type = '') < $param = (isset($_REQUEST[$key]) ? $_REQUEST[$key] : $default); if (!is_array($param) && $data_type == 'int') < $param = intval($param); >return $param; >
Могут быть некоторые случаи, когда мы хотим получить параметры запроса, преобразованные в тип Integer, поэтому я добавил третий параметр этой функции.
Этот код и обозначения не мои. Evan K разрешает многозначное одноименное задание с пользовательской функцией;) берется из:
Следует отметить, что parse_str builtin НЕ обрабатывает строку запроса стандартным способом CGI, когда дело доходит до дубликатов полей. Если в строке запроса существует несколько полей с одним и тем же именем, каждый другой язык веб-обработки будет считывать их в массив, но PHP молча перезаписывает их:
'3'); ?> Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect. array('1', '2', '3') ); ?> 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: else < $arr[$name] = array($arr[$name], $value); >> # otherwise, simply stick it in a scalar else < $arr[$name] = $value; >> # return result array return $arr; > $query = proper_parse_str($_SERVER['QUERY_STRING']); ?>
Благодаря @K. Shahzad Это помогает, когда вы хотите переписать строку запроса без каких-либо переписывающих дополнений. Скажем, вы переписываете / test /? X = y в index.php? Q = test & x = y, и вы хотите только получить строку запроса.
function get_query_string()< $arr = explode("?",$_SERVER['REQUEST_URI']); if (count($arr) == 2)< return ""; >else< return "?".end($arr)."
"; > > $query_string = get_query_string();
Get Query String from URL in php
To get the query string from a URL in php, you can use $_GET super global to get specific key value pairs or $_SERVER super global to get the entire string.
// http://theprogrammingexpert.com/?key1=value1&key2=value2&key3=value3 echo $_GET['key1']; echo $_GET['key2']; echo $_SERVER['QUERY_STRING']; //Output: value1 value2 key1=value1&key2=value2&key3=value3
A query string is a part of a URL that assigns values to specified parameters. When building web pages, query strings help us pass and access information to be used on our web pages.
When working in php, the ability to easily access and work with query strings is important.
To get a query string from a URL, there are a few different ways you can get the key value pairs.
To get a specific parameter from a query string, you can use $_GET super global to access individual parameters from the query string by name.
// http://theprogrammingexpert.com/?key1=value1&key2=value2&key3=value3 echo $_GET['key1']; //Output: value1
If you want to get the entire query string, you can use the $_SERVER super global.
// http://theprogrammingexpert.com/?key1=value1&key2=value2&key3=value3 echo $_SERVER['QUERY_STRING']; //Output: key1=value1&key2=value2&key3=value3
After getting the entire query string, you can parse it for the key value pairs with the php parse_str() function.
Using $_GET to Get Query String Parameters in php
The $_GET super global variable allows us to get individual key value pairs from query strings.
There are a few additional cases which occur when using query strings that I want to share with you.
First, in a query string, you can have duplicate key names followed by square brackets. This will create a child array in $_GET for that key with numerically indexed values.
// http://theprogrammingexpert.com/?key[]=value1&key[]=value2&key[]=value3 echo $_GET['key'][0]; echo $_GET['key'][1]; echo $_GET['key'][2]; //Output: value1 value2 value3
If the brackets are not empty, and have keys in them, then for a particular key, the child array belonging to the key will be an associative array.
// http://theprogrammingexpert.com/?key[ex1]=value1&key[ex2]=value2&key[ex3]=value3 echo $_GET['key']['ex1']; echo $_GET['key']['ex2']; echo $_GET['key']['ex3']; //Output: value1 value2 value3
Using $_SERVER to Get Query String in php
You can also use the $_SERVER super global variable to get the entire query string. After getting the query string, you can parse it with the php parse_str() function.
// http://theprogrammingexpert.com/?key1=value1&key2=value2&key3=value3 query_string = $_SERVER['QUERY_STRING']; parse_str(query_string); echo $key1; echo $key2; echo $key3; //Output: value1 value2 value3
Hopefully this article has been useful for you to learn how to get query strings and work with them in php.
Other Articles You’ll Also Like:
- 1. php e – Using M_E and exp() Function to Get Euler’s Constant e
- 2. php range() – Create Array of Elements Within Given Range
- 3. php is_float() Function – Check if Variable is Float in php
- 4. php array_key_exists() Function – Check if Key Exists in Array
- 5. In PHP isset Method is Used For Checking if Variable is Defined
- 6. php Square Root with sqrt Function
- 7. php session_destroy() – Delete Session File Where Session Data is Stored
- 8. php array_walk() – Modify Elements in Array with Callback Function
- 9. Capitalize First Letter of String with php ucfirst() Function
- 10. preg_replace php – Use Regex to Search and Replace
About The Programming Expert
The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.
Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.
At the end of the day, we want to be able to just push a button and let the code do it’s magic.
You can read more about us on our about page.
PHP: Get the full query string.
This is a tutorial on how to get the FULL query string as a string using PHP.
Most people are aware of how to retrieve URL parameters using the $_GET array. However, what if you wanted to retrieve these parameters as a string?
Let’s say, for example, that we have the following URL:
test.com/file.php?id=299&mobile=Y&clid=392829
As you can see, the query string in the URL above contains three GET parameters.
If we want to retrieve everything after the question mark and assign it to a string, we can simply access the QUERY_STRING element in the $_SERVER superglobal array like so:
//Get the full string $queryString = $_SERVER['QUERY_STRING']; var_dump($queryString);
If we were to run our code snippet above on the URL in question, it would return the following string:
Note how this string does not contain the question mark symbol. If this symbol is needed, then you will need to re-add it yourself.
What if there is no query string?
If there is no query string, then the QUERY_STRING key in $_SERVER will be an empty string.
Unlike other elements in the $_SERVER array, QUERY_STRING should always exist.
Why is this useful?
This can be useful for a number of reasons.
The first two that spring to mind are:
QUERY_STRING and XSS.
You should never print the QUERY_STRING variable out onto the page without filtering it first.
If you do this, you will leave yourself open to the possibility of a Cross Site Scripting (XSS) attack.
The code above is vulnerable to XSS because the QUERY_STRING result is being printed out without any sort of filtering. As a result, malicious users could potentially put JavaScript code into the query string and have it executed on your page.
To be safe, you should wrap it in the htmlentities function like so:
Hopefully, you found this guide useful!
Вывод данных из MySql на PHP
Первое, что нам следует сделать для того, чтобы получить данные из таблицы базы данных, — установить соединение с БД.
Извлечь данные из таблицы MySql
После того, как мы установили соединение с БД, c помощью запроса можно получить данные из любой таблицы. А с помощью цикла while их вывести.
Теперь давайте разберем функции, которые мы использовали для вывода данных из MySql.
mysqli_connect
mysqli_connect(, , , ) — устанавливает соединение с базой данных.
mysqli_query
mysqli_query(, ) — выполняет запрос к БД, написанный на языке SQL.
mysqli_fetch_array
mysqli_fetch_array() — поочередно возвращает по одной строке из результата запроса.
Вывод переменной врутри строки
Заметьте, что если вы выводите строку оператором echo и строка заключена в двойные кавычки (именно двойные), то внутрь строки можно вставлять переменные в фигурных скобках и они будут подставленны в этот шаблон. Круто, да?
Понравилась или помогла статья? Самое лучшее, что ты можешь сделать — это поделиться ею в любой из своих соцсетей (даже если ты поделишься в твиттере или google+, которыми ты не пользуешься — это очень поможет развитию моего блога). Спасибо! А если ты еще и оставишь любой комментарий снизу в обсуждениях, то это будет двойное СПАСИБО!
Ссылка на статью на всякий случай:
Крутов Герман © 2009-2023
krutovgerman2007@ya.ru
Я ВКонтате