• Hello,
    I am trying to check if an URL exists and then execute code if it does. The URL I am testing is in the format https://www.example.com/query, where query is a value I get from a html form. This is what I have now (based on examples I have found online):

    <?php
    if(!empty($_POST)){
       $query = $_POST['query'];
       $url = "https://www.example.com/" . $query;
       $accepted_status_codes = array(200, 301, 302);
       $response = wp_remote_get("{$url}");
       $response_code = wp_remote_retrieve_response_code($response);
       if(in_array($reponse_code, $accepted_status_codes)){
          echo "This works";
       }
    }
       ?>

    I don’t understand why the code above doesn’t work (the URL and query works, but not testing if the url exists). The program is in a separate php-file in my child theme. All help is very much appreciated!

    Thank you.

Viewing 1 replies (of 1 total)
  • Hi,

    In:

    if(in_array($reponse_code, $accepted_status_codes)){
         echo "This works";
    }

    $reponse_code should be $response_code (you left out the first ‘s’).

    Maybe you should remove the double quotes surrounding the $url parameter in your wp_remote_get call. Thus, $response = wp_remote_get($url);

    Finally wp_remote_get and wp_remote_retrieve_response_code may return errors. You need to check that with if ( is_wp_error( $response ) ) { /* Do something */ } and if ( is_wp_error( $response_code ) ) { /* Do something */ } respectively.

    Note that remote get functions may fail for reasons other than the URL being non-existent.

Viewing 1 replies (of 1 total)
  • The topic ‘Check if URL exists with PHP’ is closed to new replies.