php get page url

В этой статье будет рассказано о том, как в языке программирования 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 page url. Смотреть фото php get page url. Смотреть картинку php get page url. Картинка про php get page url. Фото php get page url

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

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

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

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

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

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

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

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

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

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

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

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

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

Источник

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

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

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

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

Function adjusted to execute without warnings:

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

Fun ‘base_url’ snippet!

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

will create output like this :

and if this script works fine.

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

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

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

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

This is the best method i think so.

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

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

and you get something like

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

Just test and get the result.

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

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

Источник

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:

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

11 Answers 11

$_SERVER[‘QUERY_STRING’] contains the data that you are looking for.

DOCUMENTATION

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

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

The PHP way to do it is using the function parse_url, which parses a URL and return its components. Including the query string.

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

The function parse_str() automatically reads all query parameters into an array.

EDIT

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

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:

Источник

How to get URL of current page displayed?

Can I attach get_permalink() to a particular hook that fires before the loop is executed? Or can I somehow break out of the loop, or reset it once it is complete?

13 Answers 13

get_permalink() is only really useful for single pages and posts, and only works inside the loop.

The simplest way I’ve seen is this:

$wp->request includes the path part of the URL, eg. /path/to/page and home_url() outputs the URL in Settings > General, but you can append a path to it, so we’re appending the request path to the home URL in this code.

And you could combine these two methods to get the current URL, including the query string, regardless of permalink settings:

You may use the below code to get the whole current URL in WordPress:

This will show the full path, including query parameters.

That is for single pages.

For category pages, use this:

Simple script to get the current URL of any page:

The following code will give the current URL:

You can use the below code to get the full URL along with query parameters.

This will show the full path, including query parameters. This will preserve query parameters if already in the URL.

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

In my case, this code worked fine:

I hope it will help someone, I tried all answers but this one was helpful.

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

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

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

This is an improved way of example that mentioned previously. It works when pretty URLs are enabled however it discards if there is any query parameter like /page-slug/?param=1 or URL is ugly at all.

Following example will work on both cases.

Maybe wp_guess_url() is what you need. Available since version 2.6.0.

This is what worked for me (short and clean solution that includes the query strings in the URL too):

The output URL will look like below

The solution was taken from here

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

It’s a global wp function that grabs whatever relates to the current url you’re on. So for instance if you’re on a page or post, it’ll return a post object. If you’re on an archive it will return a post type object.

WP also has a bunch of helper functions, like get_post_type_archive_link that you can give the objects post type field to and get back its link like so

The point is, you don’t need to rely on some of the hackier answers above, and instead use the queried object to always get the correct url.

This will also work for multisite installs with no extra work, as by using wp’s functions, you’re always getting the correct url.

Источник

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

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