Yii2 Cookie not generating - cookies

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.

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]);

Passport Authedication Error in laravel 5.5

Error creating resource: [message] fopen(http://127.0.0.1:8000/oauth/token): failed to open stream: HTTP request failed! [file] /var/www/html/local/api-sample-application/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php [line] 324
I'm getting this error when try to implement laravel passport authentication.
This is my code in routes/web.php content:
Route::get('/redirect', function () {
$query = http_build_query([
'client_id' => '3',
'redirect_uri' => 'http://127.0.0.1:8000/oauth/callback',
'response_type' => 'code',
'scope' => '',
]);
return redirect('http://127.0.0.1:8000/oauth/authorize?' . $query);
});
Route::get('/oauth/callback', function () {
$http = new GuzzleHttp\Client;
if (request('code')) {
$response = $http->post('http://127.0.0.1:8000/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => '3',
'client_secret' => 'H1UQCKVRARwASEJLR4ugGjBHHvFy34SCzSJFqQLL',
'redirect_uri' => 'http://127.0.0.1:8000/oauth/callback',
'code' => request('code'),
],
]);
return json_decode((string)$response->getBody(), TRUE);
} else {
return response()->json(['error' => request('error')]);
}
});
When i hit this URL, i'm getting this error, not able to generate the token.
Error message screenshot
I had the same problem, and after 1 day I found the reason...
Since the PHP built-in server is single threaded, requesting another url on your server will halt first request and it gets timed out.
So you can't request localhost from localhost in same thread.
You can easy check it, try 'get' come public server host, 'http://www.example-host.com'..
Check this http://stackoverflow.com/a/25651196/916682

yii2 can't set cookie first visit

I want to set a cookie value at first visit.so I did this.
function init() {
$cookies = Yii::$app->response->cookies;
$cookies->add(new Cookie([
'name' => 'aa',
'value' => '111',
'expire' => time()+86400,
'domain' => '.xxx.cn',
'path' => '/'
]));
}
then I refresh the page, I get nothing(refresh page at least three times, aa value would be set in browser). I knew can't get the cookie value at the same request, but I still want to do that.Any way can do this?

Use cookies on ZF2 redirect

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, '/');

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.