G
G
green1762016-02-24 08:03:34
PHP
green176, 2016-02-24 08:03:34

How to upload photos to a VKontakte group album?

Actually, it’s impossible to upload a photo to the album of the VK group, it’s possible to upload it to your wall, but there’s no way to upload it to the album or to the album of the group

class Model_Vk {

    private $access_token;
    private $url = "https://api.vk.com/method/";

    /**
     * Конструктор
     */
    public function __construct($access_token) {

        $this->access_token = $access_token;
    }

    /**
     * Делает запрос к Api VK
     * @param $method
     * @param $params
     */
    public function method($method, $params = null) {

        $p = "";
        if( $params && is_array($params) ) {
            foreach($params as $key => $param) {
                $p .= ($p == "" ? "" : "&") . $key . "=" . urlencode($param);
            }
        }
        $response = file_get_contents($this->url . $method . "?" . ($p ? $p . "&" : "") . "access_token=" . $this->access_token);

        if( $response ) {
            return json_decode($response);
        }
        return false;
    }

  public function uploadImage($file, $group_id = null) {

    $params = array();
    if( $group_id ) {
      $params['gid'] = $group_id;
      file_put_contents($_SERVER['DOCUMENT_ROOT'].'/logs/log', 'group_id '.print_r($params['gid'],true),FILE_APPEND | LOCK_EX);
    }

    //Получаем сервер для загрузки изображения
    $response = $this->method("photos.getUploadServer", $params);
    if( isset($response) == false ) {
      print_r($response);
      exit;
    }
    $server = $response->response->upload_url;
    file_put_contents($_SERVER['DOCUMENT_ROOT'].'/logs/log', ' server '.print_r($server,true),FILE_APPEND | LOCK_EX);
    //Отправляем файл на сервер
    $ch = curl_init($server);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, array('photo' => class_exists("CURLFile", false) ? new CURLFile($file) : "@" . $file));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data; charset=UTF-8'));
    $json = json_decode(curl_exec($ch));
    curl_close($ch);

    //Сохраняем файл в альбом стены 
    $photo = $this->method("photos.save", array(
      "server" => $json->server,
      "photos_list" => ($json->photo),
      "hash" => $json->hash,
      "album_id" => 228603162,
      "gid" => $group_id
    ));

    file_put_contents($_SERVER['DOCUMENT_ROOT'].'/logs/log', ' photo '.print_r($photo,true),FILE_APPEND | LOCK_EX);
    
    if( isset($photo->response[0]->id) ) {
      return $photo->response[0]->id;
    } else {
      return false;
    }
  }
}

calling
$vk = new Model_Vk($access_token);

$upload_img = $vk->uploadImage($image_path, $group_id);

if the server for uploading images is photos.getUploadServer
then I get

[error_code] => 118
[error_msg] => Invalid server

if photos.getWallUploadServer then

[error_msg] => Invalid hash

Where is wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
green176, 2016-02-25
@green176

Pokolupalsya and reached the final, it turns out to post, the code is working!

class Model_Vk {

    private $access_token;
    private $url = "https://api.vk.com/method/";

    /**
     * Конструктор
     */
    public function __construct($access_token) {

        $this->access_token = $access_token;
    }

    /**
     * Делает запрос к Api VK
     * @param $method
     * @param $params
     */
    public function method($method, $params = null) {

        $p = "";
        if( $params && is_array($params) ) {
            foreach($params as $key => $param) {
                $p .= ($p == "" ? "" : "&") . $key . "=" . urlencode($param);
            }
        }
        $response = file_get_contents($this->url . $method . "?" . ($p ? $p . "&" : "") . "access_token=" . $this->access_token);

        if( $response ) {
            return json_decode($response);
        }
        return false;
    }

  public function uploadImage($file, $group_id = null, $album_id = null) {

    $params = array();
    if( $group_id ) {
      $params['group_id'] = $group_id;
    }
    if( $album_id ) {
      $params['album_id'] = $album_id;
    }

    //Получаем сервер для загрузки изображения
    $response = $this->method("photos.getUploadServer", $params);


    if( isset($response) == false ) {
      print_r($response);
      exit;
    }
    
    $server = $response->response->upload_url;

    $postparam=array("file1"=>"@".$file);
    //Отправляем файл на сервер
    $ch = curl_init($server);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$postparam);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data; charset=UTF-8'));
    $json = json_decode(curl_exec($ch));
    curl_close($ch);


    

    
    //Сохраняем файл в альбом
    $photo = $this->method("photos.save", array(
      "server" => $json->server,
      "photos_list" => $json->photos_list,
      "album_id" => $album_id,
      "hash" => $json->hash,
      'gid' => $group_id
    ));
    

    if( isset($photo->response[0]->id) ) {
      return $photo->response[0]->id;
    } else {
      return false;
    }
  }
}

Usage:
token required, standalone application, token obtained by link
https://oauth.vk.com/authorize?client_id=YOUR_APP_...
where YOUR_APP_ID is the id of your application,
copy it from the address bar
$access_token = "токен";
$group_id = "ид группы";
$album_id = 'ид альбома в который будем грузить';
$image_path = путь к файлу;

$vk = new Model_Vk($access_token);

//Загружаем изображение
$upload_img = $vk->uploadImage($image_path,$group_id,$album_id);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question