Posting a group of pictures with text using the Vkontakte API

  • Tutorial
The task of posting text with a picture to the VKontakte group with a PHP script is simple, especially since the VKontakte API is considered understandable and reliable. Nevertheless, I could not find on the Internet a clear step-by-step guide for beginners, which would contain ready-made answers to all the small questions that arise along the way.

To get started, you must be logged into an account that has the right to add posts to the group.

Create an application

First of all, you need to create a Standalone application. For this you must have a VK account with a linked phone number. In my practice, if the account does not have an attached phone number, then the contact begins to respond very quickly to the API with errors asking them to enter captcha)) that is, it will also need to put the captcha operator next to the script.

Generate access token

Next, we need an access token for authorization in the API. To generate it, you must go to the special link,wall,offline,photos&redirect_uri= = token , where parameter client_id pass the identifier of the previously created application. The scope parameter denotes the set of rights that you award the application. Read more about rights in the documentation . After clicking on the link, you need to confirm the transfer of rights to the application and copy the access token directly from the URL, despite the contact warning. Please do not copy the data from the address bar for third-party sites. Thus, you may lose access to your account.. The token generated in this way will be enough to work with the group for unlimited time.

Write some code

Solving this problem, I tried to find a ready-made library, I found this one , and as a result I got a fork , which is used in the example below. For experts on code quality: this library is intended solely for demonstration purposes, it does not have extensive functionality, tests, good documentation, performance optimization, cross-platform (need php 5.4) and other things - all this was left to the tireless reader for implementation.
So, we post the text with the picture and tags to the VKontakte community:
// git clone
$accessToken = 'your access token';
$vkAPI = new \BW\Vkontakte(['access_token' => $accessToken]);
$publicID = 70941690;
if ($vkAPI->postToPublic($publicID, "Привет Хабр!", '/tmp/habr.png', ['вконтакте api', 'автопостинг', 'первые шаги'])) {
    echo "Ура! Всё работает, пост добавлен\n";
} else {
    echo "Фейл, пост не добавлен(( ищите ошибку\n";

The result of executing this code with my token. If you look at the code, then interaction with the VKontakte API occurs strictly according to the documentation . Thanks for attention!

Also popular now: