使用PHP提交文件到网站


Submitting file to website using PHP?

好的,所以我想提交以下网站(http://newocr.com/)的图像,但我不知道如何做到这一点。我在谷歌上找不到任何东西。

下面是我使用的代码

$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变量指定文件在硬盘上的存储位置文件不能从我的硬盘上传到网站上。但是当我使用存储在我的web主机上的文件的url而不是pc上的文件路径做同样的事情时,它可以工作。

谁能告诉我怎么做?我如何上传这个文件直接从我的硬盘驱动器,而不是使用URL?

谢谢

注意:整个foreach循环是没有意义的。curl会很乐意接受POSTFIELDS opt的数组,并自动为您完成所有的url构建/编码。

要让curl做一个上传,你必须告诉它你正在传递一个文件路径:

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

注意数组中的@ -这是curl的提示,它是一个文件路径,您希望它被上传。还要注意完全没有循环/手动编码/url构建。

还需要注意的是,在最近的curl/php实现中,这个选项已经升级为一个专用的CURLFile选项。