通过php保存表单中URL的图像

时间:2011-03-28 11:24:58

标签: php image forms url save

我有一个php脚本,它从外部URL抓取图像,读取它并将其保存到我服务器上的目录中。该脚本位于php文件中,包含:

<?php 
$image_url = "http://example.com/image.jpg"; 
$ch = curl_init(); 
$timeout = 0; 
curl_setopt ($ch, CURLOPT_URL, $image_url); 
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 

// Getting binary data 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); 

$image = curl_exec($ch); 
curl_close($ch); 

$f = fopen('/home1/path/public_html/path/saved/image.jpg', 'w');
fwrite($f, $image);
fclose($f);
?>

那里的一切都很好......

我想要做的是让脚本为多个URL执行此操作。 URL将以textarea格式写入,由逗号(或其他)分隔。

然后,提交按钮会告诉脚本使用表单中的所有URL进行操作并使用任何名称保存它们,这并不重要(随机会很好)。

我还是新手,我正在学习PHP。

提前感谢您的帮助!

修改

我的代码现在看起来像这样:

<?php 
error_reporting(E_ALL);
$image_urls = explode('\n', $_POST['urls']); 



foreach ($image_urls as $image_url) {
$ch = curl_init(); 
$timeout = 0; 
curl_setopt ($ch, CURLOPT_URL, $image_url); 
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); 

  $image = curl_exec($ch); 
  curl_close($ch); 

  $f = fopen('/home1/path/public_html/path/saved/'.rand().time().".jpg", 'w');
  fwrite($f, $image);
  fclose($f);

}
?>

它仅适用于第一个,并且不会返回任何错误......任何想法?

感谢您的大力帮助!

1 个答案:

答案 0 :(得分:1)

您需要从文本区域中提取网址,然后循环显示:

<?php 
$image_urls = explode('\n', $_POST['urls']); # Will create a list of urls, if each line contains one url.

#Basic settings and initializers need to be ran only once. 
$sequencer = 1;
$timeout = 0;

foreach ($image_urls as $image_url) {
  $ch = curl_init(); 

  curl_setopt ($ch, CURLOPT_URL, $image_url); 
  curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 

  // Getting binary data 
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
  curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); 

  $image = curl_exec($ch); 
  curl_close($ch); 

  $f = fopen("/home1/path/public_html/path/saved/image_$sequencer.jpg", 'w');
  fwrite($f, $image);
  fclose($f);
  $sequencer++;
}
?>

显然,您应该清理,验证并重复检查输入的信息:不仅要避免使用Goatses,还要避免破坏应用程序的条目(例如白线)。

相关问题