1

I am using file_get_contents to fetch data from a 3rd party, however the 3rd party is experiencing a DDOS attack at the moment and therefore, most of my sites functionality is lost.

How can I set a redirect to another page if opening the stream fails?

The Codesee
  • 3,714
  • 5
  • 38
  • 78
Chris 'Pig' Hill
  • 175
  • 2
  • 12

5 Answers5

1

This will help you:

$url = "http://example.com/url";

$response = get_headers($url);
if($response[0] === 'HTTP/1.1 200 OK') {
   // Request response is OK
   $content = file_get_contents($url);
} else {
   // if header response is NOT OK redirect...
   header("Location: someUrlGoesHere"); 
}
stollr
  • 6,534
  • 4
  • 43
  • 59
1

Change the default timeout, then redirect on failure.

You can change the default timeout used for file_get_contents like so:

ini_set('default_socket_timeout', 10); // 10 seconds

We need to do this, because the default timeout is 60 seconds - and your visitors won't want to wait that long.

Then you just test if the request went ok, and redirect based on that...

$request = file_get_contents($url);
if( !$request )
   header("Location: http://someurl.com/");
exit;

(Remember to exit after a redirect, or sometimes code after that still gets executed).

HappyTimeGopher
  • 1,377
  • 9
  • 14
0

You can redirect it with header().

<?php
$data = file_get_contents($attackedUrl);
if(!$data)
   header("Location: $pageToRedirect");
?>
Volkan Ulukut
  • 4,230
  • 1
  • 20
  • 38
0

Simple. Add validation!

First, there's several methods to check if a file exists on a remote server.

Second, if you fetch data using file_get_contents, you can add validation to check if it's the full data you expected (other answers / comments mention checking using empty, or checking for a falsey value. It's up to you how you do this though, as there's no context provided about the type of data received). You can also set a timeout value in case it takes too long to fetch!

And to redirect, you can use PHP's header function, like so:

header('Location: http://my.redirected/page/href');

However, header() will not work if you have already outputted content., so please make sure you check through your script for echo / print lines before running header

Community
  • 1
  • 1
Sean
  • 2,278
  • 1
  • 24
  • 45
0

https://www.php.net/manual/fr/function.is-file.php

<?php 
$url = "../../filename.php";
if (is_file($url))
     echo "File Exist!";
    //$request = file_get_contents($url);
    //print(filesize($url))." ko";
else
     echo "File not Exist!";
?>
Smar ts
  • 49
  • 5