如何通过cURL实现图片上传?
我被告知要使用curl_file_create,但它无效。
当我手动(使用Chrome)上传文件并查看原始结构时,这是来自帖子的数组:
Array
(
[image] => Array
(
[0] => 377529090726537.jpg
)
[thumbnail_digest] => Array
(
[0] => EMPTYDIGEST
)
[digest_present] => Array
(
[0] => 0
)
[image_rotation] => Array
(
[0] => 0
)
)
在我的cURL里面,我试过了:
$cfile = curl_file_create('IMG_33071.jpg','image/jpeg','test_name');
$post_data = array(
'image' => $cfile,
);
但是在运行脚本后,我收到了这个错误:
捕获致命错误:无法转换类CURLFile的对象 在第144行的C:\ Path \到\ my \ server \ curl.php中字符串
图像位于curl.php文件的同一文件夹中。 我的php版本是5.5。
我也试过这个:
$cfile = curl_file_create('http://www.siteexample.com/path/to/my/file.jpg','image/jpeg','test_name');
但没有成功:(
我的结构:
//These are the post data username and password
$login_data = 'email='.$email.'&password='.$password.'&entrar=Entrar';
//Create a curl object
$login = curl_init();
//Set the useragent
$agent = $_SERVER["HTTP_USER_AGENT"];
//$agent = 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0';
curl_setopt($login, CURLOPT_USERAGENT, $agent);
curl_setopt($login, CURLOPT_SSL_VERIFYPEER, false);
//Set the URL
curl_setopt($login, CURLOPT_URL, $login_url );
//This is a POST query
curl_setopt($login, CURLOPT_POST, 1 );
//Set the post data
curl_setopt($login, CURLOPT_POSTFIELDS, $login_data);
//We want the content after the query
curl_setopt($login, CURLOPT_RETURNTRANSFER, 1);
//Follow Location redirects
curl_setopt($login, CURLOPT_FOLLOWLOCATION, 1);
/*
Set the cookie storing files
Cookie files are necessary since we are logging and session data needs to be saved
*/
curl_setopt($login, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($login, CURLOPT_COOKIEFILE, 'cookie.txt');
//Execute the action to login
$LoginResult = curl_exec($login);
echo $LoginResult;
//create array of data to be posted
$post_data = array(
'name' => 'Name',
'email' => $email,
'email_confirm' => $email,
'phone' => '9999999999',
'passwd' => $password,
'passwd_ver' => $password,
'create' => '',
);
//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
$post_items[] = $key . '=' . $value;
}
//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);
var_dump($post_string);
curl_setopt($login, CURLOPT_URL, 'http://urltocurl.com/verify');
curl_setopt($login, CURLOPT_POST, false);
curl_setopt($login, CURLOPT_POSTFIELDS, $post_string);
curl_setopt($login, CURLOPT_TIMEOUT, 0);
$answer = curl_exec($login);
echo $answer;
if (curl_error($login)) {
echo curl_error($login);
}
//close the connection
curl_close($login);
现在看看开始时的数组。
Array
(
[image] => Array
(
[0] => 377529090726537.jpg
)
这是另一个内部的数组。怎么实现呢?也许curl_file_create正在运行,但是它将图像发送到数组的错误位置。
答案 0 :(得分:2)
看看我的例子它应该适合你:
$ch = curl_init();
$data = array('name' => 'Foo', 'file' => '@/path/to/image.jpeg');
curl_setopt($ch, CURLOPT_URL, 'http://example.com/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);