Use cookies on ZF2 redirect - cookies

I'm trying to set a cookie on redirect:
$cookie = new \Zend\Http\Header\SetCookie('success','1');
$response = $this->redirect()->toRoute(..., array('controller' => 'abc', 'action' => 'xyz')));
$response->getHeaders()->addHeader($cookie);
return $response;
And in the xyz action on abc controller:
$success = $this->getRequest()->getCookie()->success;
But the cookie is not being detected? How do I set a cookie and redirect?

try this :
$cookie = new \Zend\Http\Header\SetCookie('success','1');
//response1
$response = $this->getEvent()->getResponse();
$response->getHeaders()->addHeader($cookie);
//response2
$response = $this->redirect()->toRoute(..., array('controller' => 'abc', 'action' => 'xyz')));
return $response1;
response2 is the same object as response1 .... checkout the Redirect Controller Plugin source code to see why?
I am not sure but i think your code doesn't work becuase you need to set the cookie header before location header ...
this worked for me ,if it is still not working for you set the cookie path:
$cookie = new \Zend\Http\Header\SetCookie('success', '1', null, '/');

Related

How to send XML POST request with Guzzle to web service API using Laravel?

I am trying to post a request to my Web API, using Laravel Guzzle Http client. However, I am getting errors trying to post the request. The data I want to send is XML as the API controller is built in XML return format.
I have tried all sorts of methods to post the request with Guzzle but it is yet to work.
public function createProperty(Request $request)
{
$client = new Client();
$post = $request->all();
$create = $client->request('POST', 'http://127.0.0.1:5111/admin/hotel', [
'headers' => [
'Content-Type' => 'text/xml; charset=UTF8',
],
'form-data' => [
'Name' => $post['hotel_name'],
'Address' => $post['address'],
'Phone' => $post['phone'],
'Email' => $post['email'],
'Website' => $post['website'],
'Latitude' => $post['latitude'],
'Longitude' => $post['longitude'],
'Tags' => $post['tags'],
'Priority' => $post['priority'],
'Visible' => $post['visible'],
'Stars' => $post['stars'],
'Description' => $post['description'],
'Facilities' => $post['facilities'],
'Policies' => $post['policies'],
'ImportantInfo' => $post['important_info'],
'MinimumAge' => $post['minimum_age']
]
]);
//dd($create->getBody());
echo $create->getStatusCode();
echo $create->getHeader('content-type');
echo $create->getBody();
$response = $client->send($create);
$xml_string = preg_replace('/(<\?xml[^?]+?)utf-16/i', '$1utf-8', $create->getBody());
$xml_string = $create->getBody();
//dd($xml_string);
$hotels = simplexml_load_string($xml_string);
return redirect()->back();
}
I expected the result to POST to the web service and save data to database, but however I got the error "Client error: POST 'http://127.0.0.1:5111/admin/hotel' resulted in a '400 bad request' response. Please provide a valid XML object in the body
Rather than using post-data in the guzzle request, you need to use body:
$create = $client->request('POST', 'http://127.0.0.1:5111/admin/hotel', [
'headers' => [
'Content-Type' => 'text/xml; charset=UTF8',
],
'body' => $xml
]);
$xml will be the XML data you want to send to the API. Guzzle will not create the XML data for you, you'll need to do this yourself.
The XML data can be created using the DomDocument class in PHP.
If you are using Laravel 7+ this simple line should work very well
$xml = "<?xml version='1.0' encoding='utf-8'?><body></body>";
Http::withHeaders(["Content-Type" => "text/xml;charset=utf-8"])
->post('https://destination.url/api/action', ['body' => $xml]);

Yii2 Cookie not generating

I am trying to set the cookie but cookie is not getting saved. Below is what I have tried:
$cookies = Yii::$app->response->cookies;
$cookies->add(new \yii\web\Cookie([
'name' => 'abc',
'value' => 'xyz',
'expire' => time() + 86400 * 365,
]));
$cookies1 = Yii::$app->request->cookies;
if ($cookies1->has('abc'))
$cookieValue = $cookies1->getValue('abc');
echo 'value : '.$cookieValue;
echo '<pre>'; print_r($_COOKIE);
$cookieValue does not hold any value. Cookie isn't generated. What am I doing wrong?
Your code is fine. Your problem is that you are trying to set and then get the cookie in the same request.
Your browser has not yet received the response, so it has not had the chance to add the cookie before you try to read it out.
You just need to set and then fetch the cookie in separate requests:
public function actionSetCookie() {
$cookies = Yii::$app->response->cookies;
$cookies->add(new \yii\web\Cookie([
'name' => 'abc',
'value' => 'xyz',
'expire' => time() + 86400 * 365,
]));
echo 'Cookie set!';
}
public function actionGetCookie() {
$cookies1 = Yii::$app->request->cookies;
if ($cookies1->has('abc'))
$cookieValue = $cookies1->getValue('abc');
echo 'value : '.$cookieValue;
}
Set your cookie like this
$cookie = Yii::$app->response->cookies;
$cookie = new \yii\web\Cookie
([
'name' => 'abc',
'value' => 'xyz',
'expire' => time() + 86400 * 365,
]);
Yii::$app->getResponse()->getCookies()->add($cookie);
//check cookie is exist or not
if(Yii::$app->getRequest()->getCookies()->has('abc'))
{
// if exist then get cookie value
$username = Yii::$app->getRequest()->getCookies()->getValue('abc');
}
Just putting here my answer, as several time visited this question but could not find solution. I spent one whole day to solve it. So hope this answer will help someone.
In my case I've used axios package which sent request from frontend and I got response Set-Cookie in the header but not saved in the browser. So setting axios.defaults.withCredentials = true; solved my issue.

Batch upload multiple photos to multiple user accounts

I have an array that looks as follows:
$userImages = array(
'100000000000001' => array(
'..../image01.jpg',
'..../image02.jpg',
'..../image03.jpg',
),
'100000000000002' => array(
'..../image04.jpg',
'..../image05.jpg',
'..../image06.jpg',
),
);
which contains FB user ids as keys, and then an array of images to upload to each users account.
My upload code looks as follows:
/** #var FacebookSessionPersistence $facebook */
$facebook = $this->container->get('fos_facebook.api');
$facebook->setFileUploadSupport(true);
$count = 1;
foreach ($userImages as $userId => $images) {
$batch = array();
$params = array();
foreach ($images as $image) {
$request = array(
'method' => 'post',
'relative_url' => "{$userId}/photos",
'attached_files' => "file{$count}",
'access_token' => $this->getUserAccessToken($userId)
);
$batch[] = json_encode($request);
$params["file{$count}"] = '#' . realpath($image);
$count++;
}
}
$params['batch'] = '[' . implode(',', $batch) . ']';
$result = $facebook->api('/', 'post', $params);
return $result;
I've added user access tokens to each image, under access_token, but when $facebook-api() is called, I get the following back from Facebook:
Does anyone know why, I'm getting these errors? Am I adding the user access token in the wrong place?
The access_token had to be added to the $params associative array, in the root, not to each image item!
Your logic is good, but you need to put the access token inside the body for every individual request.
For example:
...
$request = array(
'method' => 'post',
'relative_url' => "{$userId}/photos",
'attached_files' => "file{$count}",
'body' => "access_token={$this->getUserAccessToken($userId)}",
);
...
Does anyone know why, I'm getting these errors? Am I adding the user access token in the wrong place?
Have you made sure, you’ve actually added access tokens at all, and not perhaps just a null value?
The error message does not say that you used a wrong or expired user access token, but it says that a user access token is required.
So I’m guessing, because you did not really put actual tokens into your separate batch request parts in the first place, then the fallback to your app access token occurs, and hence that particular error message.

Prompts user to publish feed with PHP SDK

Sorry for my English, I'll try to explain my problem.
With this code I can publish feed on the wall of the users without prompts (I need extended permissions..)
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'link' => 'www.example.com',
'message' => 'Posting with the PHP SDK!'
));
But How can I use PHP SDK to prompts the user to publish as can be done with this code (using Javascript SDK)
<script src='http://connect.facebook.net/en_US/all.js'></script>
<p><a onclick='postToFeed(); return false;'>Post to Feed</a></p>
<p id='msg'></p>
<script>
FB.init({appId: "YOUR_APP_ID", status: true, cookie: true});
function postToFeed() {
// calling the API ...
var obj = {
method: 'feed',
link: 'https://developers.facebook.com/docs/reference/dialogs/',
picture: 'http://fbrell.com/f8.jpg',
name: 'Facebook Dialogs',
caption: 'Reference Documentation',
description: 'Using Dialogs to interact with users.'
};
function callback(response) {
document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
}
FB.ui(obj, callback);
}
</script>
Thanks to all!
Seems you will need to cUrl the dialog end point to get the effect you desire.
I would suggest using a button or link and opening a new page which will cUrl the endpoint and redirect back to that page with a close tab or page button.
example endpoint link https://www.facebook.com/dialog/feed?app_id=135669679827333&link=https://developers.facebook.com/docs/reference/dialogs/&picture=http://fbrell.com/f8.jpg&name=Facebook%20Dialogs&caption=Reference%20Documentation&description=Using%20Dialogs%20to%20interact%20with%20users.&redirect_uri=http://anotherfeed.com/?pid=facebook
Refer to: https://developers.facebook.com/docs/reference/dialogs/#display
examples: under construction.
<?php
require 'facebook.php';
// Create our application instance
// (replace this with your appId and secret).
$app_id = "APP_ID";
$secret = "APP_SECRET";
$app_url = "APP_URL";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
'cookie' => true,
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
$access_token = $facebook->getAccessToken();
}
?>

What is wrong with Facebook and Twitter APIs?

Is anyone else noticing that facebook and twitters APIs aren't working?
For facebook even if I allow my application to have access to my wall
$facebook->getUser()
Is always 0... When I try to open getLoginUrl it just open pop-up and redirect it instantly to success return link...
Here is code:
require_once 'src/base_facebook.php';
require_once 'src/facebook.php';
$app_id = 'xxx';
$app_secret = 'xxx';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'oauth' => true,
'cookie' => true
));
$req_perms = "publish_stream";
$user = $facebook->getUser();
if (!$user)
{
$loginUrl = $facebook->getLoginUrl(array('display' => 'popup', 'redirect_uri' => 'http://xxxx.com/return_close.php?success=1', 'cancel_url' => 'http://xxxx.com/return_close.php?success=0','req_perms' => $req_perms, 'scope' => $req_perms));
}
And for twitter it's like someone mistyped return link...
When I open getAuthorizeURL and when I log in it redirects me to this URL:
https://twitter.comoauth_callback/?oauth_token=yA2xjLsVRm9tIuVEysXnCV8R7TISW8tF94uznn7zlw&oauth_verifier=Io1N2I8zOEzJeBWI77WXFMqmMRNDfCrXZGQxXmxJLbI
Yes, https://twitter.comoauth_callback/ is right, there is no / after .com, it's together, so I get not found page...
It's like both APIs have serious problems... Facebook sometimes work and sometimes doesn't, it's buggy a lot...
Facebook library downloaded from OFFICIAL GitHub page. Tried versions:
v3.1.1
v3.1.0
v3.0.1
And none of those work...
Update
Return URL ( redirect_uri ) MUST have facebook class included in file...
There is so many examples/documentations and none of those had this explained...
So, Facebook fixed... Twitter still not working...
Well, nothing is broken in the API. Where did you get the above code? and if you come up with it then based on what resource?
First of all, take a look at the example of the OFFICIAL PHP-SDK, you'll notice the following:
Only the facebook.php file has been included, why not base_facebook.php? well because it's included in the facebook.php file!
Developers used to use req_perms but now to request permissions you just need to use scope
Take a look inside base_facebook.php for the params the Facebook() class expect: appId, secret and fileUpload ONLY
Only use the display parameter if you know what you are doing!
Use proper indentation with your code, it makes your life (and others!) much easier!
This been said, this is a rewrite of your code:
require 'src/facebook.php';
$app_id = 'xxx';
$app_secret = 'xxx';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret
));
$req_perms = "publish_stream";
$user = $facebook->getUser();
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array('display' => 'popup', 'redirect_uri' => 'http://xxxx.com/return_close.php?success=1', 'cancel_url' => 'http://xxxx.com/return_close.php?success=0', 'scope' => $req_perms));
}