Can't create cookie in Laravel5 - php

I'm having problems to create cookie in Laravel5. The code is below.
$input = $request->input('first');
if($request->hasCookie('first'))
{
return response()->json('ok');
}
else
{
Cookie::make('first', 'first', 1);
return response()->json('no');
}
I also tried this:
public function createCookie(CookieJar $cookieJar)
{
$cookieJar->make('first', 'first', 1);
}
Nothing works for me, can someone illuminate me?
Thanks in advance. When i try to var_dump and get the cookie value it gives me NULL.

By doing this Cookie::make('first', 'first', 1); , you are creating a cookie it doesn't mean it is already set. you have to send cookie with response.
use below code:
$cookie=Cookie::make('first', 'first', 1);
return response()->json('no')->withCookie($cookie);

Cookies are sent only a request after you created them.
An easier way to check if cookie exist or not is to check http headers in the browser or resources->cookies in Chrome.
Also you didn't provide the dd/var_dump code you used or neither why you need to use a new cookie instead of using Laravel Session::flash

Related

Laravel 5.8 cookie value is different from what I set

I am trying to upgrade from Laravel 4.2 to 5.8, I saw that I can still use Cookie::forever and Cookie::get to work with cookie so I didnt had to change my code but the weird thing is that the cookie is set with the correct name but his value is very different (encrypted I guess) from what I set, I am doing this :
// login page
$cookie = Cookie::forever('session_id', 'test');
return redirect('/')->withCookie($cookie);
// index page
$cookie = Cookie::get('session_id');
echo $cookie; // return something like eyJpdiI6ImZqdnF2NkVkbVc4VGJiS3FSYzk4VWc9PSIsInZhbHVlIjoiTkgrVW
This was working fine on 4.2, did I miss something ?
Found a solution here https://stackoverflow.com/a/55223542/561670, its a decrypt issue, this is working :
\Crypt::decryptString(Cookie::get('session_id'))

Issue setting cookies

I'm trying to set cookies for the first time. I've been following the documentation on W3 schools but it doesn't seem to be working for me.
Here is my code (some naming omitted for this example):
$namenospace = 'thisnameexample';
function someSetup($somename){
$nameofcookie = $somename . '_some_value';
if(!isset($_COOKIE[$nameofcookie])) {
$someValue = rand(1, getrandmax());
$cookielastsfor = time() + (86400 * 30);
setcookie($nameofcookie, $someValue, $cookielastsfor, "/");
}
else {
$someValue = $_COOKIE[$nameofcookie];
};
return $someValue;
};
$setSomeValue = someSetup($namenospace);
As you can see, I'm trying to check if a cookie is set, if it is, grab the value and use it, otherwise, set the cookie, then return the value anyway.
For some reason this setcookie() function isn't working. Does anyone have any insight on this?
Possibly worth noting this is a wordpress site if that's relevant?
Thanks!
Edit: have updated as per scope issues highlighted in comments and still not working as intended.
Edit again: definitely not a duplicate. My team and I discovered the issue and would like this unmarked as duplicate so an answer can be given please!
Make sure you are setting your cookies before output. Where are you calling your function?
As an alternative, you could use JS to set a cookie on client side.

CakePHP: Check if SPECIFIC flash message is set

I have a page with several sections with forms that are submitted from the same page. The forms collapse to save space, but I want to conditionally keep them open if there is an error on submission.
In my controller, I set a specific "key" (see location_key below) for each form, which allows me to echo them in their respective locations:
In controller:
$this->Session->setFlash('You missed something...', 'element_name', array('class'=>'error'), 'location_key');
In view:
$this->Session->flash('location_key')
I'm trying to figure out how to check if $this->Session->flash('location_key') exists. If I do this it works but unsets the flash message:
if ( $this->Session->flash('location_key') ) // = TRUE
//Do something
$this->Session->flash('location_key') // = FALSE (because it just got called)
How can I test for the presence of this flash message without causing it to go away?
Figured it out! This works:
$this->Session->check('Message.location_key')
It returns true/false depending on whether there are any such flash messages set. ->read() does the same thing, but returns the flash data if there is (any and crucially, it leaves the session var so it can still be echoed later).
Flash messages are (surprise) stored in the session:
public function setFlash($message, $element = 'default', $params = array(), $key = 'flash') {
CakeSession::write('Message.' . $key, compact('message', 'element', 'params'));
}
To test for the presence of a flash message, test for the equivalent key in the session, e.g.:
if (CakeSession::check('Message.location_key')) {
...
}
Well, according to the api, the SessionHelper returns a string (with the flash message and element) when you do $this->Session->flash('location_key'), so why not store that string into a variable?
$myFlash = $this->Session->flash('location_key');
if ($myFlash)
/*etc*/
echo $myFlash;

Laravel 4 Redirect Header

Right now I'm trying to learn and test Laravel 4, and I have a little concern about script.
I wanted to insert information into the database, then redirect to the index page; the problem is that when I refresh the page, it displays the message to resend.
Here is the code I use:
public function store()
{
$new_cat = new Cat;
$new_cat->name = Input::get('new_cat');
$new_cat->age = Input::get('age_cat');
$new_cat->save();
return Redirect::action('CatsController#index');
}
The correct way to handle a POST request with a redirect is to issue a 303 status code.
http://en.wikipedia.org/wiki/HTTP_303
Using your original code:
return Redirect::action('CatsController#index', array(), 303);
Or Ochi's:
return Redirect::to('route_name', 303)->withInput();
maybe that will work
return Redirect::to('route_name')->withInput();

Symfony2 not saving sessions properly

I'm having a problem with Symfony creating a new session on each page load, rather than carrying data across requests. The auto_start in the session section in the config.yml is set to false, and regular php sessions work fine. It's only when running in symfony that I get the problem.
For example, I created the test action:
public function sessionTestAction()
{
$s_Response = '<html><head></head><body><p>Foo</p></body></html>'; //Initialize response and headers
$a_Headers = array();
$i_StatusCode = 200;
$oSession = $this->get('session');
var_dump($oSession->all());
if(!$oSession->has('Test'))
{
$oSession->set('Test', 'Bar');
}
$oSession->save();
return new Response($s_Response, $i_StatusCode, $a_Headers);
}
The expected action is, that on the first page load, the var_dump will yield nothing, and that on any subsequent executions, it will contain Test=>Bar. However, it never gets that data across requests.
In addition, it creates a new session id for each request.
I am using Symfony v2.0.15, and PHP v5.4
Anyone have any ideas?
Edit:
I made some progress, I think. I made the following changes to the test action:
public function sessionTestAction()
{
//Initialize response and headers
$oRequest = $this->get('request');
$a_Headers = array();
if (isset($oRequest->headers->all()['cookie']))
{
$a_Headers['Set-Cookie'] = $oRequest->headers->all()['cookie'];
}
$i_StatusCode = 200;
$oSession = $oRequest->getSession();
$oSession->start();
$s_Response = print_r($oSession->all(), true);
if(!$oSession->has('Test'))
{
$oSession->set('Test', 'Bar');
}
$oSession->save();
$oResponse = new Response($s_Response, $i_StatusCode, $a_Headers);
return $this->render('Bundle:Default:index.html.twig', array('response' => $s_Response), $oResponse);
}
Where that twig file has just {{response|raw}}. It now holds the session for 2 out of 3 of the requests. However, on the third request, it's cleared.
Turned out the problem was, someone added a line to set a session cookie whenever the app.php was run, not knowing that symfony handled sessions itself, I guess. Problem solved.
I got this problem a couple times, its very annoying. So, let me describe possible solution.
Open dev environment - yourdomain.com/app_dev.php/ Try to refresh page a couple times. If you see session ID changed each time - it means that sessions are broken.
If you are using chrome (if not - you should, its the best for developers ;) ) - you can open developers tools (click F12).
Next, check Network tab, refresh page and locate your main request.
Check headers for your request - if should see "Cookie:PHPSESSID".
If you dont see - something wrong with cookies. In my case it was
framework:
session:
cookie_domain: mydomain.com

Categories