Php 如何用数组中的每个变量替换/运行curl?
我已经为自己设置了这个代码Php 如何用数组中的每个变量替换/运行curl?,php,arrays,curl,Php,Arrays,Curl,我已经为自己设置了这个代码 <?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?i
<?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,直到得到echo“Word Found!”
我被$val部分卡住了,一旦我解决了这个问题,我也许可以设置if/else命令
有人能帮我完成这段代码吗?这是一段有效的代码。我将函数重命名为更有意义的名称,并添加了url以检查函数内部。注意,您只需要声明函数一次 函数
checkActiveIp()
现在将返回true
(如果在响应中找到active
),如果没有,则返回false
if(checkActiveIp($ip)){…
将调用函数并检查结果,如果函数返回true
,将使用将已检查的ip推送到数组的末尾$activeIP
最后,数组$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);
为什么要在循环中定义函数get_data
?我需要检查每个$val页面中的单词active。而在循环之外定义函数是不可行的?可以通过调用print_r(get_data($url))来实现这一点;
,无需经常定义函数本身。将函数定义从该循环中移到错误报告(E_ALL);
您甚至不需要将其设置为function@kerbh0lz那么,我应该将函数get_data($url)
移动到$ipaddress
之前吗?它不会错过$url
?