[英]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.