简体   繁体   中英

Retry if failed to open stream: HTTP request failed! 1 PHP

Im trying to open an api and extract some data and about 1/5 times the script runs it errors with a

PHP Warning: file_get_contents( http://192.168.1.52/home.cgi ): failed to open stream: HTTP request failed! 1

I would like to retry opening the api on error and then follow through with the rest of the code

This is running on a Pi using PHP5

$inverterDataURL = "http://".$dataManagerIP."/home.cgi";


$context = stream_context_create(array('http'=>array('protocol_version'=>'1.1')));
$result = file_get_contents('http://192.168.1.11/home.cgi', false, $context);

20% of the time when running the script it errors trying to open the api and without the api being open i can't grab any data out of it. the rest of the script runs through fine when it opens correctly

You should use a loop for the retry logic that breaks when the result succeeds. A do ... while loop is used here because it guarantees that it'll be run at least once (therefore guaranteeing that $result will be set to something ). When the file_get_contents fails, $result will be false:

<?php

$context = stream_context_create(array('http'=>array('protocol_version'=>'1.1')));

do {
  $result = file_get_contents('http://127.0.0.1/home.cgi', false, $context);
  if (!$result) {
    echo "Waiting 3 seconds.\n";
    sleep(3);
  }
} while( !$result);

If the server goes down, you'll probably want something to break the loop after a few tries. This bit will stop trying after 5 failures.

<?php

$context = stream_context_create(array('http'=>array('protocol_version'=>'1.1')));

$attempts = 0;
do {
  $attempts++;
  echo "Attempt $attempts\n";
  $result = file_get_contents('http://127.0.0.1/home.cgi', false, $context);
  if (!$result) {
    echo "Attempt $attempts has failed. Waiting 3 seconds.\n";
    sleep(3);
  }
} while( !$result && $attempts < 5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM