Answer the question
In order to leave comments, you need to log in
How to upload photos via VK API correctly?
Hello!
I have been struggling with the VK API for the second day now and I want to make it possible to upload images to the VK servers, and then attach this image to the post. I know how to attach an image, but I had problems uploading an image. Everything is written in the documentation in such a way that it is difficult for a beginner like me to understand. Below I will give a small piece of code with comments, which is responsible for loading the image:
// получаю ссылку, куда загружать изображение
$upl_url = vk_api("photos.getWallUploadServer", "group_id=".$community);
// отправляю изображение по ссылке
if (isset($upl_url["response"]["upload_url"])) {
$photo['photo'] = '@'.'/home/a7223299/public_html/images_b/'.$picture;
$curl = curl_init($upl_url["response"]["upload_url"]);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $photo);
// получаю ответ
$s = curl_exec($curl);
curl_close($curl);
}
else {
echo 'Server is not responding.';
}
// проверка #1
print_r($s);
echo '<br>';
echo '<br>';
// преобразую ответ в массив
$data_ph = json_decode($s, true);
// проверка #2
print_r($data_ph);
echo '<br>';
echo '<br>';
// сохраняю фотографию
$photo_id = vk_api("photos.saveWallPhoto", "&server=".$data_ph['server']."&hash=".$data_ph['hash']."photo=".$data_ph['photo']);
// проверка #3
print_r($photo_id);
function vk_api($method, $params) {
$json = file_get_contents("https://api.vk.com/method/".$method."?".$params."&access_token=".$access_tocken."&v=".$version);
return json_decode($json, true);
}
{"server":623229,"photo":"[{\"photo\":\"73f87c2dc5:z\",\"sizes\":,\"kid\":\"8bee91a57a9a42f79f87a04a46708486\"}]","hash":"929481842a51b72f8fdb44a229e829b6"}
Array ( [server] => 623229 [photo] => [{"photo":"73f87c2dc5:z","sizes":,"kid":"8bee91a57a9a42f79f87a04a46708486"}] [hash] => 929481842a51b72f8fdb44a229e829b6 )
Array ( [error] => Array ( [error_code] => 100 [error_msg] => One of the parameters specified was missing or invalid: photo is undefined [request_params] => Array ( [0] => Array ( [key] => oauth [value] => 1 ) [1] => Array ( [key] => method [value] => photos.saveWallPhoto ) [2] => Array ( [key] => [value] => ) [3] => Array ( [key] => server [value] => 623229 ) [4] => Array ( [key] => hash [value] => 929481842a51b72f8fdb44a229e829b6photo=[{"photo":"73f87c2dc5:z","sizes":,"kid":"8bee91a57a9a42f79f87a04a46708486"}] ) [5] => Array ( [key] => v [value] => 5.29 ) ) ) )
Answer the question
In order to leave comments, you need to log in
On the error page, [error_code] => 100
means that one of the required parameters was not passed or is incorrect.
Check the list of required parameters and their format on the method page
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question