What precautions should be taken when using file_get_contents or fopen to read external webpage contents in PHP?

When using file_get_contents or fopen to read external webpage contents in PHP, it is important to validate and sanitize the URL to prevent security vulnerabilities such as remote code execution or directory traversal attacks. One way to do this is by using filters or regular expressions to ensure that the URL is safe before passing it to the file_get_contents or fopen functions.

$url = filter_var($url, FILTER_VALIDATE_URL);
if ($url) {
    $contents = file_get_contents($url);
    // Process the contents as needed
} else {
    // Handle invalid URL
}