使用PHP将文件提交到网站?

时间:2014-06-19 01:58:17

标签: php forms file-upload

好的,所以我想在以下网站(http://newocr.com/)上提交图片,但我不知道该怎么做。我在Google上找不到任何东西。

以下是我正在使用的代码

$url = "http://newocr.com/";
$urlref = "http://newocr.com/";
$ch = curl_init();

$data_array["userfile"] =  $imgpath;
$data_array["url"]  =  '';
$data_array["1"] = 'eng';
$data_array["preview"] ='1';

  if(is_array($data_array))
    {
    # Convert data array into a query string (ie animal=dog&sport=baseball)
    foreach ($data_array as $key => $value) 
        {
        if(strlen(trim($value))>0)
            $temp_string[] = $key . "=" . urlencode($value);
        else
            $temp_string[] = $key;
        }
    $query_string = join('&', $temp_string);
    }

    if(isset($query_string))
        curl_setopt ($ch, CURLOPT_POSTFIELDS, $query_string);
        curl_setopt ($ch, CURLOPT_POST, TRUE); 
        curl_setopt ($ch, CURLOPT_HTTPGET, FALSE); 

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, $urlref);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$return = curl_exec($ch);

echo $return;

$ imgpath变量指定文件存储在我的硬盘上的位置 该文件不会从我的硬盘上传到网站。但是,当我使用存储在我的网络主机上的文件的网址而不是网络上的文件路径做同样的事情时,它可以工作。

所以有人可以告诉我该怎么做。如何直接从硬盘驱动器上传此文件而不是使用URL?

由于

1 个答案:

答案 0 :(得分:0)

注意:你的整个foreach循环都没有意义。 curl会愉快地为POSTFIELDS选择一个数组,并自动为你做所有的urlbuilding /编码。

要让卷曲进行上传,您必须告诉它您正在传递文件路径:

$opts = array(
  'foo' => 'bar',
  'file' => '@/path/to/file/on/server'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $opts);

请注意数组中的@ - 提示它是一个文件路径,并且您希望将其上传。另请注意,完全没有循环/手动编码/ url构建。

另请注意,在最近的curl / php实现中,这已经升级为专用的CURLFile选项。