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), '/');
Related
if(isset($_POST["cartDelete"])){
$item_ID = $_POST["hidden_id"];
$cookie_data = stripslashes($_COOKIE['shopping_cart']);
$cart_data = json_decode($cookie_data, true);
unset($cart_data[$item_ID]);
$item_data = json_encode($cart_data);
setcookie('shopping_cart', $item_data, time() + (86400 * 30));
header("Location: cart");
print_r($cart_data);
}
if(isset($_POST["QTYedited"])){
$item_ID = $_POST["hidden_id"];
$item_QTY = $_POST["QTYedited"];
$cookie_data = stripslashes($_COOKIE['shopping_cart']);
$cart_data = json_decode($cookie_data, true);
$cart_data[$item_ID]["item_QTY"] = $item_QTY;
$item_data = json_encode($cart_data);
setcookie('shopping_cart', $item_data, time() + (86400 * 30));
header("Location: cart");
}
I'm writing an webshop in php, but in this part the cookie somehow won't be saved. The whole fun is, with one item in the cart everything is working. The problem beginning with at least two items.
I've tried everything I knew. You can test the page with webshop.abrisx.nhely.hu
First, make sure that the cookie is enabled in your browser and note that some illegal characters will cause the cookie not to be stored,
Try calling urlencode() on your string before sending it to the cookie.
ex:
setcookie('shopping_cart', urlencode($item_data), time() + (86400 * 30), '/');
I think this will solve your problem.
I am trying to set array, but it is not getting set. Everytime the Buy function called, the array gets declared.
This is the function is controller.
public function buy() {
if($this->session->userdata('counter')){
$counter = $this->session->userdata('counter');
$this->session->set_userdata('counter', $counter + 1);
} else {
$this->session->set_userdata('counter', 1);
}
if(isset($bought)){
$name = $this->input->post('name');
$price = $this->input->post('price');
$qty = $this->input->post('qty');
$product = array('name' => $name, 'price' => $price, 'qty'=> $qty);
array_push($bought, $product);
var_dump($bought);
die();
} else {
$bought = array();
redirect("");
}
As you can see, it should remember that $bought is set, but it gets declared anew. For now I
tried to make it global, before "public function __construct()",
tried "if (!empty),
tried to put into session,
tried to find the answer across whole stackoverflow...
Please let me know if additional info needed.
Thanks a lot!
In your code when you are checking for $bought, it is not present so it is going to the else part everytime. Instead define a blank array and then set the values inside it. Try with -
if(isset($_SESSION['bought'])){
$name = $this->input->post('name');
$price = $this->input->post('price');
$qty = $this->input->post('qty');
$product = array('name' => $name, 'price' => $price, 'qty'=> $qty);
array_push($_SESSION['bought'], $product);
var_dump($_SESSION['bought']);
die();
} else {
$_SESSION['bought'] = array();
}
And start the session at top of the page.
I got it working.
I made a workaround with sgt's help, so now my code looks like this:
if($this->session->userdata('bought')){
$name = $this->input->post('name');
$price = $this->input->post('price');
$qty = $this->input->post('qty');
$product = array('name' => $name, 'price' => $price, 'qty'=> $qty);
// please see that here I just returned from old one and added new data to the old one.
// Then I just added the result to the session.
$old_session = $this->session->userdata('bought');
array_push($old_session, $product);
$this->session->set_userdata('bought', $old_session);
redirect("");
} else {
$this->session->set_userdata('bought', array());
}
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');
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
}
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