How to set and retrieve cookies in code igniter - codeigniter

I have tried setting cookies in codeigniter like this, but not working don't know what is the problem
//setting cookie
$this->load->helper('cookie');
if($loaded_position == 'nativelocation' ){
$this->input->set_cookie('nativelocation' , $request_place, '86400');
//echo $this->input->cookie('nativelocation');
}
//retrieving cookie
$this->load->helper('cookie');
$savedlocation = array();
if( $this->input->cookie('addlocation_1') )
{
$savedlocation[]= $this->input->cookie('addlocation_1') ;
}

It looks like you are setting a cookie called "nativelocation" but then you try to retrieve a cookie called "'addlocation_1", and there isn't one. Try:
if( $this->input->cookie('nativelocation') ){
echo $this->input->cookie('nativelocation');
}
Also, know that when setting a cookie, you can not access it on the same "page" you'll need a page refresh, or access the cookie $this->input->cookie('nativelocation') on another page/controller.

Related

Laravel 8 Cookie -> Can't get cookie value

I have annoying problem that I can't fix for hours. Have been trying all google suggestions, so far nothing.
Function for setting/getting cookie right now:
/* Check if user is logged in or else take cookie */
if(Auth::check()){
$user_id = Auth::user()->id;
}else{
if(Cookie::get('user_id') !== null){
$user_id_cookie = Cookie::get('user_id');
}else{
$user_id = Cookie::forever('user_id', Str::random(15));
$user_id_cookie = $user_id;
}
}
/* Check if user is logged in or else take cookie */
Cookie is set, but it doesn't get value back to blade.
For getting cookie value I have tried multiple solutions, for example 2:
$old = Crypt::decryptString(request()->cookie('user_id'))
$cookie_value = explode("|",$old)[1];
Or (As I have another cookie made in same way, and it's working. But I have no idea, why..)
$old= Crypt::decrypt(Cookie::get('user_id'), false);
$cookie_value = substr($old, 41);
But all these solutions shows this error:
Illuminate\Contracts\Encryption\DecryptException
The payload is invalid.

Laravel can't read a "recently" created cookie

I have a project who authenticate the user using cookies like token_ and refreshToken_, and a middleware who intercept my routes and verify if the user is logged or not.
In my middleware, when i need to renew the token_ I have the following code:
namespace App\Http\Middleware\VerifyAccessToken
$cookie_name = "token_";
$cookie_value = $obj->access_token;
$expires_in = $obj->expires_in;
$time = time() + $expires_in; // 3600 = 1 hora
$path = "/";
$domain = env('COOKIE_DOMAIN');
setcookie($cookie_name, $cookie_value, $time, $path, $domain, false, true);
$cookie_name = "refreshToken_";
$cookie_value = $obj->refresh_token;
setcookie($cookie_name, $cookie_value, $time + 3600, $path, $domain, false, true);
return $next($request);
It works apparently fine, but the problem is:
After the middleware intercep my route and renew the cookie, the request proced to his controller, but there, I can't access the cookie using $_COOKIE['token_'] and I get an error, but if I look in the chrome's inspector, the cookie is there and reloading the page (F5) I can access the cookie in controller
Have a method for me access the cookie in controller without need to go to the view before?
To read the value of Cookie in Laravel, do you need to use:
$token = Cookie::queued('token_');
dd($token->getValue());
https://api.symfony.com/3.0/Symfony/Component/HttpFoundation/Cookie.html

Laravel url previous return same page after page reload

I tried to access the previous URL on Laravel 5.3 Homestead by several methods but all times i got the right previous page at first request then i got the same page after i refresh the page.
I am using Middleware to check the language before accessing the page
URL::previous();
// or
back()->getTargetUrl();
Language middleware
public function handle($request, Closure $next, $guard = null) {
$locale = $request->locale;
$segments = $request->segments();
$lang_sess = $request->session()->get('language');
if (!array_key_exists($locale, Config::get('app.locales'))) :
if (count($segments) > 1):
$segments[0] = ($lang_sess == "") ? Config::get('app.fallback_locale') : $lang_sess;
$re_to = implode('/', $segments);
else:
$locale = $request->session()->get('language', 'en');
$re_to = "/$locale/" . implode('/', $segments);
endif;
return Redirect::to($re_to);
endif;
$request->session()->put('language', $locale);
App::setLocale($locale);
return $next($request);
}
[SOLVED]
as i still developing my web app, i didn't go the page through a 'href' link, i was entering it through copy and paste the URL into browser, and this causes the URL::previous to be changed after reload the page..
Case closed, thanks for all who replied and gave attention.
the 'previous URL' is stored in a session.Every time your URL changes, the session()->get('_previous')['url'] will change to previous url.
Doing the logic this way:
if (url()->current() == url()->previous()) {
url()->setPreviousUrl('xxx') // or other logic here
}
If you go to page A from B . Your previous page will be B . But if you refresh page then you are going from A to page A.
I suggest to use cookie in this case by checking previous page , if different change cookie otherwise keep it as it is.
$last_page = URL::previous();
if(Cookie::get("previous_page") == $last_page){
Cookie::make('previous_page',$last_page, 60);
}
Now you can use this cookie value Cookie::get ("previous_page") in your middleware
Not tested but this would guide you.

CodeIgniter Getting Not Found Image Path In Session

I'm implementing redirect to previous page after login and logout.
So in each methods of controller I've saved session like as follow.
$this->session->set_userdata('previous_page', current_url());
And after successful login and logout, I'm calling a library method as follows.
function redirect_to_previous_url() {
$url = base_url();
if($this->_CI->session->userdata('previous_page')) {
// Get previous_url
$url = $this->_CI->session->userdata('previous_page');
$this->_CI->session->unset_userdata('previous_page');
}
return $url;
}
But Its redirecting to base_url of the site. After checking the session value Its showing not found image path but not what I've saved it before.
I'm not able to find out what is the problem behind this.
Please help me to rectify and the work would be appreciated
Try this..
function redirect_to_previous_url() {
$url = base_url();
if($this->_CI->session->userdata('previous_page')) {
// Get previous_url
$url = $this->_CI->session->userdata('previous_page');
$this->_CI->session->unset_userdata('previous_page');
return $url;
}
return $url;
}
I would ensure the session was set. Like this;
if($this->_CI->session->userdata('previous_page')) {
show_error('The session is set');
}
If you don't see the error, the session isn't set. Then you know this isn't where the problem lies.
No need to store Previous URL in session.
In core php you can get previously visited URL in following server variable
$_SERVER['HTTP_REFERER'];
Same can be achieved in CodeIgniter as
$this->load->library('user_agent');
echo $this->agent->referrer();

PHP and session

I have strange problem with sessions. In my small admin panel for my site there were some pages, 6 in fact. All worked nice. But in time I added one more page and when I go to that one firstly I see the content and after refreshing page or going to another one I'm thrown out from the account. Cookies are not deleted. It seems that session is destroyed but there is no any work with sessions. That is just infomartion page where some data from db is displayed.
This is code from index.php where session starts:
ini_set('session.gc_maxlifetime', 3600);
ini_set('session.cookie_lifetime', 3600);
session_start();
...
And this code from problem page 'orders.php':
$res = $administrator->getOrders();
while($order = mysql_fetch_array($res, MYSQL_ASSOC)) {
filtrate and print data from db in a table
}
Do you have any assumptions? I have not, was searching for an error for 2 days ;(
Check authorization function:
public function checkLogin() {
if(isset($_SESSION['hash']) && isset($_SESSION['id'])) {
$id = intval($_SESSION['id']);
$where = "`id`='$id'";
$cookie = DBWorking::getFieldWhere('cookie', 'users', $where);
$hash = mysql_fetch_assoc($cookie);
if($_SESSION['hash'] === $hash['cookie']) {
return true;
}
}
return false;
}

Resources