0

I am trying to get my code to work when the url its sent to does not have the variables needed.

this is the error:

E_WARNING : type 2 -- file_get_contents(the link): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found -- at line 23

Ex my code goes to this users page and everything okay:

https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/24267598/ranked?season=SEASON2016&api_key=e9044828-20e3-46cc-9eb5-545949299803

But when it goes to this users page it gives a error:

https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/77828400/ranked?season=SEASON2016&api_key=e9044828-20e3-46cc-9eb5-545949299803

What im after doing if when there is no content in url for it not to show anything and when there is to show it. But for some reason I cant get it to work with both.

Here is my code:

<?php
$apiKey = 'APIKEY';
$summonerName = 'raget deathdex';
$new = rawurlencode($summonerName);

$news = str_replace(' ', '', $summonerName);
$str = strtolower($news);

$result = file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/' . $new . '?api_key=' . $apiKey);
$summoner = json_decode($result)->$str;
$id = $summoner->id;
?>  

<?php   
$claw = file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/' . $id . '/ranked?season=SEASON2016&api_key=' . $apiKey);
$gaza = json_decode($claw);
?>

<?php 
$entriesz = $gaza->champions;
usort($entriesz, function($ac,$bc){
    return $bc->stats->totalSessionsPlayed-$ac->stats->totalSessionsPlayed;
});

foreach($entriesz as $statSummaryz) if ($tmp++ < 11){

    $getLeagueNamelistside = $statSummaryz->id;
    $getsessionsplayedNamelistside = $statSummaryz->stats->totalSessionsPlayed;
    $getMiniomskillsNamelistside = $statSummaryz->stats->totalMinionKills;
    $getkillsNamelistside = $statSummaryz->stats->totalChampionKills;
    $getassistssNamelistside = $statSummaryz->stats->totalAssists;
    $getdeathsNamelistside = $statSummaryz->stats->totalDeathsPerSession;
    $getlosseslistside = $statSummaryz->stats->totalSessionsLost;
    $getwinslistside = $statSummaryz->stats->totalSessionsWon;

    $Percentkillrateside = $getkillsNamelistside / $getsessionsplayedNamelistside;
    $Percentassistrateside = $getassistssNamelistside / $getsessionsplayedNamelistside;
    $Percentdeathrateside = $getdeathsNamelistside / $getsessionsplayedNamelistside;
    $KDAside = ($getkillsNamelistside + $getassistssNamelistside) / $getdeathsNamelistside;
    $KDAMinniomsSide = $getMiniomskillsNamelistside / $getsessionsplayedNamelistside;
    $PercentWinRateSide = 100 / ($getlosseslistside + $getwinslistside) * $getwinslistside;

    if ($getLeagueNamelistside >=1){

        $resultz = file_get_contents('https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion/'.$getLeagueNamelistside.'?api_key=' . $apiKey);
        $summonerz = json_decode($resultz, true);
        $getLeagueNamelistsidez = $summonerz['name'];
        $getLeagueKeyNamelistsidez = $summonerz['key'];
        echo '<p><img src="http://lolchecker.esy.es/LOLGGWP/img/champion/' .$getLeagueKeyNamelistsidez. '.png"></p>'.$getLeagueNamelistsidez. '<p> Kills '.number_format((float)$Percentkillrateside, 1, '.', '').'</p><p> Deaths '.number_format((float)$Percentdeathrateside, 1, '.', '').'</p><p> Assists '.number_format((float)$Percentassistrateside, 1, '.', '').'</p><p> KDA '.number_format((float)$KDAside, 2, '.', '').':1 KDA</p><p> CS '.number_format((float)$KDAMinniomsSide, 1, '.', '').' CS</p><p> Games Played '.$getsessionsplayedNamelistside.'</p><p> Win Rate '.number_format((float)$PercentWinRateSide, 0, '.', '').'%</p>';

    }
    elseif($getLeagueNamelistside =0){
        return DO_NOTHING;

    }

}
?>
fusion3k
  • 11,568
  • 4
  • 25
  • 47
  • You are using different urls as 1st is `24267598/ranked` & 2nd is `77828400/ranked`; – itzmukeshy7 Apr 01 '16 at 17:49
  • Yes, as they are for different users, what i need the code to do is if it give error like in user 2 not to show anything and if not continues, but cant find away to do that – Aaron Bailey Apr 01 '16 at 17:50
  • 1
    Then you should check if `status_code` exists within the object and handle it accordingly – Derek Pollard Apr 01 '16 at 17:53
  • Possible duplicate of [file\_get\_contents() how to fix error "Failed to open stream", "No such file"](http://stackoverflow.com/questions/20562368/file-get-contents-how-to-fix-error-failed-to-open-stream-no-such-file) – Will B. Apr 01 '16 at 19:27

3 Answers3

0

Is this what you're trying to do?

PHP treats strings like a byte array. Instead of checking if a string is empty of if the strings length is greater than 0, I like to check to see if the first byte is set. Some people consider it less humanly readable, but thats just some people.

Use isset($mystring[0]) to see if a string is at least one character in length.

The @ symbol before the file_get_contents is for error suppression. The @ prevents an error from appearing in your browser if the file can't be found.


<?php
$apiKey = 'e9044828-20e3-46cc-9eb5-545949299803';
$summonerName = 'raget deathdex';
$new = rawurlencode($summonerName);

$news = str_replace(' ', '', $summonerName);
$str = strtolower($news);


$result = @file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/' . $new . '?api_key=' . $apiKey);
if(!isset($result[0])) {
    die(); // die('Nothing found in \'result\' file.');
}

$summoner = json_decode($result)->$str;
if(!$summoner) {
    die(); // die('Nothing found in \'result\' content.');
}

$id = $summoner->id;

?>  



<?php   
$claw = @file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/' . $id . '/ranked?season=SEASON2016&api_key=' . $apiKey);
if(!isset($claw[0])) {
    die(); // die('Nothing found in \'claw\' file.');
}

$gaza = json_decode($claw);
if(!$gaza) {
    die(); // die('Nothing found in \'claw\' content.');
}
?>


<?php 
$entriesz = $gaza->champions;
usort($entriesz, function($ac,$bc){
return $bc->stats->totalSessionsPlayed-$ac->stats->totalSessionsPlayed;
});

foreach($entriesz as $statSummaryz) if ($tmp++ < 11){

$getLeagueNamelistside = $statSummaryz->id;
$getsessionsplayedNamelistside = $statSummaryz->stats->totalSessionsPlayed;
$getMiniomskillsNamelistside = $statSummaryz->stats->totalMinionKills;
$getkillsNamelistside = $statSummaryz->stats->totalChampionKills;
$getassistssNamelistside = $statSummaryz->stats->totalAssists;
$getdeathsNamelistside = $statSummaryz->stats->totalDeathsPerSession;
$getlosseslistside = $statSummaryz->stats->totalSessionsLost;
$getwinslistside = $statSummaryz->stats->totalSessionsWon;



$Percentkillrateside = $getkillsNamelistside / $getsessionsplayedNamelistside;
$Percentassistrateside = $getassistssNamelistside / $getsessionsplayedNamelistside;
$Percentdeathrateside = $getdeathsNamelistside / $getsessionsplayedNamelistside;
$KDAside = ($getkillsNamelistside + $getassistssNamelistside) / $getdeathsNamelistside;
$KDAMinniomsSide = $getMiniomskillsNamelistside / $getsessionsplayedNamelistside;
$PercentWinRateSide = 100 / ($getlosseslistside + $getwinslistside) * $getwinslistside;


if ($getLeagueNamelistside >=1){

    $resultz = @file_get_contents('https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion/'.$getLeagueNamelistside.'?api_key=' . $apiKey);
    if(!isset($resultz[0])) {
        die(); // die('Nothing found in league file:' . $getLeagueNamelistside);
    }

$summonerz = json_decode($resultz, true);
if(!summonerz) {
    die(); // die('Nothing found in league content:' . $getLeagueNamelistside);
}

$getLeagueNamelistsidez = $summonerz['name'];
$getLeagueKeyNamelistsidez = $summonerz['key'];
    echo '<p><img src="http://lolchecker.esy.es/LOLGGWP/img/champion/' .$getLeagueKeyNamelistsidez. '.png"></p>'.$getLeagueNamelistsidez. '<p> Kills '.number_format((float)$Percentkillrateside, 1, '.', '').'</p><p> Deaths '.number_format((float)$Percentdeathrateside, 1, '.', '').'</p><p> Assists '.number_format((float)$Percentassistrateside, 1, '.', '').'</p><p> KDA '.number_format((float)$KDAside, 2, '.', '').':1 KDA</p><p> CS '.number_format((float)$KDAMinniomsSide, 1, '.', '').' CS</p><p> Games Played '.$getsessionsplayedNamelistside.'</p><p> Win Rate '.number_format((float)$PercentWinRateSide, 0, '.', '').'%</p>';



}
 elseif($getLeagueNamelistside == 0){
    die();
   }
}
?>

<?php
$apiKey = 'e9044828-20e3-46cc-9eb5-545949299803';
$summonerName = 'raget deathdex';

// =====

$results = @file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/' . rawurlencode($summonerName) . '?api_key=' . $apiKey);
if(!isset($results[0]))
    die();

$summoner = json_decode($results)->strtolower(str_replace(' ', '', $summonerName));
if(!$summoner)
    die();

$results = @file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/' . $summoner->id . '/ranked?season=SEASON2016&api_key=' . $apiKey);
if(!isset($results[0]))
    die();

$gaza = json_decode($results);
if(!$gaza)
    die();

// =====

$entriesz = $gaza->champions;
usort($entriesz, function($ac, $bc){
    return $bc->stats->totalSessionsPlayed-$ac->stats->totalSessionsPlayed;
});

// =====

foreach($entriesz as $statSummaryz) {
    if($tmp++ < 11) {
        $getLeagueNamelistside = $statSummaryz->id;
        $getsessionsplayedNamelistside = $statSummaryz->stats->totalSessionsPlayed;
        $getMiniomskillsNamelistside = $statSummaryz->stats->totalMinionKills;
        $getkillsNamelistside = $statSummaryz->stats->totalChampionKills;
        $getassistssNamelistside = $statSummaryz->stats->totalAssists;
        $getdeathsNamelistside = $statSummaryz->stats->totalDeathsPerSession;
        $getlosseslistside = $statSummaryz->stats->totalSessionsLost;
        $getwinslistside = $statSummaryz->stats->totalSessionsWon;

        $Percentkillrateside = $getkillsNamelistside / $getsessionsplayedNamelistside;
        $Percentassistrateside = $getassistssNamelistside / $getsessionsplayedNamelistside;
        $Percentdeathrateside = $getdeathsNamelistside / $getsessionsplayedNamelistside;
        $KDAside = ($getkillsNamelistside + $getassistssNamelistside) / $getdeathsNamelistside;
        $KDAMinniomsSide = $getMiniomskillsNamelistside / $getsessionsplayedNamelistside;
        $PercentWinRateSide = 100 / ($getlosseslistside + $getwinslistside) * $getwinslistside;

        if($getLeagueNamelistside >= 1) {
            $results = @file_get_contents('https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion/' . $getLeagueNamelistside . '?api_key=' . $apiKey);
            if(!isset($results[0]))
                die();
        }

        $summonerz = json_decode($results, true);
        if(!$summonerz)
            die();

        $getLeagueNamelistsidez = $summonerz['name'];
        $getLeagueKeyNamelistsidez = $summonerz['key'];
        echo 
            '<p><img src="http://lolchecker.esy.es/LOLGGWP/img/champion/', $getLeagueKeyNamelistsidez, '.png"></p>',
            $getLeagueNamelistsidez,
            '<p> Kills ', number_format((float)$Percentkillrateside, 1, '.', ''),
            '</p><p> Deaths ', number_format((float)$Percentdeathrateside, 1, '.', ''),
            '</p><p> Assists ', number_format((float)$Percentassistrateside, 1, '.', ''),
            '</p><p> KDA ', number_format((float)$KDAside, 2, '.', ''),
            ':1 KDA</p><p> CS ', number_format((float)$KDAMinniomsSide, 1, '.', ''),
            ' CS</p><p> Games Played ', $getsessionsplayedNamelistside,
            '</p><p> Win Rate ', number_format((float)$PercentWinRateSide, 0, '.', ''),
            '%</p>', "\n";
    }
    elseif($getLeagueNamelistside == 0)
        die();
}
Brogan
  • 708
  • 5
  • 13
0

You should be able to check the file contents in order to determine it has the required data.

<?php   
$claw = file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/' . $id . '/ranked?season=SEASON2016&api_key=' . $apiKey);
if(false === empty($claw)) {
    $gaza = json_decode($claw);
    if(true === empty($gaza->champion)) {
        return 'Invalid data received';
    }
} else {
    return 'No data found';
}
?>

It also looks like you have a syntax error on your comparison condition which is using an assignment operator which will always evaluate to true. But unsure if that portion of your code is used or not.

elseif($getLeagueNamelistside =0){

Should just be

else {

which will function as if ($getLeagueNamelistside <= 0) return DO_NOTHING;


UPDATE

To prevent the file not found error, and others from being displayed, you can disable the display of error messages. Which should be the case in production code anyways.

ini_set('display_errors', 'off');

Or filter the display of only certain error messages.

ini_set('error_reporting', E_ERROR | E_PARSE);

You can also bypass error reporting of specific commands by prepending @

@file_get_contents('https://example.com/index.php');

Last but not least, and my preferred method, is to use output buffering to prevent undesired content from outputting to the client.

ob_start();
echo file_get_contents('https://example.com/index.php');
$content = ob_get_clean();
echo false === strpos($content, '404') ? $content : 'OOps';
Will B.
  • 17,883
  • 4
  • 67
  • 69
  • Still shows this warning : E_WARNING : type 2 -- file_get_contents(https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/77828400/ranked?season=SEASON2016&api_key=e9044828-20e3-46cc-9eb5-545949299803): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found -- at line 24 – Aaron Bailey Apr 01 '16 at 18:24
  • That makes more sense - I see you updated your question with that error message. Was attempting to handle the parsing of the json content with the 404 response instead of handling `file_get_contents` Updated the answer. – Will B. Apr 01 '16 at 19:33
0

Try this ;)

$news = str_replace(' ', '', $summonerName);
$str  = strtolower($news);

$result   = file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/' . $new . '?api_key=' . $apiKey);
$summoner = json_decode($result)->$str;
$id       = $summoner->id;

$claw = file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/' . $id . '/ranked?season=SEASON2016&api_key=' . $apiKey);
$gaza = json_decode($claw);
if (isset($gaza->champions)) {
  $entriesz = $gaza->champions;
  usort($entriesz, function($ac, $bc) {
    return $bc->stats->totalSessionsPlayed - $ac->stats->totalSessionsPlayed;
  });

  foreach ($entriesz as $statSummaryz) {
    if ($tmp++ < 11) {
      $getLeagueNamelistside         = $statSummaryz->id;
      $getsessionsplayedNamelistside = $statSummaryz->stats->totalSessionsPlayed;
      $getMiniomskillsNamelistside   = $statSummaryz->stats->totalMinionKills;
      $getkillsNamelistside          = $statSummaryz->stats->totalChampionKills;
      $getassistssNamelistside       = $statSummaryz->stats->totalAssists;
      $getdeathsNamelistside         = $statSummaryz->stats->totalDeathsPerSession;
      $getlosseslistside             = $statSummaryz->stats->totalSessionsLost;
      $getwinslistside               = $statSummaryz->stats->totalSessionsWon;

      $Percentkillrateside   = $getkillsNamelistside / $getsessionsplayedNamelistside;
      $Percentassistrateside = $getassistssNamelistside / $getsessionsplayedNamelistside;
      $Percentdeathrateside  = $getdeathsNamelistside / $getsessionsplayedNamelistside;
      $KDAside               = ($getkillsNamelistside + $getassistssNamelistside) / $getdeathsNamelistside;
      $KDAMinniomsSide       = $getMiniomskillsNamelistside / $getsessionsplayedNamelistside;
      $PercentWinRateSide    = 100 / ($getlosseslistside + $getwinslistside) * $getwinslistside;

      if ($getLeagueNamelistside >= 1) {
        $resultz                   = file_get_contents('https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion/' . $getLeagueNamelistside . '?api_key=' . $apiKey);
        $summonerz                 = json_decode($resultz, true);
        $getLeagueNamelistsidez    = $summonerz['name'];
        $getLeagueKeyNamelistsidez = $summonerz['key'];
        echo '<p><img src="http://lolchecker.esy.es/LOLGGWP/img/champion/' . $getLeagueKeyNamelistsidez . '.png"></p>' . $getLeagueNamelistsidez . '<p> Kills ' . number_format((float) $Percentkillrateside, 1, '.', '') . '</p><p> Deaths ' . number_format((float) $Percentdeathrateside, 1, '.', '') . '</p><p> Assists ' . number_format((float) $Percentassistrateside, 1, '.', '') . '</p><p> KDA ' . number_format((float) $KDAside, 2, '.', '') . ':1 KDA</p><p> CS ' . number_format((float) $KDAMinniomsSide, 1, '.', '') . ' CS</p><p> Games Played ' . $getsessionsplayedNamelistside . '</p><p> Win Rate ' . number_format((float) $PercentWinRateSide, 0, '.', '') . '%</p>';
      } elseif ($getLeagueNamelistside == 0) {
        return DO_NOTHING;
      }
    }
  }
}
itzmukeshy7
  • 2,669
  • 1
  • 21
  • 29