How can PHP be used to automatically save the redirected URL into a database when only the initial URL is known?

To automatically save the redirected URL into a database when only the initial URL is known, you can use PHP to capture the redirected URL using cURL or HTTP headers. Once the redirected URL is obtained, you can then save it to a database using SQL queries.

<?php
$initial_url = "http://example.com/initial-url";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $initial_url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

$redirected_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

// Save the redirected URL into a database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO redirected_urls (initial_url, redirected_url) VALUES ('$initial_url', '$redirected_url')";

if ($conn->query($sql) === TRUE) {
    echo "Redirected URL saved successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>