Php echo requested url

Как в php получить текущий URL?

Сегодня поговорим о том, как получить адрес страницы в php.

Зачем это может быть нужно?

Сценарии могут быть разными. Например, у нас используется один и тот же шаблон для разных разделов. Но в одном из разделов нам необходимо вывести (или не вывести) какой-то специфичный блок, которого в других разделах быть не должно.

Вероятно мы захотим сделать это по условию. И именно в условии мы и будем проверять тот ли это раздел.

Возможно с архитектурной точки зрения – это не самое лучшее решение. Однако, очень часто нам достаются уже готовые проекты, с которыми нужно что-то делать.

Получаем URL текущей страницы

Чтобы получить необходимую информацию, мы будем обращаться к такой глобальной переменной в php, как $_SERVER.

Переменная $_SERVER – это массив, который хранит в себе много полезной информации: заголовки, пути, местоположения скриптов.

Если вы хотите посмотреть всё, что хранит этот массив, то можете воспользоваться следующим кодом, который в читабельном виде выведет все значения:

Читайте также:  Check if variable is defined or not

Итак, давайте представим, что у нас есть веб страница следующего вида: http://localhost/php-lessons/url/?name=anna&city=Valencia.

Я тестирую на локальном сервере. Когда вы будете работать с реальным сайтом, который лежит в сети, то вместо localhost у вас будет имя вашего сайта (например exmple.ru).

Что мы видим в нашем подопытном url?

  • Нас может интересовать адрес страницы без GET-параметров;
  • адрес страницы с GET-параметрами;
  • или просто сами GET-параметры без адреса страницы.

Давайте разберемся с каждой ситуацией.

Получаем полный URL страницы в php

Чтобы получить полный URL страницы вместе с GET-параметрами, воспользуемся следующим кодом:

$url = ((!empty($_SERVER['HTTPS'])) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; echo $url;

Сначала мы проверяем, какой протокол используется: https или http.

Если значение $_SERVER[‘HTTPS’] не пусто, значит это https, иначе http.

Далее мы присоединяем двоеточие и 2 слэша, имя домена (хоста) и остальную часть нашего URL.

Результат будет вот таким:

http://localhost/php-lessons/url/?name=anna&city=Valencia

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

Результат тогда будет следующим:

localhost/php-lessons/url/?name=anna&city=Valencia

Получаем URL страницы без GET-параметров в php

Иногда нас не интересуют GET-параметры, которые передаются как часть URL, и нам нужно получить адрес без них.

GET-параметры в нашем случает – это name=anna&city=Valencia

Чтобы отсечь их мы можем использовать php-функцию explode, которая разбивает строку по разделителю.

Наш URL – это ни что иное, как строка. GET-параметры всегда начинают передаваться после знака “?”. Следовательно разделителем будет вопросительный знак.

Функция explode превратит строку в массив с двумя элементами. В первом будет содержаться наш искомый url без GET-параметров, а во втором останутся GET-параметры.

Результат будет таким: http://localhost/php-lessons/url/

Получаем GET-параметры из URL

Здесь совсем все просто. Чтобы получить только GET-параметры будем использовать следующий код:

name=anna&city=Valencia

Дальше мы можете разобрать это строку, например, с помощью функции explode или сделать с ними что-либо еще (в зависимости от стоящей перед вами задачи).

Ставьте лайки, оставляйте комментарии, подписывайтесь на обновления!

Здесь только полезные вещи 😉

Источник

Как получить текущий URL в PHP?

Сформировать текущий адрес страницы можно с помощью элементов массива $_SERVER. Рассмотрим на примере URL:

Полный URL

$url = ((!empty($_SERVER['HTTPS'])) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; echo $url;

Результат:

https://example.com/category/page?sort=asc

URL без GET-параметров

$url = ((!empty($_SERVER['HTTPS'])) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; $url = explode('?', $url); $url = $url[0]; echo $url;

Результат:

https://example.com/category/page

Основной путь и GET-параметры

$url = $_SERVER['REQUEST_URI']; echo $url;

Результат:

Только основной путь

$url = $_SERVER['REQUEST_URI']; $url = explode('?', $url); $url = $url[0]; echo $url;

Результат:

Только GET-параметры

Результат:

Для преобразования строки с GET-параметрами в ассоциативный массив можно применить функцию parse_str() .

parse_str('sort=asc&page=2&brand=rich', $get); print_r($get);

Результат:

Array ( [sort] => asc [page] => 2 [brand] => rich )

Комментарии 2

Авторизуйтесь, чтобы добавить комментарий.

Другие публикации

Чтение Google таблиц в PHP

Как получить данные из Google spreadsheets в виде массива PHP? Очень просто, Google docs позволяет экспортировать лист в формате CSV, главное чтобы файл был в общем доступе.

Сортировка массивов

В продолжении темы работы с массивами поговорим о типичной задаче – их сортировке. Для ее выполнения в PHP существует множество функций, их подробное описание можно посмотреть на php.net, рассмотрим.

Источник

Echo the Requested URL in PHP

Here is the url page1.php page2.php: I want to get the parameter from the previous url in page1.php. So depending on the language and framework you’re using you may not have to go through the translation yourself (which can be a pain in the ***) Question: How can i get the value of previous url in php code?

Echo the Requested URL in PHP

I am not even A PHP newbie. But I need to call BS on a outside consultant who has come to my company and told me something was impossible.

Is it possible in PHP to simply create a webpage that displays the URL requested by the user.

In other words: rather than echoing/Printing «Hello World»

I would like the page to print the URL that the user requested.

This can be accomplished with:

Another useful one is $_SERVER[‘HTTP_HOST’]

If you’re going to do a redirect, you have more footwork to do, but a straightforward solution would be:

header(«Location: ?original_request=»); — and then handle the rest in the page you redirect to.

I think what you are looking for is the full url. This can be done with.

$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; echo $url; 

Just incase the port is included.

$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]); $url = "http://".$_SERVER['HTTP_HOST'].$port.$_SERVER['REQUEST_URI']; 

In a sense, both you and the consultant are correct. In most cases, yes you can get the exact URL. In many cases, the URL will be approximate. In some cases, you might not get anywhere close to the requested URL.

Here are some barriers to building the exact URL:

  1. The #fragment isn’t sent
  2. You don’t know if :port was present (so you can’t know whether to add it or not)
  3. You don’t know what outside PHP rerouting was done (eg in .htaccess)

You could get around these by having a hidden input variable that is filled by Javascript with the full URL, which is then posted. But then the argument is «well what if Javascript isn’t turned on.»

So, I’d say «yes you can» is the practical/pragmatic answer, while «no you can’t» is the academic answer.

How to call url of any other website in php, php // create a new cURL resource $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, «http://www.example.com/»);

PHP How to get URL parameters GET POST method

Download the source code here https://jinujawad.com/php-how-to-get-url-parameters-get
Duration: 12:39

URL Parameters | PHP

Giraffe Academy is rebranding! I’ve decided to re-focus the brand of this channel to highlight
Duration: 7:13

Get Current Page URL in PHP

How to get url in php?

I want to get the url in php. In my root directory «myproject»->book folder/index.php file

Kindly check what I am doing:

I am accessing the url on adressbar http://localhost:8080/myproject/book/index.php?id=myurl

If I want to access http://localhost:8080/myproject/book/

The output will be: http://localhost:8080/myproject/book/

Till now all are working fine. But I want to get url like below, remove on my index.php file the actual url will be http://localhost:8080/myproject/book/index.php?id=myurl but I want when user hit url below

http://localhost:8080/myproject/book/myurl 

It can access the url http://localhost:8080/myproject/book/index.php?id=myurl but on the addressbar still url show http://localhost:8080/myproject/book/myurl

Any idea or suggestion would be welcome.

You should use mod_rewrite directives in Apache web-server configuration file .htaccess in the root of web-site, or nginx analog.

It depends on your webserver, here are solutions for the main 3:

Microsoft IIS Rewrite rules

I think the hardest to accomplish are the ones on IIS, but all of them need some getting-used-to . Enjoy

Most of the web frameworks have built in rewrite rules or routing with params instead of query parameters. So depending on the language and framework you’re using you may not have to go through the translation yourself (which can be a pain in the ***)

How to call an url in php file? [duplicate],

How can i get the value of previous url in php code?

How can i get the value of previous url in php code?

http://localhost/spk/kelulusan_process.php?lulus=10003 

page2.php:
I want to get the parameter from the previous url in page1.php. I use

For $_GET to work you have to redirect user using form action

Or you can do that by setting session variables and access them any page

You can try $_SERVER[«HTTP_REFERER»]

But don’t forget to escape $_SERVER[«HTTP_REFERER»] since it’s common for attacks.

Better is to store the current page in a $_SESSION var.

if (!isset($_SESSION)) < session_start(); >$_SESSION['lastpage'] = $_SERVER['REQUEST_URI']; 

Then when loading the next page:

if (!isset($_SESSION)) < session_start(); >// now you can access the last page $lastpage = $_SESSION['lastpage']; 

how are you trying to pass from page 1? if through a form set the method to get and action to page2.php

in page1.php make sure you set the name

You cannot display $_GET[‘lulus’]; in page2.php unless you write get parameter in page2.php.

Your code is redirect from page1.php to page2.php, You must set $_GET[‘lulus’]; into one session and echo in page2.php

Instead, echo $_GET[‘lulus’], you should echo in page2.php $_SESSION. Because $_SESSION variable was overrode by $_GET itself.

Get the full URL in PHP, Get the full URL in PHP · Create a PHP variable that will store the URL in string format. · Check whether the HTTPS is enabled by the server.

Get the folder name via php request url

I need current folder name via PHP. I already know basename will help this.

But It wont help me because of my folder structure.

|template.php
|/pages/
|/pages/ requiredfoldername /index.php

So in my index.php it’s just one line

So my question is what should i write to template.php for getting current foldername?

getcwd(); or dirname(__FILE__); or (PHP5) basename(__DIR__) 

dirname : Given a string containing the path of a file or directory, this function will return the parent directory’s path.

__FILE__ : The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.

Inside template.php, __FILE__ is the absolute path to template.php:

/[path to your app]/template.php

Then dirname(__FILE__) return:

Inside index.php, __FILE__ is the absolute path to index.php:

/[path to your app]/pages/requiredfoldername/index.php

Then dirname(__FILE__) return:

/[path to your app]/pages/requiredfoldername

Also in template.php, maybe $_SERVER would help you with the key ‘SCRIPT_FILENAME’. This key contains the absolute path (with exceptions in CLI) to the currently executing script:

If /pages/requiredfolder/index.php is your entry point to the app, when you include template.php, the currently executing script remains index.php. So $_SERVER[‘SCRIPT_FILENAME’] will be

‘/[path to your app]/pages/requiredfoldername/index.php’

Using dirname with $_SERVER[‘SCRIPT_FILENAME’] results in:

‘/[path to your app]/pages/requiredfoldername’

Thank you all, I asked to my friend and he come up with this solution. And it works.

How to get and change URL variable PHP, Suppose you have url like :- and you want to replace parameter b’s value to test3

Источник

Оцените статью