How can you efficiently handle URL collisions in a PHP URL Shortener application?

To efficiently handle URL collisions in a PHP URL Shortener application, you can generate a unique hash for each URL and check if it already exists in the database before creating a new shortened URL. If a collision is detected, you can generate a new hash until a unique one is found.

// Function to generate a unique hash for the URL
function generateUniqueHash($url) {
    $hash = md5($url); // Generate hash from URL
    // Check if hash already exists in the database
    if (checkIfHashExists($hash)) {
        // If hash exists, generate a new hash until a unique one is found
        while (checkIfHashExists($hash)) {
            $hash = md5($hash);
        }
    }
    return $hash;
}

// Function to check if hash already exists in the database
function checkIfHashExists($hash) {
    // Implement your database query here to check if the hash exists
    // Return true if hash exists, false otherwise
}