What is the best way to see a URL exists and the response is not a 404 ?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
You can use
get_headers($url)
Example 2 from Manual:
The first array element will contain the HTTP Response Status code. You have to parse that.
Note that the
get_headers
function in the example will issue an HTTP HEAD request, which means it will not fetch the body of the URL. This is more efficient than using a GET request which will also return the body.Also note that by setting a default context, any subsequent calls using an http stream context, will now issue HEAD requests. So make sure to reset the default context to use GET again when done.
PHP also provides the variable $http_response_header
If you want to download the content of a remote resource, you don't want to do two requests (one to see if the resource exists and one to fetch it), but just one. In that case, use something like
file_get_contents
to fetch the content and then inspect the headers from the variable.@Gordon - Here is a more complete library routine based on your answer. It includes some preliminary checking for URL validity, some more error handling, and parsing of the returned headers. It also follows any redirect chains for a reasonable number of steps.
With apologies to @FranciscoLuz - if you're expecting errors based on user input, the "@ and error_get_last" method seems perfectly sensible to me - I don't see that there's anything more proper about using set_error_handler.
BTW, not sure if I should have done this as an edit to @Gordon's answer rather than as a separate answer. Can someone advise?