[英]How to substitute/run curl with every variable in an array?
我已经为自己设置了这个代码。
<?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!";
}
}
}
?>
但是由于某种原因(请阅读我的无能),$val 的值仅为 8.8.8.8,我想在 $url 末尾替换数组中的每个 IP 直到我得到回显“Word Found。”。
我被 $val 部分卡住了,一旦我解决了这个问题,我也许可以设置 if/else 命令?
谁能帮我完成这段代码?
这是一个工作代码。 我将 function 重命名为更有意义的名称,并添加了 url 以检查 function 内部。 注意,您只需声明一次 function。
function checkActiveIp()
现在将返回true
(如果在响应中发现active
),否则返回false
。 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() .
最后,数组$activeIps
将包含其响应包含单词active
的所有 IP。
<?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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.