I'm using a search system, in PHP, that adds the text searched to an array and put it inside a cookie using json_encode().
The problem is: I need to check if the cookie already exists and, if not, create it.
I'm using the following code to simply verify if it exists but without success:
{
$search = $this->input->post('search_text');
$types = $this->input->post('search_type');
$checkboxes = "";
if(!empty($types))
{
foreach($types as $v)
$checkboxes = $v.",";
}
//cookie
$this->load->helper('cookie');
//cookie's array
$search_history = array();
array_push($search_history, $search);
//cookie check 1
if(get_cookie('search')!=''){
echo "cookie exists";
}else
echo "cookie doesn't exist";
// set cookie
$cookie = array(
'name' => 'search',
'value' => json_encode($search_history),
'expire' => time()+86500
);
set_cookie($cookie);
//cookie check 2
if(get_cookie('search')!=''){
echo "cookie exists";
}else
echo "cookie doesn't exist";
//echo get_cookie('search');
//redirect('search/'.urlencode($search).'/'.urlencode($checkboxes));
}
I can create the cookie and get it's value, but I can't seem to find a way to check if it's already created in PHP code.
Have already tried with:
if(get_cookie('search')!='')
,
if(get_cookie('search')!=null)
and with
if(get_cookie('search'))
but neither of those seem to work.
EDIT:
As suggested, I'm now using this and it doesn't create the cookie.
//cookie
$this->load->helper('cookie');
//cookie's array
$search_history = array();
array_push($search_history, $search);
if(cookie('search') == false){
// set cookie
$cookie = array(
'name' => 'search',
'value' => json_encode($search_history),
'expire' => time()+86500
);
set_cookie($cookie);
}
Final EDIT
Problem solved.
//checks if the cookie exists
if($this->input->cookie('cookiename')!=''){
//exists
}
use get_cookie()
if (is_null(get_cookie('cookiename'))) {
//set yours cookie here
}
Related
I have a shopping cart which I store in a cookie. The cookie 'shopping_cart' is set once an item is added onto the cart.
function shopping_cart_add(){
if(isset($_COOKIE['shopping_cart'])){
$cookie_data = $_COOKIE['shopping_cart'];
$cart_data = json_decode($cookie_data, true);
}else{
$cart_data = array();
}
$data = array(
"cart_id" => 1,
"product_id" => $this->input->post('product_id'),
"product_name" => $this->input->post('product_name'),
"product_price" => $this->input->post('product_price'),
"quantity" => $this->input->post('quantity'),
"options" => $this->input->post('options'),
"description" => $this->input->post('description'),
"image" => $this->input->post('image')
);
$cart_data[] = $data;
$item_data = json_encode($cart_data);
setcookie('shopping_cart',$item_data,time() + (86400 * 30));
$_COOKIE['shopping_cart'] = $item_data;
}
I am having a problem with when the user wants to remove an item from cart. I am using codeigniter framework but not its inbuilt cookies.
The following is the code in my view for deleting an item:
<td>Delete</td>
The following is the code in my controller for deleting an item:
function delete($delete_id){
$cookie_data = $_COOKIE['shopping_cart'];
$cart_data = json_decode($cookie_data, true);
foreach ($cart_data as $key => $value) {
if ($cart_data[$key]['product_id'] == $delete_id) {
unset($cart_data[$key]);
$item_data = json_encode($cart_data);
setcookie('shopping_cart',$item_data,time() + (86400 * 30));
header("location:/category/cart_summary.php?remove=1");
}
}
}
However I keep getting an error when I click the delete button.
Undefined variable $_COOKIE['shopping_cart']
Yet when I check my browser it show the cookie exists. What could be the problem?? I have already checked similar questions on stack pertaining to this issue but none has helped.
This includes:
undefined index for cookie in some browsers
PHP Undefined Index When Checking Cookie Value And Cookie Exists
This probably happens because you didn't explicitly mentions on what path the shopping_cart cookies will be saved. Try to add a 4th parameter (path) at each setcookie :
setcookie('shopping_cart',$item_data,time() + (86400 * 30), '/');
I have coded a internal messenger system for the company I work for and I am trying to make things easier for myself by making a admin panel for this so it can control the usernames, passwords and groups.
Basically I am trying to select a user from the array using a url ?user=username which will then return the user information and allow it to be changed. The problem I am having is to get the url to select the username in the array.
The array is basic:
$users = array(
'0' => array(
'username' => 'test',
'password' => 'test123',
'group' => 'office',
),
Like this?:
<?php
// get username from URL (GET METHOD)
$username=$_GET["username"];
// $users has all the info
foreach ($users as $u) {
// find the target user
if ($u["username"] == $username) {
// do something with $u
var_dump($u);
}
}
?>
Did you tried to do this:
$user_name = $users[0]["username"];
Try this (not tested)
$u = null;
foreach($user as $user) {
if(isset($_GET['user']) && $user['username'] == $_GET['user']) {
$u = $user;
}
}
$u variable should contains yours user record.
Since it's an array i assume you have multiple indexes. I guess a simple 'find' function might work.
function findUser($searchData, $users, $searchField) {
$retObj = array();
foreach ($users as $user) {
if (isset($user[$searchField]) && $user[$searchField] == $searchData) {
$retObj['username'] = $user['username'];
$retObj['password'] = $user['password'];
$retObj['group'] = $user['group'];
break;
}
}
return $retObj;
}
EDIT: Added searchField so u can do same for password and group. Searchdata is the value u are searching
I am having problems regarding the shared sessions once the users logged in simultaneously to the website. When the last user logs in, every users views the account of the last user, which is not appropriate (security issue I guess). All users must login to the same website and must show an output for a specific user only.
I am using PHP code. Does anyone also experienced these scenario? here's the code
function validate_login(){
$userName= trim((isset($_POST['username']) === TRUE ? $_POST['username'] : ''));
$userPass= trim((isset($_POST['userpass']) === TRUE ? $_POST['userpass'] : ''));
$userNameArray = explode("#", $userName);
$userName = $userNameArray[0];
$compLogin = ((isset($userNameArray[1]) === TRUE ? $userNameArray[1]: ''));
$KeepAlive = new KeepAlive();
if(isset($userNameArray[1])){
if(!$this->Login->checkattempt('admin')){
$loginArray = array(
'login' => $userName,
'comp_login_string' => $compLogin,
'pass' => $cryptography->encryptPassword($userPass)
);
$userCredentials = $this->Login->getLogin($loginArray);
if(!empty($userCredentials)){
$_SESSION['userCredentials'] = $userCredentials[0];
header('Content-Type: application/json');
$_SESSION['employee_user'] = '0';
$_SESSION['emp_id'] = '0';
$_SESSION['page']['client_ip_address'] = $KeepAlive->get_client_ip();
$_SESSION['page']['last_trans_time'] = time();
$this->Login->clear_attempt_log($_POST, 'admin');
echo json_encode(array('id' => $userCredentials[0]['id']));
}
} else {
array_shift($loginArray);
$this->Login->attempt_log($_POST, 'admin');
header('Content-Type: application/json');
echo json_encode(array('id' => '-1'));
}
} else {
echo json_encode(array('id' => '-2'));
}
}
function session_input()
{
$session_value = $this->input->post('welcome');
$this->session->set_userdata('name', $session_value);
echo "<a href='". base_url()."/index.php/contact/session_output'> go to </a>";
echo "your session has been save " ;
}
Is this correct?
Retrieving Session Data
Any piece of information from the session array is available using the following function:
$this->session->userdata('item');
Where item is the array index corresponding to the item you wish to fetch. For example, to fetch the session ID you will do this:
$session_id = $this->session->userdata('session_id');
Note: The function returns FALSE (boolean) if the item you are trying to access does not exist.
Adding Custom Session Data
$this->session->set_userdata($array);
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
yes correct
$session_value = $this->input->post('welcome');
if($this->session->set_userdata('name', $session_value)){
echo "your session has been save";
}
you can read more about it here ->
https://ellislab.com/codeigniter/user-guide/libraries/sessions.html
if its single value session:
$this->session->set_userdata('session_name', 'session_value');
if its multiple value session:
$array_name = array('value1','value2','value3');
$this->session->set_userdata('session_name',$array_name);
array along with key
$array_name = array('key_name1'=>'value1','key_name2'=>'value2','key_name3'=>'value3');
$this->session->set_userdata('session_name',$array_name);
to get the session value
$var = $this->session->userdata('session_name');
Site built on Code Igniter framework. I have two links (like and dislike). When you click the link, the correspond value increases or decreases. You can see the site: http://joke.guluzade.com/jokes/view/24
What I want: That user can change this value only once. I do it by cookies. For example, if user click to "like" link the value +5 became +6. Then if you click "dislike" the value must not change. User should have only one chance to like or dislike. Now it doesn't work correctly, if you click like you are able to click dislike too, but I want only change the lie or dislike value only one time.
How I do: I check if the cookie is set, function does nothing, if not it sets cookie and changes value. But if cookie set for like, when you click dislike it doesn't see that cookie.
Here is code:
function vote ($mm, $id){ //get the parameters (like or dislike and id)
$name = $mm;
$value = (int)$id;
$time = time()+3600;
if(isset($_COOKIE[$value])){
redirect($_SERVER['HTTP_REFERER']);
} else {
SetCookie($value, $name, $time);
if($name == "like"){
$this->db->select('like');
$this->db->where('id', $id);
$query = $this->db->get('jokes');
$data = $query->row_array();
$likes = $data['like'];
$likes++;
$dd = array();
$dd['like'] = $likes;
$this->db->where('id', $id);
$this->db->update('jokes', $dd);
redirect($_SERVER['HTTP_REFERER']);
} else {
$this->db->select('dislike');
$this->db->where('id', $id);
$query = $this->db->get('jokes');
$data = $query->row_array();
$likes = $data['dislike'];
$likes--;
$dd = array();
$dd['dislike'] = $likes;
$this->db->where('id', $id);
$this->db->update('jokes', $dd);
redirect($_SERVER['HTTP_REFERER']);
}
}
}
Can anybody say, what I do wrong?
use get_cookie('some_cookie') OR get_cookie('some_cookie',TRUE); instead of $cookie[$value].
moreover set cookie for full domain using
$cookie = array(
'name' => 'The Cookie Name',
'value' => 'The Value',
'expire' => '86500',
'domain' => '.some-domain.com',
'path' => '/',
);
set_cookie($cookie);
You can find the answer from following posts.
How can I set a cookie and then redirect in PHP?
http://www.tek-tips.com/viewthread.cfm?qid=1509045