Galgóczi Levente
Galgóczi Levente

Reputation: 101

How to get the current url with php?

Here is a problem with "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; when I using this code in a php file, which I called from a JS (with fetch or XMLHttpRequest), the output will be the the current url of this .php file!

Example I call PHP in JS (on my wordpress site):

    const item = document.querySelector('.item');
    fetch('path/wp-content/themes/current_theme_directory/called.php')
   .then(res => res.text())
   .then(responseText => item.innerHTML = responseText);

And my called.php file contain this code:

   $current_url = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
   echo $current_url;

My responseText in my JS this: path/wp-content/themes/current_theme_directory/called.php

In this situation how can I get the real current url, what shows my browser also?

Upvotes: 1

Views: 829

Answers (2)

Taki
Taki

Reputation: 17664

you can get the current url using javascript, it's in a variable called window.location.href

console.log(window.location.href); will log the current url in the console.

Upvotes: 1

l008com
l008com

Reputation: 1749

Technically $_SERVER['HTTP_REFERER'] will have the url that loaded the PHP, but keep in mind that info is easily edited by a crafty user.

Upvotes: 0

Related Questions