Why You Can't Put Variables Inside header('Location: ...')
You are attempting to redirect a user by placing a variable directly inside the URL string of the header() function, but there is a fundamental misunderstanding of how PHP handles output headers versus HTML content. The specific code snippet you provided mixes two different concepts: HTTP headers and HTML links.
In your current implementation, header('Location: <a href="...">...</a>'); does not work because header() expects a raw string representing the URL path (e.g., /path/to/page) or a full absolute URL. It does not parse HTML tags like <a>. When PHP executes that line, it sends an HTTP redirect signal to the browser with a malformed header containing literal text like <a href=...>, which results in a broken redirect or a security warning depending on the server configuration.
To achieve your goal, you must extract the variable value first and then concatenate it into the URL string before passing it to the header() function.
Extracting the Path Variable
Looking at your source code, you are already correctly parsing the current URL to isolate the path component. You use get_permalink() (which is a WordPress function) followed by parse_url(). This logic is sound for extracting just the path portion of the URL without the scheme or domain.
$url_endpoint = get_permalink();
$parsed_url = parse_url( $url_endpoint );
// Ensure we only take the path to avoid protocol-relative issues
$path = isset($parsed_url['path']) ? $parsed_url['path'] : '/';
Note: parse_url() returns an array with keys like scheme, host, and path. In your original code, you assign this array directly to $url_endpoint before accessing the 'path' key. Ensure you store the parsed result in a temporary variable first to avoid overwriting the string prematurely.
Constructing the Redirect Header
Once you have the clean path (or the full URL if that is what you intend to redirect to), you simply concatenate it into the header() call. If your goal is to redirect the user to a specific endpoint on http://linkhere.com, you should construct the string explicitly:
$destination_url = 'http://linkhere.com' . $url_endpoint;
if ( ! empty($useragent) && preg_match('/android.+mobile|avantgo/i', $useragent)) {
header('Location: ' . $destination_url);
} else {
// Fallback for desktop or non-matched agents
header('Location: http://linkhere.com');
}
This approach separates the logic:
- Variable Preparation: Calculate exactly where you want to go.
- Condition Check: Verify if the user agent matches mobile criteria.
- Header Injection: Send the raw redirect command with the correct URL appended.
The Danger of Mixing HTML in Headers
A common pitfall beginners face is trying to build complex URLs using echo statements or HTML tags inside header declarations. The header() function sends data directly to the HTTP protocol layer. Browsers expect headers to be plain text, not rendered markup. If you try to render an <a> tag as a redirect target, the browser receives a 302 status code pointing to a string that starts with <, which it interprets as a malformed URI.
Additionally, always ensure no whitespace or newlines exist between the PHP opening tag and the header() call. Even a single space before header can cause PHP to output a blank line, which triggers a "Headers already sent" fatal error. This is a frequent issue when developers inadvertently echo debug information or include CSS/JS files that print whitespace.
Security Considerations
When constructing destination URLs dynamically, you must be vigilant about Open Redirect vulnerabilities. If $url_endpoint contains user input (which it does not in your specific WordPress example since it comes from get_permalink()), you must validate the domain to ensure the redirect goes only to your trusted list of domains.
In your case, since you are hardcoding http://linkhere.com, the risk is lower, but it is still best practice to strip any query parameters or fragments that might attempt to hijack the session if the destination logic were to change later.
// Secure construction example
$base_url = 'https://linkhere.com'; // Use HTTPS in production
$path = isset($parsed_url['path']) ? $parsed_url['path'] : '/';
$safe_url = $base_url . $path;
header('Location: ' . $safe_url, true, 302);
Using the third argument of header() to explicitly set the status code (e.g., 302 for temporary redirect) can provide clarity in server logs and ensures the browser interprets the request correctly as a client-side redirect rather than a permanent move.
