php get url without params
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.
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.
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!
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.
How, in Yii, to get the current page’s URL. For example:
Edit: Current solution:
16 Answers 16
Yii 1
For Yii2:
This will output something in the following format:
Yii 1
Here is a complete breakdown (creating url for the currently active controller, modules or not):
When you don’t have the same active controller, you have to specify the full path like this:
To get the absolute current request url (exactly as seen in the address bar, with GET params and http://) I found that the following works well:
In Yii2 you can do:
You are definitely searching for this
I don’t know about doing it in Yii, but you could just do this, and it should work anywhere (largely lifted from my answer here):
to get an Absolute webroot url, and strip the http[s]://
Something like this should work, if run in the controller:
This assumes that you are using ‘friendly’ URLs in your app config.
For Yii2: This should be safer Yii::$app->request->absoluteUrl rather than Yii::$app->request->url
For Yii1
I find it a clean way to first get the current route from the CUrlManager, and then use that route again to build the new url. This way you don’t ‘see’ the baseUrl of the app, see the examples below.
Example with a controller/action:
Example with a module/controller/action:
This works only if your urls are covered perfectly by the rules of CUrlManager 🙂
Try to use this variant:
It is the easiest way, I guess.
Most of the answers are wrong.
Here is the function that works. It does more things actually. You can remove the param that you don’t want and you can add or modify an existing one.
This will remove query params ‘remove_this1’ and ‘remove_this2’ from URL and return you the new URL
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 в PHP
Затем добавьте имя хоста и протокол.
Лучший ответ здесь – от RiaD :
Stackoverflow: как удалить запрос и получить только URL?
Вы можете использовать strtok для получения строки до первого появления?
Это приложение strtok для возврата всего в строку до первого экземпляра символа будет работать лучше, чем любой другой метод в PHP, хотя WILL оставит запрос в памяти.
Самое простое решение:
echo parse_url ($_SERVER[«REQUEST_URI»], PHP_URL_PATH);
Я на самом деле думаю, что это не лучший способ разобрать его. Это не чисто или немного из-за темы …
Я бы сделал что-то вроде …
РЕДАКТИРОВАТЬ
Почему так сложно? знак равно
это должно действительно сделать это человек;)
Вот решение, которое учитывает разные порты и https:
Или более базовое решение, которое не учитывает другие порты:
Не всем это будет просто, но я считаю, что это лучший способ обойти это:
То, что происходит, это просто пройти через REQUEST_URI с начала строки, а затем остановиться, когда он попадет в «?» (что действительно, только должно произойти, когда вы добираетесь до параметров).
Я надеюсь, что кто-то сможет это использовать …
PS. Это подтверждено, работая при использовании SLIM, чтобы перенаправить URL-адрес.
У меня была такая же проблема, когда мне нужна ссылка на домашнюю страницу. Я пробовал это, и это сработало:
Обратите внимание на знак вопроса в конце. Я считаю, что говорит, что машина перестает думать от имени кодера 🙂
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:
11 Answers 11
$_SERVER[‘QUERY_STRING’] contains the data that you are looking for.
DOCUMENTATION
The PHP way to do it is using the function parse_url, which parses a URL and return its components. Including the query string.
The function parse_str() automatically reads all query parameters into an array.
EDIT
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: