Curl api on for loop doesn't work

From my online list:

include("channels_list.php");

// play call API 

for($i=1; $i <= $q; $i++){
$forse = 'channels' . $i;
if($forse != NULL){
$callAPI = implode('&user_login=', ${$forse});
$url="https://api.twitch.tv/helix/streams?user_login=" . $callAPI;
$ch = curl_init();
  
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  
    'Accept: application/vnd.twitchtv.v5+json',
    'Client-ID: c533u8ntdp29h42xxzwfe0pf5v66dm'
  
));

$forse2 = "result" .$i;
${$forse2} = curl_exec($ch);
curl_close($ch);

// play print API
$str = json_decode(${$forse2}, true);
} else {
    echo 'nothing';
}
// end call API
}

From channels_list.php

$channels1 = array();
$channels2 = array();
$channels3 = array();
$channels4 = array();
$channels5 = array();

  $canale = "SELECT * FROM `ttp_tsp` ORDER BY id ASC LIMIT 0, 100";
  $result = mysqli_query($connString, $canale)or die(mysqli_error());
  if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
  $channels1[] = $row['canale'];
}
  }

  $canale = "SELECT * FROM `ttp_tsp` ORDER BY id ASC LIMIT 100, 100";
  $result = mysqli_query($connString, $canale)or die(mysqli_error());
  if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
 $channels2[] = $row['canale'];
}
  }

$canale = "SELECT * FROM `ttp_tsp` ORDER BY id ASC LIMIT 200, 100";
$result = mysqli_query($connString, $canale)or die(mysqli_error());
if (mysqli_num_rows($result) > 0){
    while($row = mysqli_fetch_assoc($result)){
 $channels3[] = $row['canale'];
}
  }

$canale = "SELECT * FROM `ttp_tsp` ORDER BY id ASC LIMIT 300, 100";
$result = mysqli_query($connString, $canale)or die(mysqli_error());
if (mysqli_num_rows($result) > 0){
    while($row = mysqli_fetch_assoc($result)){
 $channels4[] = $row['canale'];
}
  }

$canale = "SELECT * FROM `ttp_tsp` ORDER BY id ASC LIMIT 400, 100";
$result = mysqli_query($connString, $canale)or die(mysqli_error());
if (mysqli_num_rows($result) > 0){
    while($row = mysqli_fetch_assoc($result)){
 $channels5[] = $row['canale'];
}
  }

if($channels5 != NULL){
$q = 5;
}elseif($channels4 != NULL){
$q = 4;
}elseif($channels3 != NULL){
$q = 3;
}elseif($channels2 != NULL){
$q = 2;
}elseif($channels1 != NULL){
$q = 1;
}

The problem is the curl, it should repeat five times but it call only last $channels if $channels is not null.
What should i do for repeat five time curl calling five different channels array?

Your PHP is bad for want of better wording.

Try something more akin to

include("channels_list.php");

// play call API 

foreach ($channels as $chans) {
    $callAPI = implode('&user_login=', $chans);
    $url="https://api.twitch.tv/helix/streams?user_login=" . $callAPI;
    $ch = curl_init();
      
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Client-ID: c533u8ntdp29h42xxzwfe0pf5v66dm'
  ));

  $result = curl_exec($ch);
  $i = curl_getinfo($ch);
  curl_close($ch);

  $str = json_decode($result, true);
  if ($i['http_code'] == 200) {
    // play print API
    // do stuff with $str has chnanels
  } else {
    // non 200 do somethign with the error
    // do stuff with $str has error message
  }
}
// end call API

$channels = array(
  array(),
  array(),
  array(),
  array(),
  array()
);

  $canale = "SELECT * FROM `ttp_tsp` ORDER BY id ASC LIMIT 0, 100";
  $result = mysqli_query($connString, $canale)or die(mysqli_error());
  if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
  $channels[0][] = $row['canale'];
}
  }

  $canale = "SELECT * FROM `ttp_tsp` ORDER BY id ASC LIMIT 100, 100";
  $result = mysqli_query($connString, $canale)or die(mysqli_error());
  if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
 $channels[1][] = $row['canale'];
}
  }

$canale = "SELECT * FROM `ttp_tsp` ORDER BY id ASC LIMIT 200, 100";
$result = mysqli_query($connString, $canale)or die(mysqli_error());
if (mysqli_num_rows($result) > 0){
    while($row = mysqli_fetch_assoc($result)){
 $channels[2][] = $row['canale'];
}
  }

$canale = "SELECT * FROM `ttp_tsp` ORDER BY id ASC LIMIT 300, 100";
$result = mysqli_query($connString, $canale)or die(mysqli_error());
if (mysqli_num_rows($result) > 0){
    while($row = mysqli_fetch_assoc($result)){
 $channels[3][] = $row['canale'];
}
  }

$canale = "SELECT * FROM `ttp_tsp` ORDER BY id ASC LIMIT 400, 100";
$result = mysqli_query($connString, $canale)or die(mysqli_error());
if (mysqli_num_rows($result) > 0){
    while($row = mysqli_fetch_assoc($result)){
 $channels[4][] = $row['canale'];
}
  }

Also removed the accept header thats not needed with Helix.and added a curl 200 check.

Thanks for your reply.
channels_list.php works great!
But index for channels make a http error 500

Inspect the body of the response for additional information.

Check the URL that is being constructed is the correct/expected/valid URL

I modified your code off the top of my head and didn’t test it myself, since I don’t have your DB structure.

Ok, now work perfectly, but now print all five array if any are null too, this generate error on undefined index for str[‘data’].
If i add channel name on all array curl print only last array and not all five.

I can tell that English is not your first language. I don’t quite understand what you have written

yup sorry ahahah i’m italian.
if i have $channels[1] without channels it generate error “undefined index” because curl print only latest $channels ($channels[4] in this case).

Show your code please. But this is erring towards general PHP problems rather than a TwitchAPI problem

channels_list.php

<?php

  include_once(“connection.php”);

  $db = new dbObj();

  $connString =  $db->getConnstring();

  

    $channels = array(

      array(),

      array(),

      array(),

      array(),

      array()

    );

  $canale = “SELECT * FROM ttp_tsp ORDER BY id ASC LIMIT 0, 100”;

  $result = mysqli_query($connString, $canale)or die(mysqli_error());

  if (mysqli_num_rows($result) > 0){

    while($row = mysqli_fetch_assoc($result)){

      $channels[0] = $row[‘canale’];

    }

  }

  $canale = “SELECT * FROM ttp_tsp ORDER BY id ASC LIMIT 100, 100”;

  $result = mysqli_query($connString, $canale)or die(mysqli_error());

  if (mysqli_num_rows($result) > 0){

    while($row = mysqli_fetch_assoc($result)){

     $channels[1] = $row[‘canale’];

    }

  }

    $canale = “SELECT * FROM ttp_tsp ORDER BY id ASC LIMIT 200, 100”;

    $result = mysqli_query($connString, $canale)or die(mysqli_error());

    if (mysqli_num_rows($result) > 0){

        while($row = mysqli_fetch_assoc($result)){

     $channels[2] = $row[‘canale’];

    }

  }

    $canale = “SELECT * FROM ttp_tsp ORDER BY id ASC LIMIT 300, 100”;

    $result = mysqli_query($connString, $canale)or die(mysqli_error());

    if (mysqli_num_rows($result) > 0){

        while($row = mysqli_fetch_assoc($result)){

     $channels[3] = $row[‘canale’];

    }

  }

    $canale = “SELECT * FROM ttp_tsp ORDER BY id ASC LIMIT 400, 100”;

    $result = mysqli_query($connString, $canale)or die(mysqli_error());

    if (mysqli_num_rows($result) > 0){

        while($row = mysqli_fetch_assoc($result)){

     $channels[4] = $row[‘canale’];

    }

  }

?>

connection.php

<?php

Class dbObj{

    / Database connection start /

    var $servername = “localhost”;

    var $username = “username”;

    var $password = “password”;

    var $dbname = “dbname”;

    var $conn;

    function getConnstring() {

        $con = mysqli_connect($this->servername, $this->username, $this->password, $this->dbname) or die("Connection failed: " . mysqli_connect_error());

        / check connection /

        if (mysqli_connect_errno()) {

            printf(“Connection failed: %s\n”, mysqli_connect_error());

            exit();

        } else {

            $this->conn = $con;

        }

        return $this->conn;

    }

}

?>

index.php

<?php ini_set(‘display_errors’, ‘On’);

error_reporting(E_ALL); ?>

<html>

<head>

<script type=“text/javascript” src=“./js/jquery-1.10.1.min.js”></script>

<script type=“text/javascript” src=“./js/function.js”></script>

<script type=“text/javascript” src=“https://code.jquery.com/jquery-1.12.4.min.js”></script>

<script data-ad-client=“ca-pub-1504328409663488” async src=“https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js”></script>

<link rel=“stylesheet” href=“./css/font-awesome/css/font-awesome.min.css”>

<link rel=“stylesheet” href=“./css/style.css”>

</head>

<body>

<?php

include(“lista_canali_prova.php”);

// inizio a chiamare le API 

foreach($channels as $chans){

    $callAPI = implode(‘&user_login=’, $chans);

    $url=“https://api.twitch.tv/helix/streams?user_login=” . $callAPI;

    $ch = curl_init();

  

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

    curl_setopt($ch, CURLOPT_URL,$url);

    curl_setopt($ch, CURLOPT_HTTPHEADER, array(

        ‘Client-ID: c533u8ntdp29h42xxzwfe0pf5v66dm’

  

    ));

    

    $result = curl_exec($ch);

    $i = curl_getinfo($ch);

    curl_close($ch);

    // preparo le stamp per le API

    $str = json_decode($result, true);

    if ($i[‘http_code’] == 200) {

        // play print API

        // do stuff with $str has chnanels

    } else {

        // non 200 do somethign with the error

        // do stuff with $str has error message

    }

    // fine chiamata API

 // Print test, lo uso solo per testare degli script

  print_r($url);

   echo $str[‘data’];

}

?>

<div class=“center”>

    <div><center><img src=“./img/TPS-logo.webp” alt=“Logo TSP” height=“150” width=“150” style=“padding: 13px;”></center></div>

<?php  if(is_array($str[‘data’])){ ?>

    <div class=“twitch-online” align=“center”>

    </div>

<?php 

                                        $TopRaid = “SELECT canale FROM ttp_tsp WHERE raid=‘Si’”;

                                        $risraid = mysqli_query($connString, $TopRaid)or die(mysqli_error()); 

                                        while($row = mysqli_fetch_array($risraid)){

                                            $canaleraid = $row[‘canale’];

                                        }

?>

        <div class=“divTable”>

            <div class=“divTableBody”>

                <div class=“divTableRow”>

                    <div class=“divTableCell cella1” style=“background-color:red;”><h2><b>RAID IN EVIDENZA    &emsp;</b>  <p hidden id=“TopHOST”>/host <?php echo $canaleraid; ?></p><button onclick=“copyToClipboard(‘TopHOST’)” class=“button button_primary”>Fai da HOST</button>&emsp;<p hidden id=“TopRAID”>/raid <?php echo $canaleraid; ?></p><button onclick=“copyToClipboard(‘TopRAID’)” class=“button button_primary”>Fai il RAID</button></h2></div>

                </div>

                <div class=“divTableRow”>

                    <div class=“divTableCell” style=“width:100%;”>

                        <div id=“twitch-embed”></div>

                            <script src=“https://embed.twitch.tv/embed/v1.js”></script>

                                <script type=“text/javascript”>

                                    var embed = new Twitch.Embed(“twitch-embed”, {

                                        width: 500,

                                        height: 400,

                                        channel: “<?php echo $canaleraid; ?>”,

                                        layout: “video”,

                                        autoplay: false

                                    });

                                      

                                    embed.addEventListener(Twitch.Embed.VIDEO_READY, () => {

                                        var player = embed.getPlayer();

                                        player.play();

                                    });

                                </script> 

                    </div>

                </div>

            </div>

        </div>

    <br><br>

    <div id=“update”>

    <div class=“twitch-online” align=“center”>     

    <h2>CHANNELS LIVE NOW: <?php  $online = count($str[‘data’]); echo $online; ?><br><br></h2> 

    </div>

        <div class=“divTable”>

            <div class=“divTableBody”>

                <div class=“divTableRow”>

                    <div class=“divTableCell cella1”><h2><b>CHANNEL NAME</b><h2></div>

                    <div class=“divTableCell cella2”><h2><b><i class=“fa fa-users” aria-hidden=“true”></i></b><h2></div>

                    <div class=“divTableCell cella3”><h2><b>ACTIONS</b><h2></div>

                </div>

<?php

foreach($str[‘data’] as $mydata){

if($mydata != null) {

  $name      = $mydata[‘user_name’];

  $views     = $mydata[‘viewer_count’];

  ?>

                <div class=“divTableRow table-row”>

                    <div class=“divTableCell”><?php echo “<h3>” . $name .“</h3>”; ?></div>

                    <div class=“divTableCell”><?php echo “” . $views .“”; ?></div>

                    <div class=“divTableCell”><?php echo “<a href=‘https://twitch.tv/“&#160;&#160;.&#160;$name&#160;.&#160;”‘&#160;target=’_blank’&#160;&gt;&lt;button&#160;class=‘button&#160;button_primary’&gt;WATCH&lt;/button&gt;&lt;/a&gt;“;&#160;?&gt;&amp;nbsp;&amp;nbsp;&lt;p&#160;hidden&#160;id=”&lt;?php&#160;echo&#160;$name;&#160;?&gt;"&gt;/raid&#160;&lt;?php&#160;echo&#160;$name;&#160;?&gt;&lt;/p&gt;&lt;button&#160;onclick="copyToClipboard('&lt;?php&#160;echo&#160;$name;&#160;?&gt;’)” class=“button button_primary”>RAID</button></div>

                </div>

<?php

}else{

  echo “<p>test</p>”;

  } } } 

?>

            </div>

        </div>

    </div>

<?php

if($str[‘data’] == null or $str[‘data’] == “0”){

?>

<div id=“twitch-embed” class=“twitch-embed”>

<?php

echo    “<p><h2>No one in live.</h2></p>”;

}

?>

</div>

</body>

</html>

This is the error:

https://api.twitch.tv/helix/streams?user_login=
Notice : Undefined index: data in /var/www/prova_curl.php on line 53

Try this instead

<?php ini_set(‘display_errors’, ‘On’);

error_reporting(E_ALL); ?>

<html>

<head>

<script type=“text/javascript” src="./js/jquery-1.10.1.min.js"></script>

<script type=“text/javascript” src="./js/function.js"></script>

<script type=“text/javascript” src=“https://code.jquery.com/jquery-1.12.4.min.js”></script>

<script data-ad-client=“ca-pub-1504328409663488” async src=“https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js”></script>

<link rel=“stylesheet” href="./css/font-awesome/css/font-awesome.min.css">

<link rel=“stylesheet” href="./css/style.css">

</head>

<body>

<?php

include(“lista_canali_prova.php”);

// inizio a chiamare le API 

$all_channels = [];

foreach($channels as $chans){
    if (count($chans) > 0) {
        $callAPI = implode(’&user_login=’, $chans);

        $url=“https://api.twitch.tv/helix/streams?user_login=” . $callAPI;

        $ch = curl_init();

      

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

        curl_setopt($ch, CURLOPT_URL,$url);

        curl_setopt($ch, CURLOPT_HTTPHEADER, array(

            ‘Client-ID: c533u8ntdp29h42xxzwfe0pf5v66dm’

      

        ));

        

        $result = curl_exec($ch);

        $i = curl_getinfo($ch);

        curl_close($ch);

        // preparo le stamp per le API

        $str = json_decode($result, true);

        if ($i[‘http_code’] == 200) {

            // play print API
            foreach ($str['data'] as $live_chan) {
                $all_channels[] = $live_chan;
            }
            // do stuff with $str has chnanels

        } else {

            // non 200 do somethign with the error
                        // handle the error HERE
            // do stuff with $str has error message

        }

    // fine chiamata API
    }
}

// SNIP
// AND then iterate all_channels instead for your html
  • Check if channels has any channels to go load,
  • Do your curl loops merge all the response data into one array
  • then iterate that new array in the HTML display
1 Like

Okay i’ve applied your corrections.
Continues undaunted not to work the loop :frowning_face:

Only last $channels show

Thats what this bit does here. Which I didn’t change/fix

This block of code uses the data from the last $str that was generate. You havn’t added a iterator for the $all_channels that we added

1 Like

OH GOD THAT WORK! Thanks :heart_eyes:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.