0

I need to use curl_multi to get http codes from urls but my code is not working. I am able to scan urls but curl_getinfo always returns 0. i tried without multi api but then checking takes forever

        $i = 0;
        $ch = curl_multi_init();

        while($i < count($cat_and_id)){ 

            $link    = explode("_", $cat_and_id[$i]);
            $cat     = $link[0];
            $post_id = $link[1];
            $link    = "https://website.com/item/?cat=".$cat."&post_id=".$post_id;
            
            
            curl_setopt($ch, CURLOPT_URL, $link);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
            curl_setopt($ch, CURLOPT_NOBODY, true);
            curl_multi_exec($ch);
            $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            

            if($code !== 301) {
               echo $code;
            }

            $i++;
         }

         curl_multi_close($ch);
stack
  • 1
  • 4

1 Answers1

1

Use the following pattern for your code:

<?php 
    $requests = array('http://www.website.com', 'http://www.google.com');  
    $main    = curl_multi_init();  
    $results = array();  
    $errors  = array();  
    $info = array();  
    $count = count($requests);  
    for($i = 0; $i < $count; $i++)   
    {    
        $handles[$i] = curl_init($requests[$i]);    
        //var_dump($requests[$i]);    
        curl_setopt($handles[$i], CURLOPT_URL, $requests[$i]);    
        curl_setopt($handles[$i], CURLOPT_RETURNTRANSFER, 1);    
        curl_multi_add_handle($main, $handles[$i]);  
    }  
    $running = 0;   
    do {    
        curl_multi_exec($main, $running);  
    }   
    while($running > 0);   
    for($i = 0; $i < $count; $i++)  
    {  
        $results[] = curl_multi_getcontent($handles[$i]);    
        $errors[]  = curl_error($handles[$i]);    
        $info[]    = curl_getinfo($handles[$i]);    
        curl_multi_remove_handle($main, $handles[$i]);  
    }  
    curl_multi_close($main);  
    //print_r($results);  
    //var_dump($errors);  
    echo $requests[0]. " ==><br>";
    print_r($info[0]);
    echo "<br><br>";
    echo $requests[1]. " ==><br>";
    print_r($info[1]);
    
    
    //print_r();
      

Majid Hajibaba
  • 3,105
  • 6
  • 23
  • 55