WP_REST_REQUEST: how to add "_embed" to request parameters - wordpress

I added this function to my wordpress REST API to have a custom endpoint
function getSettimanaEventi(){
$request = new WP_REST_Request( 'GET', '/wp/v2/tribe_events' );
$request['_embed'] = '1';
$request['filter[meta_query][0][key]'] = '_EventStartDate';
$request['filter[meta_query][0][value][0]'] = '2017-07-03 00:00:00';
$request['filter[meta_query][0][value][1]'] = '2017-07-09 00:00:00';
$request['filter[meta_query][0][compare]'] = 'BETWEEN';
$request['filter[meta_query][0][type]'] = 'DATE';
$response = rest_do_request( $request );
return $response;
i got a response but there isn't the embedded content.
I know the parameters with a leading '_' are private but i need embedded content.
How can i do?

This works for me perfectly
global $wp_rest_server;
$request = new WP_Rest_Request('GET', '/wp/v2/posts');
$response = rest_do_request($request);
$response = $wp_rest_server->response_to_data($response, true);

The only way i found is to add the "_embed" parameter to the url (when you call it from Postman for example) and delete it from the request parameters

(Update - this doesn't seem to be working. I'll update if I figure it out.)
You must set it in the super global like this:
function getSettimanaEventi () {
// Set super global to simulate request param
$_GET['_embed'] = 1;
$request = new WP_REST_Request( 'GET', '/wp/v2/tribe_events' );
$request['filter[meta_query][0][key]'] = '_EventStartDate';
$request['filter[meta_query][0][value][0]'] = '2017-07-03 00:00:00';
$request['filter[meta_query][0][value][1]'] = '2017-07-09 00:00:00';
$request['filter[meta_query][0][compare]'] = 'BETWEEN';
$request['filter[meta_query][0][type]'] = 'DATE';
$response = rest_do_request( $request );
// cleanup after
unset($_GET['_embed']);
return $response;
}
I found this info in this ticket for WP-API:
https://github.com/WP-API/WP-API/issues/2857

Related

Making asynchronous requests with Goutte library? (PHP)

I found this article on doing asynchronous requests with Goutte:
https://victor.4devs.io/en/web-scraping/scraping-data-with-goutte.html
However, it's from 2017 and it seems to be out of date. Using some code based on that article:
use Goutte\Client;
$goutte = new \Goutte\Client();
$client = $goutte->getClient();
foreach ($randomurls as $url) {
$futureResponse = $client->get($url, ['future' => true]);
$futureResponse->then(function ($response) {
echo $response->getBody();
});
}
I get the error, "Call to undefined method Goutte\Client::getClient()". Based on this thread:
Call to undefined method Goutte\Client::setClient()
I tried:
use Goutte\Client;
use Symfony\Component\HttpClient\HttpClient;
$goutte = new Client(HttpClient::create(['timeout' => 60]));
$client = $goutte->getClient();
foreach ($randomurls as $url) {
$futureResponse = $client->get($url, ['future' => true]);
$futureResponse->then(function ($response) {
echo $response->getBody();
});
}
But I still got the same error. I then tried without the getClient():
use Goutte\Client;
use Symfony\Component\HttpClient\HttpClient;
$client = new Client(HttpClient::create(['timeout' => 60]));
foreach ($randomurls as $url) {
$futureResponse = $client->get($url, ['future' => true]);
$futureResponse->then(function ($response) {
echo $response->getBody();
});
}
But then I got, "Call to undefined method Goutte\Client::get()", as now Goutte uses request(). So then I tried:
use Goutte\Client;
use Symfony\Component\HttpClient\HttpClient;
$client = new Client(HttpClient::create(['timeout' => 60]));
foreach ($randomurls as $url) {
$futureResponse = $client->request('GET', $url, ['future' => true]);
$futureResponse->then(function ($response) {
echo $response->html();
});
}
However, I then get, "Call to undefined method Symfony\Component\DomCrawler\Crawler::then()". I couldn't find any information about that error.
Is it still possible to make asynchronous requests in Goutte after the Goutte updates from a couple years ago?

Symfony 5 : how to create (in a database) with ajax and without form

I have this button and I'd like to make it so when I click on it, there's an ajax that goes directly into my create function in symfony but doesn't display any form (at this point I already have the informations I need). But I have no idea how to get the form that way.
I used to do
$livre = new Livre();
$livre->setUuid(Uuid::v4());
$form = $this->createForm(LivreType::class, $livre);
$form->handleRequest($request);
But obviously I can't use LivreType::class anymore cause I don't need the form.
I keep searching for information about this but I can't find anything
Any ideas?
You'll have multiple way of doing it.
I'm gonna show you a simple way to do it, and try to adapt or find a better way for doing it!
LivreController.php
/**
* #Route(path="/livre/create", methods={POST})
*/
public function createNewLivre(Request $request, EntityManagerInterface $em)
{
$json = $this->getJSON($request);
$newLivre = new Livre();
// Set to your new entity parameters...
$em->persist($newLivre);
$em->flush();
return $this->json([
'message' => 'A new Livre has been added.' // It could also be empty if you don't want to manage anything
]);
}
private function getJSON(Request $request)
{
$data = json_decode($request->getContent(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new HttpException(400, 'json invalid');
}
return $data;
}
script.js
let button = document.getElementById('livreCreatorButton');
button.addEventListener("click", e => {
e.preventDefault();
fetch('http://127.0.0.1:8000/livre/create', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: '{}',
})
});

dynamically populated cascading dropdown error

I found very useful article on the web
for contact form 7
<?php
function ajax_cf7_populate_values() {
// read the CSV file in the $makes_models_years array
$makes_models_years = array();
$uploads_folder = wp_upload_dir()['basedir'];
$file = fopen($uploads_folder.'\make_model_year.csv', 'r');
$firstline = true;
while (($line = fgetcsv($file)) !== FALSE) {
if ($firstline) {
$firstline = false;
continue;
}
$makes_models_years[$line[0]][$line[1]][] = $line[2];
}
fclose($file);
// setup the initial array that will be returned to the the client side script as a JSON object.
$return_array = array(
'makes' => array_keys($makes_models_years),
'models' => array(),
'years' => array(),
'current_make' => false,
'current_model' => false
);
// collect the posted values from the submitted form
$make = key_exists('make', $_POST) ? $_POST['make'] : false;
$model = key_exists('model', $_POST) ? $_POST['model'] : false;
$year = key_exists('year', $_POST) ? $_POST['year'] : false;
// populate the $return_array with the necessary values
if ($make) {
$return_array['current_make'] = $make;
$return_array['models'] = array_keys($makes_models_years[$make]);
if ($model) {
$return_array['current_model'] = $model;
$return_array['years'] = $makes_models_years[$make][$model];
if ($year) {
$return_array['current_year'] = $year;
}
}
}
// encode the $return_array as a JSON object and echo it
echo json_encode($return_array);
wp_die();
}
// These action hooks are needed to tell WordPress that the cf7_populate_values() function needs to be called
// if a script is POSTing the action : 'cf7_populate_values'
add_action( 'wp_ajax_cf7_populate_values', 'ajax_cf7_populate_values' );
add_action( 'wp_ajax_nopriv_cf7_populate_values', 'ajax_cf7_populate_values' );
and some java
<script>
(function($) {
// create references to the 3 dropdown fields for later use.
var $makes_dd = $('[name="makes"]');
var $models_dd = $('[name="models"]');
var $years_dd = $('[name="years"]');
// run the populate_fields function, and additionally run it every time a value changes
populate_fields();
$('select').change(function() {
populate_fields();
});
function populate_fields() {
var data = {
// action needs to match the action hook part after wp_ajax_nopriv_ and wp_ajax_ in the server side script.
'action' : 'cf7_populate_values',
// pass all the currently selected values to the server side script.
'make' : $makes_dd.val(),
'model' : $models_dd.val(),
'year' : $years_dd.val()
};
// call the server side script, and on completion, update all dropdown lists with the received values.
$.post('/wp-admin/admin-ajax.php', data, function(response) {
all_values = response;
$makes_dd.html('').append($('<option>').text(' -- choose make -- '));
$models_dd.html('').append($('<option>').text(' -- choose model -- '));
$years_dd.html('').append($('<option>').text(' -- choose year -- '));
$.each(all_values.makes, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_make == this) {
$option.attr('selected','selected');
}
$makes_dd.append($option);
});
$.each(all_values.models, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_model == this) {
$option.attr('selected','selected');
}
$models_dd.append($option);
});
$.each(all_values.years, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_year == this) {
$option.attr('selected','selected');
}
$years_dd.append($option);
});
},'json');
}
})( jQuery );
</script>
but when i add it to me website nothing appear in the dropdowns. They are empty.
I tried to contact the blogger but there is no answer yet. Give me some advice
I copied the csv almost as the one in the post. So I think the function is mistaken... somewhere
I found the solution: in the article the file name is mistaken. It has to be "make_model_year.csv" !!!

Silex: RouteNotFoundException with PHPUnit - Unable to generate a URL for the named route "homepage" as such route does not exist

I asked this on https://github.com/silexphp/Silex/issues/1442 but I have a feeling it isn't necessarily a code problem so I thought I would extend the reach.
upgrading to silex 2 and symfony 3 and all the rest...
routes are included at end of app.php and look something like this...
$app->get('/', 'queue.controller:indexAction')
->after(function (Request $request, Response $response, $app) {
$response->setPublic();
$response->setSharedMaxAge($app['cache']['s-maxage']);
})
->host($app['domains']['xxx'])
->bind('homepage');
this works great in a browser, goto homepage, works fine. If I am running phpunit though... I get the following error when trying to generate a route...
Symfony\Component\Routing\Exception\RouteNotFoundException: Unable to generate a URL for the named route "homepage" as such route does not exist.
and the test looks something like this...
public function testTargetingOnHomepage()
{
$client = $this->createClient();
echo $this->app->url('homepage');
.....
}
i am bewildered as to why my routes are not getting added to app when being executed from phpunit.
test case class has ...
class AdTargetControllerTest extends SomeWebTestCase
and that somewebtestcase.php looks like ...
<?php
namespace theapp\SomeFramework;
use Silex\WebTestCase;
use Fixtures\UserFixture;
use Symfony\Component\BrowserKit\Client;
use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage;
class SomeWebTestCase extends WebTestCase
{
public $youtubeEmbed;
private $mockSessionDir;
public function createApplication()
{
$appDir = __DIR__.'/../../..';
$app = include "$appDir/app.php";
$app['debug'] = true;
$app['session.test'] = true;
$this->mockSessionDir = $app['tmpdir']. '/mocksessions';
$app['session.storage.test'] = function ($app) {
return new MockFileSessionStorage($app['tmpdir']. '/mocksessions');
};
unset($app['exception_handler']);
// Emails get stored in the mail "logger" ... not delivered.
$app['mailer.logger'] = function ($app) {
return new \Someecards\SomeFramework\MessageLogger();
};
// Force silex to use transport and not spooltransport
$app['swiftmailer.use_spool'] = false;
$app["swiftmailer.transport"] = function ($app) {
return new \Swift_Transport_NullTransport($app['swiftmailer.transport.eventdispatcher']);
};
$app->extend('mailer', function ($mailer, $app) {
$mailer->registerPlugin($app['mailer.logger']);
return $mailer;
});
$this->youtubeEmbed = '<iframe width="480" height="270" src="https://www.youtube.com/embed/';
$this->youtubeEmbed .= 'LDtHJYa6xu4?feature=oembed" frameborder="0" allowfullscreen></iframe>';
// using Mockery since this library uses a static method for create
$app['oembedMock'] = \Mockery::mock('alias:Embed\Embed');
$app['oembedMock']
->shouldReceive('create')
->andReturn(
(object) array(
'title' => 'Oembed title',
'description' => 'Oembed Description',
'providerName' => 'YouTube',
'code' => $this->youtubeEmbed,
'type' => 'video',
'author' => 'test',
'authorUrl' => 'test',
'width' => 500,
'height' => 500,
'image' => 'test',
'imageWidth' => 500,
'imageHeight' => 500
)
);
$app->boot();
return $app;
}
there are other functions here but thats the important one i believe.
phpunit bootstraps with ...
<?php
use theapp\SomeFramework\TestingUtil;
// autoload libraries
require_once __DIR__.'/../thirdparty/vendor/autoload.php';
TestingUtil::init();
and then testingutil.php looks like ...
namespace Someecards\SomeFramework;
class TestingUtil
{
public static function init()
{
// This if/else allows the phpunit processIsolation flag to be set to true.
// We're not currently doing that because it slows things down three fold.
// If you see errors about too many open connections/files you can run
// ulimit -n 10000, try to close db connections and log files (couldn't fclose
// these in tearDowns for some reason), or turn on processIsolation.
if (!defined('PHPUNIT_HAS_BOOTSTRAPED')) {
self::bootstrap();
define('PHPUNIT_HAS_BOOTSTRAPED', true);
}
}
public static function bootstrap()
{
$app = require __DIR__.'/../../../app.php';
$app->boot();
$dbOptions = $app['db.options'];
if ($dbOptions['driver'] == 'pdo_sqlite') {
$testdb = $dbOptions['path'];
if (file_exists($testdb)) {
#unlink($testdb);
}
$cacheDriver = $app['orm.em']->getConfiguration()->getMetadataCacheImpl();
$cacheDriver->deleteAll();
$cacheDriver = $app['orm.em']->getConfiguration()->getResultCacheImpl();
$cacheDriver->deleteAll();
$cacheDriver = $app['orm.em']->getConfiguration()->getQueryCacheImpl();
$cacheDriver->deleteAll();
$tool = new \Doctrine\ORM\Tools\SchemaTool($app['orm.em']);
$classes = $app['orm.em']->getMetadataFactory()->getAllMetadata();
$tool->createSchema($classes);
$loader = new \Doctrine\Common\DataFixtures\Loader();
$loader->loadFromDirectory(__DIR__ ."/../../Fixtures");
$purger = new \Doctrine\Common\DataFixtures\Purger\ORMPurger();
$executor = new \Doctrine\Common\DataFixtures\Executor\ORMExecutor($app['orm.em'], $purger);
$executor->execute($loader->getFixtures());
}
register_shutdown_function(
function ($app) {
$path = $app['orm.default_cache']['path'];
if (is_dir($path) === true) {
$files = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($path),
\RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $file) {
if (in_array($file->getBasename(), array('.', '..')) !== true) {
if ($file->isDir() === true) {
rmdir($file->getPathName());
} elseif (($file->isFile() === true) || ($file->isLink() === true)) {
unlink($file->getPathname());
}
}
}
rmdir($path);
} elseif ((is_file($path) === true) || (is_link($path) === true)) {
return unlink($path);
}
},
$app
);
}
}

Upload image/video to facebook asynchronously using php sdk 4

I am trying to upload video/image to facebook albumb using php sdk 4 asynchronously.I googled and found that php asynchronous call be sent using fsockopen. However, it is not working for facebook request. I have two files, one for checking login and getting token. Then second file is called for uploading the file to facebook. Below is the code for first file:
// start session
session_start();
Yii::import('application.vendor.*');
require_once('facebook-4/autoload.php');
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
// init app with app id and secret
FacebookSession::setDefaultApplication('xxxxx', 'yyyy');
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'http://website.com/user/login/page/view/fb-share-php1' );
// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// validate the access_token to make sure it's still valid
try {
if ( !$session->validate() ) {
$session = null;
}
}catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
}
if ( !isset( $session ) || $session === null ) {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
// handle this better in production code
print_r( $ex );
} catch( Exception $ex ) {
// When validation fails or other local issues
// handle this better in production code
print_r( $ex );
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION['fb'] = $session;
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
//$session = new FacebookSession( $session->getToken() );
// graph api request for user data
//$request = new FacebookRequest( $session, 'GET', '/me' );
//$response = $request->execute();
backgroundPost('http://website.com/user/login/page/view/fb-share-php');
// get response
//$graphObject = $response->getGraphObject()->asArray();
// print profile data
//echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
// print logout url using session and redirect_uri (logout.php page should destroy the session)
echo 'Logout';
}else {
// show login url
echo 'Login';
}
function backgroundPost($url){
$parts=parse_url($url);
//print_r($parts);exit;
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
if (!$fp) {
echo "test";
return false;
} else {
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ". 0 ."\r\n";
$out .= "Cookie: PHPSESSID=" . $_COOKIE['PHPSESSID'] . "\r\n";
$out .= "Connection: Close\r\n\r\n";
if (isset($parts['query'])) $out.= $parts['query'];
// print_r($out);exit;
fwrite($fp, $out);
fclose($fp);
return true;
}
}
And second file is:
// start session
session_start();
Yii::import('application.vendor.*');
require_once('facebook-4/autoload.php');
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
$session = $_SESSION['fb'] ;
file_put_contents('file.txt', serialize($session));
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$response = (new FacebookRequest(
$session, 'POST', '/me/photos', array(
'source' => '#/var/www/website-root/images/add_more.png',
'message' => 'User provided message'
)
))->execute()->getGraphObject();
file_put_contents('files.txt', serialize($session));
// If you're not using PHP 5.5 or later, change the file reference to:
// 'source' => '#/path/to/file.name'
//echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
Finally, I figured out the way to achieve it. Now, I am using facebook javascript sdk with php sdk. Following is the process:
1)Get access token from javascript sdk(first file) and pass it to background along with the url of image/video. Code may be modified, if image/video is being uploaded through source.
2) php file(2nd file) containing function for executing backend-process(which is in third file) receives the posted data and and call the third file(in the form of url) and pass the data to it as well.
3) File(s) are uploaded to facebook through php sdk 4(third file)
Below is the code for first file containing javascript sdk code:
<script>
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
window.fbAsyncInit = function() {
FB.init({
appId : 'your app id',
xfbml : true,
version : 'v2.0'
});
FB.login(function(response){
console.log(response);
if (response.status === 'connected') {
var data = new Array();
alert('Logged into your app and Facebook.');
//type: 0 for photo and type:1 for video. Create data array dynamically for real word applications
data[0]= {url: 'http://url-of-video-file.mov',privacy : 'SELF', message: "title of video", type:1};
data[1]= {url: 'http://url-to-image-file.png',privacy : 'SELF', message: "photo caption", type:0};
$.ajax({
url: 'http://url-of-second-file/containing-code-for/backend-process',
data: {data: data, accessToken:response.authResponse.accessToken},
type: 'POST',
success:function(){
alert("photo uploaded");
}
});
},{scope:'email'});
}
</script>
Now code of second file which receives data and execute back-end process:
<?php
//session_start();
ignore_user_abort(true);
set_time_limit(0);
function backgroundPost($url){
$parts=parse_url($url);
//print_r($parts);exit;
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
if (!$fp) {
echo "test";
return false;
} else {
$vars = $_POST;
$content = http_build_query($vars);
//file_put_contents('url.txt',$content);exit;
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ". strlen($content) ."\r\n";
//$out .= "Cookie: PHPSESSID=" . $_COOKIE['PHPSESSID'] . "\r\n";
$out .= "Connection: Close\r\n\r\n";
if (isset($parts['query'])) $out.= $parts['query'];
// print_r($out);exit;
fwrite($fp, $out);
fwrite($fp,$content);
fclose($fp);
return true;
}
}
backgroundPost('http://link-to-third-file/containing-code-for-facebook-upload');
Now code of third file, which will actually upload the files. Please note, video files need to be downloaded before it can be uploaded.
<?php
// start session
//session_start();
error_reporting(1);
ignore_user_abort(true);
set_time_limit(0);
#ini_set('display_errors', 1);
//include facebook library through autoload
require_once('facebook-4/autoload.php');
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
// init app with app id and secret
FacebookSession::setDefaultApplication('app_id','secret_key' );
$session = new FacebookSession( $_POST['accessToken'] );
foreach($_POST['data'] as $key => $data){
if($data['type'] == 1){
$ext = substr($data['url'],strrpos($data['url'],'.'));
$file = '/path/to/temp/location/for/saving/video/'.time().$ext;
if(file_put_contents($file,file_get_contents($data['url']))){
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$response = (new FacebookRequest(
$session, 'POST', '/me/videos', array(
'source' => '#'.$file,
'title' => $data['message'],
'privacy' => json_encode(array('value' => $data['privacy'])),
'published' => true
)
))->execute()->getGraphObject()->asArray();
// If you're not using PHP 5.5 or later, change the file reference to:
// 'source' => '#/path/to/file.name'
//echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
}else{
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$response = (new FacebookRequest(
$session, 'POST', '/me/photos', array(
'url' => $data['url'],
'message' => $data['message'],
'privacy' => json_encode(array('value' => $data['privacy'])),
'published' => true
)
))->execute()->getGraphObject()->asArray();
// If you're not using PHP 5.5 or later, change the file reference to:
// 'source' => '#/path/to/file.name'
//echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
}
?>

Resources