What are the best practices for efficiently handling URL existence checks in PHP to avoid security vulnerabilities?

When handling URL existence checks in PHP, it is important to avoid using functions like file_get_contents or fopen with user-provided URLs as they can lead to security vulnerabilities such as remote code execution or directory traversal attacks. Instead, it is recommended to use cURL library to safely perform URL existence checks in PHP.

// Initialize cURL session
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute cURL session
curl_exec($ch);

// Get HTTP response code
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

// Close cURL session
curl_close($ch);

// Check if URL exists based on HTTP response code
if ($httpCode == 200) {
    echo "URL exists";
} else {
    echo "URL does not exist";
}