How can I check if a URL exists via PHP?

前端 未结 22 1674
天涯浪人
天涯浪人 2020-11-22 04:13

How do I check if a URL exists (not 404) in PHP?

22条回答
  •  不要未来只要你来
    2020-11-22 05:03

    get_headers() returns an array with the headers sent by the server in response to a HTTP request.

    $image_path = 'https://your-domain.com/assets/img/image.jpg';
    
    $file_headers = @get_headers($image_path);
    //Prints the response out in an array
    //print_r($file_headers); 
    
    if($file_headers[0] == 'HTTP/1.1 404 Not Found'){
       echo 'Failed because path does not exist.
    '; }else{ echo 'It works. Your good to go!
    '; }

提交回复
热议问题