How to check if a webpage exists. jQuery and/or PHP

后端 未结 4 631
长发绾君心
长发绾君心 2021-01-05 07:55

I want to be able to validate a form to check if a website/webpage exists. If it returns a 404 error then that definitely shouldn\'t validate. If there is a redirect...I\'m

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-05 08:57

    It sounds like you don't care about the web page's contents, you just want to see if it exists. Here's how I'd do it in PHP - I can stop PHP from taking up memory with the page's contents.

    /*
     * Returns false if the page could not be retrieved (ie., no 2xx or 3xx HTTP
     * status code). On success, if $includeContents = false (default), then we
     * return true - if it's true, then we return file_get_contents()'s result (a
     * string of page content).
     */
    function getURL($url, $includeContents = false)
    {
      if($includeContents)
        return @file_get_contents($url);
    
      return (@file_get_contents($url, null, null, 0, 0) !== false);
    }
    

    For less verbosity, replace the above function's contents with this.

    return ($includeContents) ? 
                   @file_get_contents($url) :  
                   (@file_get_contents($url, null, null, 0, 0) !== false)
    ;
    

    See http://www.php.net/file_get_contents for details on how to specify HTTP headers using a stream context.

    Cheers.

提交回复
热议问题