0 - 确保您已阅读PHP manual以查看PHP所具有的所有令人惊叹的内置函数。
1 - 建立对图像的本地路径,你可以使用preg_replace
消毒的URL
2 - 检查图像尚未使用file_exists
下载,如果是这样,加载它;其他下载
3 - 使用file_get_contents
检索图像(cURL
会白白较重)
4 - 使用file_put_contents
foreach($html->find('.featured img') as $image)
{
$imageSrc = $image->src;
$imageUri = $this->rel2abs($imageSrc, $sourceURI);
$imageLocalPath = 'getImages/'.preg_replace('/[^a-z0-9-.]/i', '-', $imageUri);
if (!file_exists($imageLocalPath))
{
$imageData = file_get_contents($imageUri, false, $streamContext);
file_put_contents($imageLocalPath, $imageData);
}
else
$imageData = file_get_contents($imageLocalPath);
}
说明它保存到本地文件:
- 您需要
rel2abs
来解析相对URI或任何适当的pecl扩展名。
- getImages/会把所有的图像在一个子文件夹:您需要手动创建子文件夹,或检查它是否存在于PHP代码,如果需要
- $的imageData包含图像的原始数据创建它,你可以使用
imagecreatefromstring
加载相应的Gd图像。
- 小心:你正在从远方的网页下载东西,所以你必须信任它。人们可以在html页面中添加一个像
<div class="featured"><img src="http://evil.com/your-heart-will-bleed.php"/></div>
这样的标签,并且会下载邪恶的php文件。最糟糕的是,它可能会通过访问您的网站http://mywebsite.com/getImages/your-heart-will-bleed.php
执行。
请将目前为止放在一起的代码贴出来 - Stack Overflow用于解决特定的编程问题;它不是一个编码服务。你有没有搜索过类似的问题? – 2014-09-27 12:07:12