简体   繁体   中英

How to substitute/run curl with every variable in an array?

I have setup this code for myself.

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


$ipaddress = array("8.8.8.8", "1.1.1.1", "8.8.4.4");
foreach ($ipaddress as $key => $val) {
$url="https://example.com/test/check?ip=$val"; //
print_r(get_data($url)); //dumps the content, you can manipulate as you wish to
/* gets the data from a URL */

function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);

$word = 'active';
// Test if string contains the word 
if(strpos($data, $word) !== false){
    echo "Word Found!";
} else{
    echo "Word Not Found!";
}
}
}
?>

However for some reason (read my incapability), the value for $val is only 8.8.8.8, i want to substitute each IP in the array at the end of $url till i get echo "Word Found.".

I am stuck with the part $val, once i solve that, i can perhaps setup if/else command?

Can anyone help me with completing this code?

Here's a working code. I renamed the function to something more meaningful and added the url to check inside the function. Note, you only need to declare the function once.

The function checkActiveIp() will now return true (if active was found in the response) or false if it wasn't. if ( checkActiveIp($ip) ) {... will call the function and check for the result and if the function returns true , will push the checked IP to the end of the array $activeIps using array_push() .

In the end, the array $activeIps will contain all IPs whose response contains the word active .

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

function checkActiveIp($ip) {
    $url = "https://example.com/test/check?ip=$ip";
    $timeout = 5;

    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
    $data = curl_exec($ch);
    curl_close($ch);

    $word = 'active';
    // Test if string contains the word 
    if(strpos($data, $word) !== false){
        return true;
    } else {
        return false;
    }
}


$activeIps = array();
$ips = array("8.8.8.8", "1.1.1.1", "8.8.4.4");
foreach ($ips as $ip) {
    if ( checkActiveIp($ip) ) {
        array_push($activeIps, $ip);
    }
}

print_r($activeIps);

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