Home > Back-end >  How to get the full current URL in PHP with the query string and parse it?
How to get the full current URL in PHP with the query string and parse it?

Time:08-16

I've went through tons of websites and a few pages of StackOverflow however I just can't find somethting that works.

So, what I'm trying to do is get the current URL of the page with the query strings so I can parse it, but it doesn't work and I don't know what I'm doing wrong.

Here is my current code:

$url = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";  
$CurPageURL = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];  
parse_str($url_components['query'], $params);
$id = $params['id'];

Here is where I'm using that $id variable later on:

<h3 ><?=$id?>, please enter your staff password below.</h3>

No errors are being thrown, please help!, Thanks!

CodePudding user response:

try this instead:

<?php
$br       = "<br>";
$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']), 'https') === FALSE ? 'http' : 'https';
$hostame  = $_SERVER['HTTP_HOST'];
$script   = $_SERVER['SCRIPT_NAME'];
$params   = $_SERVER['QUERY_STRING'];
if ($params == ""){
    $currentUrl = $protocol . '://' . $hostame . $script . $params;
}
else {
    $currentUrl = $protocol . '://' . $hostame . $script . '?' . $params;
}
?>

URL: <?php echo $currentUrl . $br; ?>
Protocol: <?php echo $protocol . $br; ?>
Hostname: <?php echo $hostame . $br; ?>
<?php 
if ($script == ""){ 
    exit; 
} else {
    echo "Page / Script: " . $script . $br; };
if ($params == ""){
    exit; 
} else { 
    echo "Params: " . $params . $br; }; 
?>
  • Related