unable to set session for multidimensional array in php opencart - php

I have the following opencart function to add product in session
Consider this as my $bean_sku and $product_id
$bean_id = 'werwer-23423s-sd-01';
$product_id = 120;
public function add($product_id, $bean_sku, $qty = 1, $option = array()) {
if (!$option) {
$key = (int)$product_id;
} else {
$key = (int)$product_id . ':' . base64_encode(serialize($option));
}
if ((int)$qty && ((int)$qty > 0)) {
if (!isset($this->session->data['cart'][[$bean_sku][$key]])) { echo 'not set';
$this->session->data['cart'][[$bean_sku][$key]] = (int)$qty;
} else { echo 'session set';
$this->session->data['cart'][[$bean_sku][$key]] += (int)$qty;
}
}
echo $this->session->cart;
exit;
$this->data = array();
}
In the above function I have added $bean_sku But I am unable to set the session. Each time when I run getting not set.

Try as
$this->session->data['cart'][$bean_sku.$key] = (int)$qty;

Try
$this->session->data['cart'][$bean_sku][$key]
instead of
$this->session->data['cart'][[$bean_sku][$key]]

Related

Sending POST data from Symfony into Yii controller

I have Yii2 project. And there I also have api written by Symfony.
In Symfony part I have method in the class which send request to Yii controller.
$buzz = $this->container->get('buzz');
$buzz->getClient()->setVerifyHost(false);
$buzz->getClient()->setVerifyPeer(false);
$buzz->getClient()->setTimeOut(false);
$url = $this->container->getParameter('integra_sync_prices');
$sendResult = $buzz->post($url, array('authorization' => $this->container->getParameter('load_token')), array('products' =>
json_encode($productPrices)));
$resultJson = json_decode($sendResult->getContent(), true);
if (isset($resultJson['error']))
throw new \Exception('Site: '.$resultJson['error'], 500);
class IntegraController extends Controller{
public function actionIndex()
{
Yii::$app->response->format = Response::FORMAT_JSON;
$headers = Yii::$app->request->getHeaders();
foreach ($headers as $key => $value) {
if(strtolower(trim($key)) == 'authorization') {
$token = trim($value[0]);
break;
}
}
$products = json_decode(Yii::$app->request->post('products'));
$post_products = Yii::$app->request->post('products');
if('111' == $token) {
if(isset($post_products) && $products) {
foreach ($products as $product) {
echo $product->price." = ".$product->productId."<br>";
Yii::$app->db->createCommand("UPDATE oc_product SET quantity = '" . (int)$product->quantity . "', price = '" . (float)$product->price . "' WHERE product_id = '" . (int)$product->productId . "'")->execute();
}
$json['success'] = 'complete';
} else {
$json['error'] = 'empty data';
}
} else {
$json['error'] = 'authorization error';
}
Yii::$app->controller->enableCsrfValidation = false;
echo json_encode($json);
}
I expect that data in my database will be updated by this controller. But there in nothing changes.
What do I do wrong? Maybe I should send some another headers? Thanks a lot )

How do I modify an existing file to add the ability to unlink a specific file from a folder?

Thank you StackOverflow experts for looking at my question.
First, It is possible this question has been asked before but my situation is a bit unique. So, please hear me out.
When our users want to edit an existing record, they would also like to have the ability to delete an existing pdf file if one exists before adding a new one.
To display an existing file, I use this code.
<td class="td_input_form">
<?php
// if the BidIDFile is empty,
if(empty($result["BidIDFile"]))
{
//then show file upload field for Bid File
echo '<input type="file" name="BidIDFile[]" size="50">';
}
else
{
// Bid file already upload, show checkbox to delete it.
echo '<input type="checkbox" name="delete[]" value="'.$result["BidIDFile"].'"> (delete)
'.$result["BidIDFile"].'';
}
</td>
Then to delete this file, I use the following code:
// Connect to SQL Server database
include("connections/Connect.php");
// Connect to SQL Server database
include("connections/Connect.php");
$strsID = isset($_GET["Id"]) ? $_GET["Id"] : null;
if(isset($_POST['delete']))
{
// whilelisted table columns
$fileColumnsInTable = array( 'BidIDFile', 'TabSheet', 'SignInSheet', 'XConnect',
'Addend1', 'Addend2','Addend3','Addend4','Addend5', 'Addend6');
$fileColumns = array();
foreach ($_POST['delete'] as $fileColumn)
{
if(in_array($fileColumn, $fileColumnsInTable))
$fileColumns[] = $fileColumn;
}
// get the file paths for each file to be deleted
$stmts = "SELECT " . implode(', ', $fileColumns) . " FROM bids WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
$files = sqlsrv_fetch_array($querys,SQLSRV_FETCH_ROW);
// loop over the files returned by the query
foreach ($files as $file )
{
//delete file
unlink($file);
}
// now remove the values from the table
$stmts = "UPDATE bids SET " . impload(' = '', ', $fields) . " WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
This works fine. However, the edit file points to an existing file with an INSERT and UPDATE operation in this one file (great thanks to rasclatt) and I am having problem integrating the two together.
Can someone please help with integrating the two files into one?
Thanks in advance for your assistance.
Here is the INSERT and UPDATE file:
<?php
error_reporting(E_ALL);
class ProcessBid
{
public $data;
public $statement;
public $where_vals;
protected $keyname;
protected $conn;
public function __construct($conn = false)
{
$this->conn = $conn;
}
public function SaveData($request = array(),$skip = false,$keyname = 'post')
{
$this->keyname = $keyname;
$this->data[$this->keyname] = $this->FilterRequest($request,$skip);
return $this;
}
public function FilterRequest($request = array(), $skip = false)
{
// See how many post variables are being sent
if(count($request) > 0) {
// Loop through post
foreach($request as $key => $value) {
// Use the skip
if($skip == false || (is_array($skip) && !in_array($key,$skip))) {
// Create insert values
$vals['vals'][] = "'".ms_escape_string($value)."'";
// Create insert columns
$vals['cols'][] = "".str_replace("txt","",$key)."";
// For good measure, create an update string
$vals['update'][] = "".str_replace("txt","",$key)."".' = '."'".ms_escape_string($value)."'";
// For modern day binding, you can use this array
$vals['bind']['cols'][] = "".$key."";
$vals['bind']['cols_bind'][] = ":".$key;
$vals['bind']['vals'][":".$key] = $value;
$vals['bind']['update'][] = "".$key.' = :'.$key;
}
}
}
return (isset($vals))? $vals:false;
}
public function AddFiles($name = 'item')
{
// If the files array has been set
if(isset($_FILES[$name]['name']) && !empty($_FILES[$name]['name'])) {
// Remove empties
$_FILES[$name]['name'] = array_filter($_FILES[$name]['name']);
$_FILES[$name]['type'] = array_filter($_FILES[$name]['type']);
$_FILES[$name]['size'] = array_filter($_FILES[$name]['size']);
$_FILES[$name]['tmp_name'] = array_filter($_FILES[$name]['tmp_name']);
// we need to differentiate our type array names
$use_name = ($name == 'item')? 'Addend':$name;
// To start at Addendum1, create an $a value of 1
$a = 1;
if(!empty($_FILES[$name]['tmp_name'])) {
foreach($_FILES[$name]['name'] as $i => $value ) {
$file_name = ms_escape_string($_FILES[$name]['name'][$i]);
$file_size = $_FILES[$name]['size'][$i];
$file_tmp = $_FILES[$name]['tmp_name'][$i];
$file_type = $_FILES[$name]['type'][$i];
if(move_uploaded_file($_FILES[$name]['tmp_name'][$i], $this->target.$file_name)) {
// Format the key values for addendum
if($name == 'item')
$arr[$use_name.$a] = $file_name;
// Format the key values for others
else
$arr[$use_name] = $file_name;
$sql = $this->FilterRequest($arr);
// Auto increment the $a value
$a++;
}
}
}
}
if(isset($sql) && (isset($i) && $i == (count($_FILES[$name]['tmp_name'])-1)))
$this->data[$name] = $sql;
return $this;
}
public function SaveFolder($target = '../uploads/')
{
$this->target = $target;
// Makes the folder if not already made.
if(!is_dir($this->target))
mkdir($this->target,0755,true);
return $this;
}
public function where($array = array())
{
$this->where_vals = NULL;
if(is_array($array) && !empty($array)) {
foreach($array as $key => $value) {
$this->where_vals[] = $key." = '".ms_escape_string($value)."'";
}
}
return $this;
}
public function UpdateQuery()
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$update[] = implode(",",$arr['update']);
}
}
$vars = (isset($update) && is_array($update))? implode(",",$update):"";
// Check that both columns and values are set
$this->statement = (isset($update) && !empty($update))? "update bids set ".implode(",",$update):false;
if(isset($this->where_vals) && !empty($this->where_vals)) {
$this->statement .= " where ".implode(" and ",$this->where_vals);
}
return $this;
}
public function SelectQuery($select = "*",$table = 'bids')
{
$stmt = (is_array($select) && !empty($select))? implode(",",$select):$select;
$this->statement = "select ".$stmt." from ".$table;
return $this;
}
public function InsertQuery($table = 'bids')
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
$this->statement = "insert into ".$table;
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$insert['cols'][] = implode(",",$arr['cols']);
$insert['vals'][] = implode(",",$arr['vals']);
}
}
$this->statement .= '(';
$this->statement .= (isset($insert['cols']) && is_array($insert['cols']))? implode(",",$insert['cols']):"";
$this->statement .= ") VALUES (";
$this->statement .= (isset($insert['vals']) && is_array($insert['vals']))? implode(",",$insert['vals']):"";
$this->statement .= ")";
return $this;
}
}
include("../Connections/Connect.php");
function render_error($settings = array("title"=>"Failed","body"=>"Sorry, your submission failed. Please go back and fill out all required information."))
{ ?>
<h2><?php echo (isset($settings['title']))? $settings['title']:"Error"; ?></h2>
<p><?php echo (isset($settings['body']))? $settings['body']:"An unknown error occurred."; ?></p>
<?php
}
// this function is used to sanitize code against sql injection attack.
function ms_escape_string($data)
{
if(!isset($data) || empty($data))
return "";
if(is_numeric($data))
return $data;
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
$non_displayables[] = '/[\x00-\x08]/'; // 00-08
$non_displayables[] = '/\x0b/'; // 11
$non_displayables[] = '/\x0c/'; // 12
$non_displayables[] = '/[\x0e-\x1f]/'; // 14-31
foreach($non_displayables as $regex)
$data = preg_replace($regex,'',$data);
$data = str_replace("'","''",$data);
return $data;
}
// New bid save engine is required for both sql statement generations
$BidSet = new ProcessBid($conn);
$strId = null;
if(isset($_POST["Id"]))
{
$strId = $_POST["Id"];
//echo $strId;
}
If ($strId == "") {
//echo "This is an insert statement";
// This will generate an insert query
$insert = $BidSet->SaveData($_POST)
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->InsertQuery()
->statement;
// Check that statement is not empty
if($insert != false) {
sqlsrv_query($conn,$insert);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to Solicitation screen'));
$err = false;
}
//echo '<pre>';
//print_r($insert);
// echo '</pre>';
}
else
{
//echo "This is an update statement";
// This will generate an update query
$update = $BidSet->SaveData($_POST,array("Id"))
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->where(array("Id"=>$_POST["Id"]))
->UpdateQuery()
->statement;
//echo '<pre>';
//print_r($update);
//echo '</pre>';
// Check that statement is not empty
if($update != false) {
sqlsrv_query($conn,$update);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to admin screen'));
$err = false;
}
}
// This will post an error if the query fails
if((isset($err) && $err == true) || !isset($err))
render_error(); ?>

Wordpress Shortcode not passing variable from function (Newbie)

Here is the snippet of code in question:
function hoursearned_func($user) {
$key = 'Service Hours Earned';
if(isset($user[$key])) {
$result = $user[$key];
}
return "Service Hours Earned: ".$result." Hours";
}
add_shortcode('hoursearned', 'hoursearned_func');
This small function simply returns the value of an array given the key, but when calling the shortcode, [hoursearned], it only displays:
Service Hours Earned: Hours
rather than:
Service Hours Earned: 200 Hours
Where 200 is a string that is returned by the function hoursearned_func given $user.
For some reason Wordpress is not passing the returned variables from the functions to the shortcodes. How can I get Wordpress to show the result from the function?
Here is the full code if that helps... (note that all of this is being loaded as a plugin)
//Dump CSV file (SalesForce Report) to php array to be parsed..
add_action('dump_csv_array', 'dump_csv_array', 10);
function dump_csv_array(){
$data = array();
$header = NULL;
if (($file = fopen('http://blah.com/info.csv', 'r')) !==FALSE) { //The link to the CSV is insignificant
while (($row = fgetcsv($file, 1000, ",")) !==FALSE) {
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($file);
}
return $data;
}
$multiarray = (array) dump_csv_array();
global $current_user;
get_currentuserinfo();
$user_email = $current_user->user_email;
//Parses the multidimensional array of Dumped CSV info. Looks up the current user's email and returns a single array of the current user's SalesForce information.
function parse_array($multiarray, $user_email){
$array = (array) $multiarray;
$email = $user_email;
if(is_user_logged_in() === true ) {
foreach($array as $subarray) {
if(isset($subarray['Email']) && $subarray['Email'] == $email) {
$data = $subarray;
}
}
}
else {
return NULL;
}
return $data;
}
$user = parse_array($multiarray, $user_email);
//Defines Shortcodes and their Functions
function hoursearned_func($user) {
$key = 'Service Hours Earned';
if(isset($user[$key])) {
$result = $user[$key];
}
return "Service Hours Earned: ".$result." Hours";
}
function hoursawarded_func($user) {
$key = 'Service Hours Awarded';
if(isset($user[$key])) {
$result = $user[$key];
}
return "Service Hours Awarded: ".$result." Hours";
}
function rank_func($user) {
$key = 'Rank';
if(isset($user[$key])) {
$result = $user[$key];
}
return "Rank: ".$result;
}
function memstatus_func($user) {
$key = 'Membership Status';
if(isset($user[$key])) {
$result = $user[$key];
}
return "Status: ".$result;
}
function register($atts) {
add_shortcode( 'hoursearned', 'hoursearned_func');
add_shortcode( 'hoursawarded', 'servicehours_func');
add_shortcode( 'rank', 'rank_func');
add_shortcode( 'memstatus', 'memstatus_func');
}
add_action('init', 'register');
var_dump(hoursearned_func($user));
Try to create a shortcode with attributes, (or) retrieve the $user data inside the shortcode's function and set them as default values.
function example_func($atts) {
$user = get_user_array(); //Retrieve the data
$atts = shortcode_atts($user, $atts);
return 'example: ' . $atts['foo'] . ' ' . $atts['bar'];
}
add_shortcode('example', 'example_func');
Have a look at the Shortcode API it basically explains everything.

Storing array in sessions

I am trying to store some data as an array in the session but the function does not seem to be working.it does not throw any error but every time i add data to it, it just overwrites the previous data. I am using yii and here is the action
public function actionStoreProducts($name)
{
$name=trim(strip_tags($name));
if(!empty($name))
{
if(!isset(Yii::app()->session['_products']))
{
Yii::app()->session['_products']=array($name);
echo 'added';
}
else
{
$myProducts = Yii::app()->session['_products'];
$myProducts[] = $name;
Yii::app()->session['products'] = $myProducts;
echo 'added';
}
}
Can anyone suggest me how can i achieve the desired result?
Please correct your code like this .
public function actionStoreProducts($name) {
$name = trim(strip_tags($name));
if (!empty($name)) {
if (!isset(Yii::app()->session['_products'])) {
Yii::app()->session['_products'] = array($name);
echo 'added';
} else {
$myProducts = Yii::app()->session['_products'];
$myProducts[] = $name;
Yii::app()->session['_products'] = $myProducts;
echo print_r(Yii::app()->session['_products']);
echo 'added';
}
}
}
session property read-only
i think the correct aproach is :
function actionStoreProducts($name) {
$session = new CHttpSession; //add this line
$session->open(); //add this line
$name = trim(strip_tags($name));
if (!empty($name)) {
if (!isset(Yii::app()->session['_products'])) {
$session->add('_products', array($name)); //replace this line
echo 'added';
} else {
$myProducts = Yii::app()->session['_products'];
$myProducts[] = $name;
$session->add('_products', $myProducts); //replace this line
echo 'added';
}
}
}
first get an variable into $session['somevalue'] ,then sore in array variable, Use Like IT:-
$session = new CHttpSession;
$session->open();
$myval = $session['somevalue'];
$myval[] = $_POST['level'];
$session['somevalue'] = $myval;

Checking a cookie in a PHP script

Hey i still need a little bit of help with the rating system but i have a problem checking if the cookie exist this is
<?php
$rating = new ratings($_POST['widget_id']);
isset($_POST['fetch']) ? $rating->get_ratings() : $rating->vote();
class ratings {
var $data_file = './ratings.data.txt';
private $widget_id;
private $data = array();
function __construct($wid) {
$this->widget_id = $wid;
$all = file_get_contents($this->data_file);
if($all) {
$this->data = unserialize($all);
}
}
public function get_ratings() {
if($this->data[$this->widget_id]) {
echo json_encode($this->data[$this->widget_id]);
}
else {
$data['widget_id'] = $this->widget_id;
$data['number_votes'] = 0;
$data['total_points'] = 0;
$data['dec_avg'] = 0;
$data['whole_avg'] = 0;
echo json_encode($data);
}
}
public function vote() {
# Get the value of the vote
preg_match('/star_([1-5]{1})/', $_POST['clicked_on'], $match);
$vote = $match[1];
$ID = $this->widget_id;
# Update the record if it exists
# doesn't update if it already exists
if (!isset($_COOKIE[$id])) {
if($this->data[$ID]) {
$this->data[$ID]['number_votes'] += 1;
$this->data[$ID]['total_points'] += $vote;
}
# Create a new one if it doesn't
else {
$this->data[$ID]['number_votes'] = 1;
$this->data[$ID]['total_points'] = $vote;
}
$this->data[$ID]['dec_avg'] = round( $this->data[$ID]['total_points'] / $this->data[$ID]['number_votes'], 1 );
$this->data[$ID]['whole_avg'] = round( $this->data[$ID]['dec_avg'] );
file_put_contents($this->data_file, serialize($this->data));
$this->get_ratings();
}
} //ends if isset
# ---
# end class
}
?>
The part that should check if the cookie exist is this:
if (!isset($_COOKIE[$id])) {
but for some reason nothing in the script works when i add that.
if (!isset($_COOKIE[$id])) {
You declared everything as $ID, but you're using $id. Try switching that out and see if it works.
if (!isset($_COOKIE[$ID])) {
i think what you wanted to do is isset (if exist) intead of !isset (if doesn t exist)
if (isset($_COOKIE[$id])) {

Categories