hi i want to read the whole URL passing through the address bar and asssign it to a variable .Please help me

Dani AI

Generated

A quick clarification: there are two different problems behind "read the whole URL from the address bar." If you need the exact value the browser shows (including the hash/fragment), read it in the browser. If you need the URL as the server saw the request, reconstruct it from request headers. , pointed you toward server variables — that is the right direction, but there are a few important gotchas below.

Client-side (full address, includes fragment)

const fullUrl = window.location.href;

// send to server if you must capture it
fetch('/capture-url.php', {
  method: 'POST',
  headers: {'Content-Type': 'application/x-www-form-urlencoded'},
  body: 'url=' + encodeURIComponent(fullUrl)
});

Browser Location API only: fragments (the part after #) never reach the server. See MDN: Location.href.

Server-side (what the server received)

function get_current_url() {
    $scheme = 'http';
    if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') $scheme = 'https';
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) $scheme = $_SERVER['HTTP_X_FORWARDED_PROTO'];
    $host = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'];
    $port = isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : null;
    $request = $_SERVER['REQUEST_URI'] ?? ($_SERVER['PHP_SELF'] . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : ''));
    if ($port && (($scheme==='http' && $port!==80) || ($scheme==='https' && $port!==443))) $host .= ':' . $port;
    return $scheme . '://' . $host . $request;
}

This rebuilds scheme, host (with port when nonstandard) and request path+query. PHP $_SERVER variable details: PHP manual — Server/Request vars.

Security and practical notes

  • Do not blindly trust HTTP_HOST (it can be client-controlled). Validate it against a whitelist or use a configured canonical host when producing links.
  • HTTP_XFORWARDED* headers should only be trusted when you are behind a trusted proxy.
  • Escape any URL before echoing into HTML (e.g., htmlspecialchars) and validate with filter_var(..., FILTER_VALIDATE_URL) if you store or use it.
  • was right to suggest request-based variables; , use JS when you need fragments or the exact client view.

Recommended Answers

All 2 Replies

URL of the current page :

$current_url = $_SERVER['REMOTE_ADDR'].$_SERVER['PHP_SELF'];

echo $current_url;

- Mitko Kostov

I was wrong posted the code above in a hurry.

You can use :

echo  'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']; 

echo 'http://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

echo 'http//'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];

- Mitko Kostov

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.