PHP response true / false and correct IF statemen - php

In add to cart function can be placed discount, discounts are made via xxx-hashid. i figure out that problem is when user want cheat and type random xxx-123456 my system crash.
hashid is from Ivan Akimov.
is possible to achiev, when hashID (userID) doesnt exist function return code isnt valid but without crash ?
public function getIdByHash($hashid) {
$response = ['valid' => false];
if ($hashid){
$response['valid'] = true;
$hashid = explode("PMX-",$hashid)[1];
$hashids = new Hashids("",6);
return $hashids->decode($hashid)[0];
}
if ($hashid){
$response ['valid'] = false;
return $hashids = "PMX-"."dGRLrb";
}
}

You could try :
public function getIdByHash($hashid) {
$response = ['valid' => false];
if ($hashid){
$response['valid'] = true;
try {
$hashid = explode("PMX-",$hashid)[1];
$hashids = new Hashids("",6);
return $hashids->decode($hashid)[0];
} catch(\Exception $e) {
$response ['valid'] = false;
}
}
return $hashids = "PMX-"."dGRLrb";
}

Related

php redis insert a data at a same time with few queues error

There are 3 queues in redis.
If I insert a data at a same time with different browsers, both requests are accepted.
I get 2 duplicated records. Any helps?
For example, the first request is on the 1st queue.
At the second request, 2nd queue is searched for finding the data.
But the data doesn't exist in the queue.
The second request is inserted on the queue.
Is it understandable?
public function save($evt_no, $type = "redis") {
$name = '';
$res = true;
try{
$headers = getallheaders();
$bodys = $_REQUEST;
$session = $_SESSION;
foreach ($_FILES as $fileKey=>$fileVal) {
if ($fileVal['error'] == 0) {
try {
$uploaded_row = $this->fileL->upload('queueEventParticipant', $fileKey, array() ,'queue');
} catch (\Exception $ex) {
throw $ex;
}
$bodys['file'][_return_numeric($fileKey)] = $uploaded_row;
}
}
$data = array(
'header' => $headers,
'body' => $bodys,
'session' => $session
);
$data['body']['evt_no'] = $evt_no;
$data = json_encode($data);
if($type == "redis"){
$name = $this->attendQueueRedisService->setNewRsvp($data);
} else {
throw new \Exception("No exist");
}
} catch (\Exception $ex){
log_message("error", $ex->getMessage());
throw $ex;
}
if($res){
return $name;
} else {
return "Error";
}
}
class AttendQueueRedisService extends CI_Model {
private $redisClient;
private $redisConfig;
const PREFIX_DONE = 'done_';
const PREFIX_ERROR = 'error_';
public function __construct() {
parent::__construct();
if ($this->load->config('redis', true, true)) {
$this->redisConfig = $this->config->config['redis'];
}
$this->redisClient = new Redis();
$this->redisClient->connect($this->redisConfig['hostname'], $this->redisConfig['port']);
$this->redisClient->auth($this->redisConfig['auth']);
$this->redisClient->select($this->redisConfig['queue']);
}
public function setNewRsvp($data) {
$key = uniqid('rsvp_'.gethostname().'_',true).':redis';
$this->redisClient->set($key, $data, 60 * 30);
return $key;
}
}

Symfony- passing post params returns the same

I defined my postParams where I want to pass "hash" value from db.
What I am trying to accomplish is that if hash exists in my Session table to return TRUE and if not to return FLASE.
Problem is my code always returns TRUE.
What I am missing?
$postData = $this->requirePostParams(['hash']);
$this->container->get('app')->formService(
$this->data['hash']
);
if ($postData['hash']) {
$hash = $this->get('app')->getSessionRepository()->find($this->data['hash']);
if (!$hash) return false;
} else {
return true;
}
And my requirePostParams works fine! (tested on other functions)
protected function requirePostParams($params) {
$currentRequest = $this->get('request_stack')->getCurrentRequest();
$postData = $currentRequest->request->all();
$postContent = json_decode($currentRequest->getContent(), true);
if(!empty($postContent)) $postData = $postContent;
$this->data = $postData;
$missingParams = [];
foreach ($params as $param) {
if (!array_key_exists($param, $postData)) {
$missingParams[] = $param;
}
}
}
And my service:
$findHash = $this->getSessionRepository()->findOneBy([
'hash' => $hash
]);
As xmike mentioned in comments, function requirePostParams returns nothing. That's why $postData['hash'] is never set.
Try to replace $postData['hash'] with $this->data['hash']:
$this->requirePostParams(['hash']);
$this->container->get('app')->formService(
$this->data['hash']
);
if ($this->data['hash']) {
$hash = $this->get('app')->getSessionRepository()->find($this->data['hash']);
if (!$hash) return false;
} else {
return true;
}

How to update or insert new data on codeigniter

I'm setting up a rest-API on my server, and I want to update a table (i.e "comp_holding_stock"). but every time I test to post new data it returns "No item found"
Here is my controller
public function create_comp_holding_stock(){
$returnArr['status'] = '0';
$returnArr['response'] = '';
try {
if (!$this->input->post()) {
$returnArr['response'] = "Only POST method is allowed";
} else {
$holding_stock_data = array(
'comp_id' => $this->input->post('comp_id'),
'customer_id' => $this->input->post('customer_id'),
'quantity' => $this->input->post('quantity'),
'date' => date('Y-m-d H:i:s')
);
if (!isset($holding_stock_data)) {
$returnArr['response'] = "Some Parameters are missing";
} else {
$customer = $this->Customer->save_holding_stock($holding_stock_data);
if (!$customer) {
$returnArr['response'] = 'No items found';
} else {
$returnArr['status'] = '1';
$returnArr['response'] = $customer;
}
}
}
} catch (Exception $ex) {
$returnArr['response'] = "Error in connection";
$returnArr['error'] = $ex->getMessage();
}
$response = json_encode($returnArr, JSON_PRETTY_PRINT);
echo $response;
}
And here is my model below
public function save_holding_stock($holding_stock_data)
{
// $this->db->trans_start();
$success = $this->db->insert('comp_holding_stock', $holding_stock_data);
return $success;;
}
what am i doing wrong? what is the best approach to this scenarios
I would recommend try to check if you have load model in your controller.
And in your model try to do this.
public function save_holding_stock($holding_stock_data, $comp_id=FALSE)
{
if(!$comp_id == -1 || !$this->exists($comp_id))
{
if($this->db->insert('comp_holding_stock', $holding_stock_data))
{
$holding_stock_data['comp_id'] = $this->db->insert_id();
return TRUE;
}
return FALSE;
}
$this->db->where('comp_id', $comp_id);
return $this->db->update('comp_holding_stock', $holding_stock_data);
}
Try these changes in your code
In your controller,
$customer = $this->Customer->save_holding_stock($holding_stock_data);
$save_status = $this->db->affected_rows();
if ($save_status>0) {
$returnArr['status'] = '1';
$returnArr['response'] = $customer;
} else {
$returnArr['response'] = 'No items found';
}
In your model,
public function save_holding_stock($holding_stock_data)
{
// $this->db->trans_start();
$this->db->insert('comp_holding_stock', $holding_stock_data);
}

Array to string conversion Error in Laravel 4.2

I was working in one Laravel Project using 92Five App. when access user List. its goto Something Went Wrong Page. Its Display Array to string conversion Error in Error Log.
In User Controller Following Functions are Defined.
Error :
[2016-08-09 13:13:12] log.ERROR: Something Went Wrong in User
Repository - getAllUsersData():Array to string conversion [] []
My Code :
public function getAllUsersData()
{
try{
$users = array();
$tempUsers = \User::all()->toArray();
$users = $this->getGroupBaseRole($tempUsers);
return $users;
}
catch (\Exception $e)
{
\Log::error('Something Went Wrong in User Repository - getAllUsersData():'. $e->getMessage());
throw new SomeThingWentWrongException();
}
}
public function getGroupBaseRole($groupMembersInfo) {
$data = [];
if(!empty($groupMembersInfo) && isset($groupMembersInfo)) {
foreach($groupMembersInfo as $user)
{
$banned = false;
$suspended = false;
$loginAttempt = 0;
$usersThrottle = \Throttle::where('user_id',$user['id'])->get()->toArray();
// print_r($usersThrottle); exit;
if(sizeof($usersThrottle) != 0)
{
foreach($usersThrottle as $userThrottle)
{
if($userThrottle['banned'] == true)
{
$banned = true;
}
if($userThrottle['suspended'] == true)
{
$suspended = true;
}
$loginAttempt = $loginAttempt + $userThrottle['attempts'];
}
$user['banned'] = $banned;
$user['suspended'] = $suspended;
$user['loginAttempt'] = $loginAttempt;
}
else
{
$user['banned'] = false;
$user['suspended'] = false;
$user['loginAttempt'] = 0;
}
$groupUser = \Sentry::findUserById($user['id']);
$groups = $groupUser->getGroups()->toArray();
if(sizeof($groups)!=0)
{
$user['role'] =$groups[0]['name'];
}
else
{
$user['role'] = '';
}
$data[] = $user;
}
}
return $data;
}
It seeems getGroupBaseRole() method accepts string, but you're trying to pass an array $tempUsers as first argument.

Password automatically changed on DB while update personal details usin cake PHP

if i update any of this personal details filed then i click on save it. its save the new data and change my login password also to random value
public function update_personal_details() {
$this->layout = null ;
$this->autoRender = false;
$response = array('success' => true);
if ($this->request->isPost()) {
if($this->User->exists($this->Auth->user('id'))) {
try {
$this->User->read(null, $this->Auth->user('id'));
$this->User->set('first_name',$this->request->data["first_name"]);
$this->User->set('last_name',$this->request->data["last_name"]);
$this->User->set('mobile',$this->request->data["mobile"]);
$this->User->set('city',$this->request->data["city"]);
$this->User->save();
} catch (exception $ex) {
$response['success'] = false;
}
}
}
return json_encode($response);
}
To make sure that cakePHP only updates the wanted cols you can pass the data and a field list on the save command:
Model::save(array $data = null, boolean $validate = true, array $fieldList = array())
Just have a look at Cookbook Save your Data
For you this should work:
$data = array();
$data['first_name'] = $this->request->data["first_name"]);
$data['last_name'] = $this->request->data["last_name"]);
$data['mobile'] = $this->request->data["mobile"]);
$data['city'] = $this->request->data["city"]);
$this->User->save(array('User' => $data), true, array('first_name', 'last_name', 'mobile', 'city'));
Hope that helps

Categories