1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

cURL question, how to verify if URL is valid

Discussion in 'General PHP and MySQL Discussions' started by AndyB, Sep 6, 2013.

  1. AndyB

    AndyB Well-Known Member

    I would like to be able to use cURL and have the script determine if the file path is reachable. Here's an example of code that verifies the domain is reachable:

    PHP:

    <?php

    // Create a curl handle to a non-existing location
    $ch curl_init('http://www.google.com/');
    curl_setopt($chCURLOPT_RETURNTRANSFERtrue);

    if (
    curl_exec($ch) === false) {
        echo 
    'Curl error: ' curl_error($ch);
    }
    else
    {
        echo 
    'Operation completed without any errors';
    }

    // Close handle
    curl_close($ch);

    ?>

    This works fine. But if I change the path to something like this:

    http://www.google.com/path_to_invalid_image.jpg

    it still shows as a valid path.

    So how would I modify the code to show an error if the path to a file is invalid?
     
    Last edited: Sep 6, 2013
  2. Chris D

    Chris D XenForo Developer Staff Member

    I'm not sure how to do it with cURL actually.

    I tend to use the XenForo_Helper_Http class.

    Incredibly easy to use.

    But in relation to the code you've already written, I think you need this:

    PHP:
    $httpCode curl_getinfo($chCURLINFO_HTTP_CODE);
    Obviously if $httpCode contains 404, 403 etc. then you can throw an error.
     
  3. KenSmith

    KenSmith Active Member

    To do it with curl, add
    curl_setopt($ch, CURLOPT_FAILONERROR, true);

    If you just want to make sure the URL exists, you should be also doing a HEAD request instead of a GET to avoid transferring the data.

    For that, see the option CURL_NOBODY.
     
    AndyB and Chris D like this.
  4. AndyB

    AndyB Well-Known Member

    Hi Ken,

    Thank you kindly for your information, works perfectly.

    PHP:

    <?php

    // Create a curl handle to a non-existing location
    $ch curl_init('http://www.google.com/path_to_invalid_image.jpg');

    curl_setopt($chCURLOPT_FAILONERRORtrue);
    curl_setopt($chCURLOPT_NOBODYtrue);

    if (
    curl_exec($ch) === false) {
        echo 
    'Curl error: ' curl_error($ch);
    }
    else
    {
        echo 
    'Operation completed without any errors';
    }

    // Close handle
    curl_close($ch);

    ?>

     
    Jan_Nemecek likes this.
  5. DRE

    DRE Well-Known Member

  6. AndyB

    AndyB Well-Known Member

    DRE likes this.

Share This Page