How can one check if an HTML file (URL) has content before using file_get_contents in PHP?
When using file_get_contents in PHP to retrieve the contents of an HTML file from a URL, it's important to first check if the file exists or if there is content available to avoid errors. One way to do this is by using the get_headers function to check the HTTP response code of the URL. If the response code is 200, it means the file exists and has content. Only then should you proceed with using file_get_contents to retrieve the file contents.
$url = 'https://example.com/sample.html';
$headers = get_headers($url);
if (strpos($headers[0], '200') !== false) {
$html_content = file_get_contents($url);
// Proceed with processing the HTML content
} else {
echo 'Error: HTML file does not exist or has no content.';
}
Keywords
Related Questions
- In what ways can PHP developers optimize the processing of user input in a guestbook to maintain design integrity and prevent malicious code execution?
- Are there any specific considerations or modifications needed when transitioning from MySQL to MySQLi for login functionality in PHP?
- What are common pitfalls when using PHP to read directories and display specific file types?