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();
?>
Related Questions
- What are the potential pitfalls of using the @ symbol to suppress errors in PHP shell commands?
- What are the best practices for structuring HTML elements within PHP code to ensure proper rendering and styling?
- How can PHP be used to ensure that a user must enter their name and at least one other contact field in a mail form?