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.

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

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:

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

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:

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

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:

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

In Yii2 you can do:

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

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):

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

to get an Absolute webroot url, and strip the http[s]://

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

Something like this should work, if run in the controller:

This assumes that you are using ‘friendly’ URLs in your app config.

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

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

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 🙂

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

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.

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

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.

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

Function adjusted to execute without warnings:

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

Fun ‘base_url’ snippet!

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

will create output like this :

and if this script works fine.

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

Try this. It works for me.

Note: This is an expansion of the answer provided by maček above. (Credit where credit is due.)

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

Edited at @user3832931 ‘s answer to include server port..

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

This is the best method i think so.

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

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.

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

and you get something like

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

Just test and get the result.

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

.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?

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

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

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

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

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

Если протокол получать не требуется, код на PHP можно немного сократить:

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

Смотрим на результат и видим, что протокол отсутствует:

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

Получение URL в PHP без GET-параметров

Иногда эти параметры, передаваемые в качестве части ссылки, нас не интересуют, то есть требуется получить адрес без них. Мы говорим о следующих параметрах: name=anna&city=Valencia.

В действительности их можно отсечь, используя функцию explode в PHP, разбивающую строку по разделителю. Не стоит объяснять, что ссылка представляет собой строку, а параметры GET начинают прописываться после «?». В результате вопросительный знак и станет разделителем, а функция explode сделает из строки массив с 2-мя элементами. Первый элемент станет содержать искомую ссылку без GET-параметров, так как эти самые параметры останутся во втором элементе.

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

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

Получение только параметров GET

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

С помощью этого кода получим:

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

Источник

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

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