yii2 can't set cookie first visit - cookies

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?

Related

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.

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.

Flash size on publishing post by Graph API

I use Facebook Graph API to post on user's wall. I also attach Flash application ("source" parameter) to it.
$data = array(
'name' => 'Test name',
'message' => 'Custom message',
'picture' => 'http://www.example.com/image.png',
'link' => 'http://www.example.com',
'description' => 'Description of the message',
'source' => 'http://www.example.com/flash.swf',
'access_token' => '... token_here ...',
'method' => 'post'
);
$ret = file_get_contents('https://graph.facebook.com/me/feed?'.http_build_query($data));
The problem that i can't set flash size. For example if use REST API, then you can define attached flash size by "expanded_width" and "expanded_height" parameters.
A few month ago when i tried to publish such post i saw that Facebook set flash size to 398x260, but today when i tried it again, i saw that Facebook set size to 398x224.
1) Does someone know if there is some way to define flash size in Graph API, like in REST API?
2) Is there some official documentation that provide default size of post attachment (source)?

ZF routing - url with extension with Nth params

Similar to this question, I have accomplished passing the format with the url extension, but you have have to declare the parameters passed upfront. Example:
new Zend_Controller_Router_Route_Regex(
'([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)(\.(\w+))?',
array(
'module' => 'Default',
'controller' => 'index',
'action' => 'index',
),
array(
1 => 'module',
2 => 'controller',
3 => 'action',
4 => 'extension',
5 => 'format'
)
);
But what if I want /:module/:controller/:action/*.:format???
So that no matter how many parameters I pass through the url, the '.whatever' will be the format parameter? Basically, I'm trying to take the default router and add extension as the 'format param'.
Edit:
The issue isn't grabbing the extension, the issue is adding other params. For example
/blogs/posts/view/post/500/foo/bar/format/html
will translate into:
array('module'=>'blogs','controller'=>'posts', 'action' => 'view', 'post'=>500, 'format' => 'html', 'foo' => 'bar');
But I want to be able to represent the format the same route like so:
/blogs/post/view/post/500/foo/bar.html
No matter how many parameters are declared between the action and the format.
Your whatever you can specify with .* expression.
To match it - simply: (.*)
If you want not to grab for example extension, use ?:
(.*?)(\.(\w+))