Php facebook share picture

Кнопки «Поделиться», «Tweet» и «Share» с собственным дизайном

Начну с того, что дизайн — не единственная причина, по которой следует использовать собственные кнопки социальных сетей. О причинах написано в отдельном посту, поэтому сейчас в это углубляться не будем.

Рассмотрим создание кнопки для каждого социального сервиса по-отдельности. В качестве тестируемой страницы у нас будет стандартный пост WordPress — «Привет, мир!».

Twitter

Начнём с несложного примера:

Текст и URL — два основных параметра, конечно, их вполне достаточно для создания кнопки, хэштеги например можно спокойно добавлять в переменную $text, тем не менее давайте рассмотрим полный список параметров:

url Абсолютный URL с HTTP или HTTPS, будет автоматически сокращён через t.co. Также рекомендуется пропускать его через php-функцию urlencode() . text Текст твита. Должен быть в кодировке UTF-8 и состоять не более чем из 140 символов (с учётом ссылки и хэштегов!). После нажатия на кнопку «Твитнуть» у пользователя будет возможность отредактировать этот текст — также имейте это ввиду. hashtags Список #хэштегов через запятую без символа «#». via Через что был опубликован твит? Информация будет добавлена в конце твита. Например с помощью @twitterfeed. В передаваемом параметру значении символ «@» указывать не нужно. in_reply_to Ответ на другой твит. В качестве значения параметра нужно указать ID твита, на который нужно ответить. Имя автора, на чей твит мы хотим написать ответ, будет автоматически добавлено в начало твита. related Укажите через запятую аккаунты в Твиттере, которые будет автоматически рекомендовано зафолловить пользователю после того, как он запостит твит.

Раньше я использовал php-функцию для преобразования ссылок через bit.ly, но это значительно тормозило скорость загрузки страниц и я решил не сокращать ссылки на своём блоге.

Язык во всплывающем окошке будет таким же, как в профиле посетителя вашего сайта в твиттере.
Ещё один пример:

При нажатии на кнопку «Твитнуть» получаем следующее:

Поделиться ссылкой в Твиттере

Facebook

p[title] Заголовок поста. p[summary] Анонс поста. p[url] Ссылка на пост. Не забываем про функцию urlencode() . p[images][0] Основное изображение поста, вы также можете перечислить дополнительные изображения в параметрах p[images][1] , p[images][2] и так далее. Хотел бы заметить, что если вы защищаете изображения от хотлинков через .htaccess, то надо будет добавить все эти социальные сети в исключения, иначе ваши картинки просто не будут отображаться.

Поделиться ссылкой на Фейсбук

Вконтакте

Все параметры абсолютно аналогичны параметрам из примера про кнопку Facebook, поэтому не буду их описывать лишний раз. А в результате получаем вот что:

Сохранить в Вконтакте

Ну вот и всё, теперь при помощи CSS вы можете придать ссылкам какой угодно вид (например как у меня на блоге).

Смотрите также

Миша

Впервые познакомился с WordPress в 2009 году. Организатор и спикер на конференциях WordCamp. Преподаватель в школе Нетология.

Пишите, если нужна помощь с сайтом или разработка с нуля.

Читайте также:  Css font family font awesome

Источник

Facebook Share Button Code with PHP

You can create your own custom Facebook share buttons which use dynamic URLs of your web pages with the help of a server side programming language. In this tutorial, I will show you how to create a share button for non-static URLs using PHP.

Imagine that you have a website which uses a CMS (Content Management System) like WordPress or Drupal for its backend or a custom built website which uses a server-side programming language such as PHP to generate dynamic pages. Most static websites with only a couple of pages don’t need such a structure; however, websites with lots of pages, online stores with thousands of products, blogs with many posts, forums with a lot of threads etc., especially if they are frequently updated and new pages are added, certainly need a dynamic structure for easier maintenance and updates.

Such a dynamic website uses specific files (PHP files in this case) to establish and display the structure of the site, while storing the content -usually- in a database. In some cases, many of the same type of pages (e.g. blog posts, product pages, news articles) are controlled via a single PHP file such as page.php, post.php, product.php or something similar. Each page on such a dynamic site is controlled with the same file, but the URLs (permalink) of those pages are still different, due to the use of certain scripts and server rewrite rules.

TIP: On a website, no two pages can have the exact same URL, since otherwise the server will not be able to locate the correct page to display.

In some other tutorials, I showed adding Facebook like and share buttons, as well as adding a share button with no script and multiple share buttons on the same page. In this tutorial, I will focus on how to use PHP for generating the correct dynamic URLs to use in the custom share buttons. You may want to refresh your PHP knowledge before we start.

Custom Facebook Share Button for Dynamic Pages with PHP

If we were to put the share button on a static page, or if we were to use the default share button Facebook provides on its Share Button Configurator we would simply insert the code it generates into the page and it would handle the URLs for both static and dynamic pages correctly. What we are doing here is slightly different as we are building our own custom Facebook share button using our own style.

Now, let’s see how to do it.

STEP 1: Get the URL of the Current Page

The first step is to get the URL of the current page, the page the visitor has open in her browser, and store it in a PHP variable with the following code:

You can put this code to the top of your PHP page file inside PHP tags:

Читайте также:  Ссылка в новом окне

I named the variable as $url for simplicity, you can name it as you wish. If you have SSL on your website, use https instead of http or if you prefer you can also use a simple script to identify your connection type. The $_SERVER[‘HTTP_HOST’] global server variable gives the domain (or subdomain) your website is located at and the $_SERVER[‘REQUEST_URI’] variable gives the URI of the current page. For this site, these variables give the following values:

$_SERVER[‘HTTP_HOST’] = www.tutsandtips.com
$_SERVER[‘REQUEST_URI’] = /php/facebook-share-button-code-with-php/

So, the $url variable, in this case will give the full URL of the current page like the following:

Since the URL is generated dynamically, we can now use this variable in our custom share button.

STEP 2: Insert the Dynamic URL in Custom Share Button

The next step is to put the $url variable into the custom share button link. The URL Facebook uses for sharing web pages is:

If we put this URL in our link and insert the $url variable, we will have the following:

You can insert the above link on your page at a position where you want to display the share button. For example, on this site, I have used the same code for the Share buttons that you see at the top and bottom of this post. If you hover your mouse over those buttons or click on them, you can see the link in action.

You can add styles to the link by assigning it an id or class, and make the link open in a new tab by adding target attribute:

To conclude our tutorial, we can say that this is a great way to create custom Facebook share buttons with PHP as it gives you control over the style.

Источник

How to Upload and Read Facebook User Photos using PHP SDK

Facebook provides options for uploading photos or videos via the interface. We can also post photos, videos, text data to Facebook by using their API. We can create our own application interface and use the Facebook API and post.

Facebook gives different channels to post photos or videos depending on the platform. Here, I have used the Facebook PHP SDK to upload photos to the Facebook edge.

For uploading photos to a Facebook page, the publish_pages and the manage_pages permissions are required with the page access token. The /photos is specified for uploading user photos to the “photos” edge. While uploading photos, the image URL and the caption are set with the appropriate post params.

In this example, we have also stated the code for reading user photos using Facebook PHP SDK get function. In a previous Facebook developer example, we have seen how to read Facebook feed using PHP SDK. The /photos will be mentioned in the get function with the access token.

Читайте также:  Press any key to exit python

Read-and-Upload-Facebook-User-Photo-Output

The SDK functions call with the valid access token will read user photos from Facebook. The photo result is returned in a secured format which can be decoded to parse the data. The decoded data is used to display an image gallery with the Facebook photos.

Creating User Interface to Upload Facebook User Photos

This code is used to create the web interface for uploading the photo to the Facebook using PHP SDK. This interface contains a HTML form with input fields to get the image caption, file and a publish button. A photo icon is used to browse the file explorer to choose the photo to be uploaded to the Facebook. By submitting the Image file and caption, the photo will be uploaded to the specified target.

 

In PHP the selected image and caption is received and posted by using the Facebook PHP SDK method. The image data is added to the array of param elements that are required to send the photo post request. The caption and the url parameters are used to set the image caption and the file address respectively.

 > $fbUserPhoto->uploadPhoto($_POST["photo_caption"],$photoPath); > $postData = $fbUserPhoto->getPhotos(); ?> 

FBUserPhoto.php

This is the PHP class that loads the PHP SDK includes to send or receives user photo data to and from the Facebook edge. This class initializes the API credentials and instantiate Facebook API to access methods to read and upload the user photos.

The getPhotos() function uses the SDK get() method by specifying the /photos edge with the access token. It returns the data related to the Facebook user photos. The returned data is decoded to get the photo thumbnail and the created time to form the image gallery.

The uploadPhoto() function of the FBUserPhoto class receives the image caption and the URL from the user and uploads it to the Facebook. This post action is similar to that of publishing text post to Facebook but the target and params will differ.

appId = "API-KEY"; $this->appSecret = "API-SECRET"; $this->fb = new Facebook([ 'app_id' => $this->appId, 'app_secret' => $this->appSecret, 'default_graph_version' => 'v3.1' ]); $this->accessToken = ""; > function getPhotos() < $postData = ""; try < $userPosts = $this->fb->get("//photos/uploaded?fields=picture,created_time,name", $this->accessToken); $postBody = $userPosts->getDecodedBody(); $postData = $postBody["data"]; > catch (FacebookResponseException $e) < // display error message exit(); >catch (FacebookSDKException $e) < // display error message exit(); >return $postData; > function uploadPhoto($caption, $photoPath) < $params = array( "caption" =>$caption, "url" => "https://yourdomain.com/how-to-upload-facebook-user-photos-using-php-sdk/" . $photoPath ); try < $postResponse = $this->fb->post("//photos", $params, $this->accessToken); > catch (FacebookResponseException $e) < // display error message print $e->getMessage(); exit(); > catch (FacebookSDKException $e) < print $e->getMessage(); exit(); > > > 
  1. Integrate Facebook Login to get the credentials and access token. The access token should be created with the user_photos permission to read photos from the Facebook edge.
  2. The image URL specified with the url param should be a valid remote address. Otherwise, the SDK will throw the “invalid_request” “(#324) Missing or invalid image file” Exception.

Источник

Оцените статью