Search code examples
codeigniterif-statementfile-get-contents

Manupulate Error file_get_contents


I have a script

$data = file_get_contents('http://my_example_link/data.xml');

and if http://my_example_link/data.xml is showing error

Failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found

I would like to create condition if the link is showing error above I will showing alert notification using bootstrap panel.

can I doing like that ?


Solution

  • You can do it with curl, Please refer curl_getinfo

    <?php
    // Create a cURL handle
    $ch = curl_init('http://www.example.com/');
    
    // Execute
    curl_exec($ch);
    
    // Check HTTP status code
    if (!curl_errno($ch)) {
      switch ($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
        case 200:  # OK
          break;
        default:
          echo 'Unexpected HTTP code: ', $http_code, "\n";
      }
    }
    
    // Close handle
    curl_close($ch);
    ?>