php get current url php
php get URL of current file directory
Might be an easy question for you, but I’m breaking my head over this one.
I have a php file that needs to know it’s current directory url to be able to link to something relative to itself.
For example, currently I know to get the current directory path instead of the url. When I use this I get the path:
But this would be my desired result:
Note that this is not the location of the current page. The page calls a file from «http://localhost:8888/dir1/dir2/dir3/myfile.php» And «myfile.php» has the script from above.
4 Answers 4
For example if the URL is http://localhost/
The output would be:
That’s enough to generate a relative URL.
In the case above that will give you /
Please note that echo getcwd(); is not what you want, based on your question. That gives you the location on the filesystem/server (not the URL) that your script is running from. The directory the script is located in on the servers filesystem, and the URL, are 2 completely different things.
There is also a function to parse URL’s built in to PHP: http://php.net/manual/en/function.parse-url.php
This is the code I’ll now be useing:
If your URL is like this: https://localhost.com/this/is/a/url
If you would like to get the full url, you can do something like:
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
How do I get the base URL with PHP?
How do I get http://127.0.0.1/test_website/ with PHP?
I tried something like these, but none of them worked.
23 Answers 23
If you plan on using https, you can use this:
NOTE: If you’re depending on the HTTP_HOST key (which contains user input), you still have to make some cleanup, remove spaces, commas, carriage return, etc. Anything that is not a valid character for a domain. Check the PHP builtin parse_url function for an example.
Function adjusted to execute without warnings:
Fun ‘base_url’ snippet!
will create output like this :
and if this script works fine.
Try this. It works for me.
Note: This is an expansion of the answer provided by maček above. (Credit where credit is due.)
Edited at @user3832931 ‘s answer to include server port..
This is the best method i think so.
I used it to echo the base url of my site to link my css.
I had the same question as the OP, but maybe a different requirement. I created this function.
. which, incidentally, I use to help create absolute URLs that should be used for redirecting.
and you get something like
Just test and get the result.
.htaccess
index.php
Now I use this in the base tag of the template (in the head section of the page):
So if the variable was not empty, we use it. Otherwise fallback to / as default base path.
Based on the environment the base url will always be correct. I use / as the base url on local and production websites. But /foldername/ for on the staging environment.
How to get complete current url for Cakephp
How do you echo out current URL in Cake’s view?
25 Answers 25
Which will give you the absolute url from the hostname i.e. /controller/action/params
which should give you the full url with the hostname.
I prefer this, because if I don’t mention «request» word, my IDE gives warning.
Edit: To clarify all options
Full current url:
Router::reverse($this->request, true)
I know this post is a little dated, and CakePHP versions have flourished since. In the current (2.1.x) version of CakePHP and even in 1.3.x if I am not mistaken, one can get the current controller/view url like this:
While this method does NOT return the parameters, it is handy if you want to append parameters to a link when building new URL’s. For example, we have the current URL:
projects/edit/6
In the above example we’d need to manually add the ID of 6 back into the URL, so perahaps the final link build would be like this:
projects/edit/6/c_action:remove_image
Sorry if this is in the slightest unrelated, but I ran across this question when searching for a method to achieve the above and thought others may benefit from it.
В этой статье будет рассказано о том, как в языке программирования PHP получить адрес текущей страницы. Также вы узнаете о работе переменной $_SERVER.
Первое, о чём следует сказать, — зачем вообще получать ссылки (urls) в PHP? На практике варианты могут различаться. Представьте, что у нас для разных разделов применяется один и тот же шаблон. И возникает потребность в том, чтобы вывести (либо не вывести — зависит от ситуации) какой-нибудь специальный блок, причём в других разделах вывод этого блока не нужен.
В большинстве случаев мы пожелаем выполнить поставленную задачу по условию. То есть сделаем условие, в котором будем выполнять проверку того либо иного раздела. Можно сказать, что с точки зрения архитектуры данное решение не является оптимальным. Но на практике нам нередко достаются уже реализованные проекты, с которыми необходимо что-то решать с учётом уже имеющейся архитектуры.
Но давайте не будем много говорить, а лучше приступим к решению поставленной задачи — получению ссылки в PHP.
Получение ссылки текущей страницы в PHP
Идём дальше. Представьте, что у вас есть web-страница, имеющая следующий вид: http://localhost/php-lessons/url/?name=anna&city=Valencia. Тестирование в данном примере осуществляется на локальном сервере. Если надо тестировать код на реальном веб-сайте, доступном в интернете, достаточно вместо localhost прописать имя сайта (домен) — тот же otus.ru.
Что же мы увидим в подопытном url? Нас могут интересовать следующие данные: — адрес веб-страницы без GET-параметров; — URL с GET-параметрами; — непосредственно GET-параметры без текущей ссылки (адреса веб-страницы).
Лучше всего разобраться с каждым из случаев по отдельности — так будет гораздо понятнее.
Получение полного URL в PHP
Для получения полного URL вместе с имеющимися GET-параметрами, пригодится следующий код:
На втором этапе выполняется присоединение двоеточия и двух слэшев, имени домена и остальной части URL.
Итог выполнения кода будет следующим:
Если протокол получать не требуется, код на PHP можно немного сократить:
Смотрим на результат и видим, что протокол отсутствует:
Получение URL в PHP без GET-параметров
Иногда эти параметры, передаваемые в качестве части ссылки, нас не интересуют, то есть требуется получить адрес без них. Мы говорим о следующих параметрах: name=anna&city=Valencia.
В действительности их можно отсечь, используя функцию explode в PHP, разбивающую строку по разделителю. Не стоит объяснять, что ссылка представляет собой строку, а параметры GET начинают прописываться после «?». В результате вопросительный знак и станет разделителем, а функция explode сделает из строки массив с 2-мя элементами. Первый элемент станет содержать искомую ссылку без GET-параметров, так как эти самые параметры останутся во втором элементе.
Получение только параметров GET
С помощью этого кода получим: