cURL , get redirect url to a variable

cURL , get redirect url to a variable

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Capturing Redirect URLs with cURL

When you use curl to submit a form, the server often responds with an HTTP 302 (Found) or 303 (See Other) status code instead of returning the data directly in the body. The response headers contain a Location field pointing to the next URL, but if you simply execute the command in a shell without capturing that header, the redirect happens immediately and silently. To handle this programmatically, you must explicitly tell curl to follow the redirect and then extract the final destination from the output stream or headers before the process completes.

The most straightforward approach is using the -L flag, which instructs curl to automatically follow any redirects. However, relying solely on this flag often results in the final URL being printed to standard output along with other data, making it difficult to isolate. If you only need the location string and not the content of the final page, you can suppress the body output while keeping the headers visible using -s (silent) combined with -I (head info), or by parsing the full response.

Consider a scenario where you are submitting a form via POST. You send the request, and the server responds with a redirect header before sending a 302 status. If your script needs to log that specific URL for analytics or further processing, you need to capture it from the HTTP headers rather than waiting for curl to finish downloading the redirected resource.

Here is a practical method using standard Unix pipes and text processing tools like awk or grep:

curl -sL -D - "https://example.com/form" | grep -i "^Location:" | awk '{print $2}'

In this command, -D - dumps the headers to standard output while -sL handles the silent follow of redirects. The pipe sends this header stream to grep, which filters for the line starting with Location:, and awk extracts the URL that follows the colon. This works well in a POSIX shell environment because it separates the logic of following the redirect from the logic of extracting the string.

If you are working within a Laravel application or need to integrate this into a PHP script, you should switch to the native curl_init() functions or the Guzzle HTTP client, which offers more robust handling of redirects and response objects. In pure PHP without external libraries, you can initialize the handle with CURLOPT_FOLLOWLOCATION enabled (value true) and use CURLOPT_RETURNTRANSFER set to true so the response is returned as a string instead of being output directly. You can then parse the $response_headers array or the full $response object depending on your version of PHP.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com/form');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, true); // Include headers in the response string

$response = curl_exec($ch);
curl_close($ch);

// Parse the raw response to find the last Location header if multiple exist
$lines = explode("\r\n", $response);
$location = null;
foreach ($lines as $line) {
    if (stripos($line, 'Location:') !== false) {
        // Remove 'Location:' prefix and trim whitespace
        $location = ltrim(substr($line, strpos($line, ':') + 1), " \t\r\n");
    }
}

echo $location;

One critical pitfall to avoid is assuming that the Location header points to the final destination immediately. In some complex server configurations, a 302 might redirect to an intermediate URL (like a captcha service or a logging endpoint), which then issues its own redirect. If you only capture the first Location header without following it, you will get the wrong URL. This is why enabling CURLOPT_FOLLOWLOCATION in PHP or using -L in the shell is essential when the goal is to reach the final resolved URL.

Additionally, be aware that some servers use meta refreshes instead of HTTP redirects, or they return a 200 OK status with JavaScript that performs the redirect client-side. Standard curl commands will not follow these without specific flags like -k (insecure, for self-signed certs) or custom user-agent headers to mimic browser behavior if the server blocks non-browser requests.

For developers looking to manage complex form submissions and redirection logic within a Laravel ecosystem, leveraging packages designed for HTTP clients can simplify this process further than raw curl commands. Resources like https://laravelcompany.com often highlight best practices for handling HTTP interactions in the framework, suggesting that while low-level tools are powerful, higher-level abstractions reduce boilerplate code and potential errors when dealing with status codes and headers.

Our network