首页 > 解决方案 > 获取域年龄 (file_get_contents) 的 PHP 脚本问题

问题描述

嗨,我在 php 中有一个我不明白的问题,

我制作了一个php 脚本,从带有 file_get_contents的 waybackmachine中获取特定域的域年龄

域都在一个称为域的数组中,来自用户的 texfield。

该脚本工作正常,但仅适用于数组中的第一个域,但对于第二个域,我只从循环中得到奇怪的值或什么都没有

但我不知道为什么,我看不出有什么错误。并且数组中的所有域都是正确的。

谁能帮助我我做错了什么?

//Array with Domains
$domain = explode("\n",trim($_POST['url']));

// Print the Array for debugging
print_r($domain);



// count domains for the loop
$count = count($domain);
echo $count;

for ($i = 0; $i < $count; $i++) {

$content=file_get_contents('http://web.archive.org/cdx/search/cdx?url='.$domain[$i].'',FALSE, NULL, 1, 600);

//use the data from file_get_contents to calculate the age

preg_match('/\d+/', $content, $date); 
$startyear= substr($date[0], 0, -10);
$startmonth=  substr($date[0], 4, -8);
$actualyear= date("Y");


// calculate the year & month
$years= $actualyear- $startyear;
$month= 12-$startmonth;

//echo the Age

echo " <div style='font-size:20px;text-align:center;width:100%;height:5%;color:#25bb7f;
    font-weight: bold;'> $domain[$i]: $years Jahre und $month Monate </div>"; 

}

标签: phpfile-get-contents

解决方案


我认为问题在于 URL 的解码和编码。您传递的域'http://web.archive.org/cdx/search/cdx?url='必须完全编码。请参阅下面如何完成此操作...

//Array with Domains
$domain = explode("\n",trim($_POST['url']));


# url encode all the urls/domains.
$domain = array_map(function($domain){ return urlencode($domain); }, $domain);

// Print the Array for debugging
print_r($domain);



// count domains for the loop
$count = count($domain);
echo $count;

for ($i = 0; $i < $count; $i++) {

$content=file_get_contents('http://web.archive.org/cdx/search/cdx?url='.$domain[$i].'',FALSE, NULL, 1, 600);

//use the data from file_get_contents to calculate the age

preg_match('/\d+/', $content, $date); 
$startyear= substr($date[0], 0, -10);
$startmonth=  substr($date[0], 4, -8);
$actualyear= date("Y");


// calculate the year & month
$years= $actualyear- $startyear;
$month= 12-$startmonth;

//echo the Age

$domainNonEncoded = htmlspecialchars(urldecode($domain[$i])); # get the decoded url

echo " <div style='font-size:20px;text-align:center;width:100%;height:5%;color:#25bb7f;
    font-weight: bold;'> {$domainNonEncoded}: $years Jahre und $month Monate </div>"; 

}

推荐阅读