Check if POST data was sent to page - php

I am trying to check if POST data has been sent to a page. A quick Google search turned up nothing.
if(postdataisSent)
{
//do this
}
else
$items = Gamefarm::where('roost_hen', '=', 1)->paginate(6);
return View::make('gamefarms/index',compact('items'));

You can use if ( Input::has('parameter') ) to check for the existence of a certain parameter in the POST, or you can pass a default into the function, and then test if it's there.
$parameter = Input::get('parameter', false);
if ($parameter)
{
// do something with the data
}
else
{
// it's not present in the POST
}
To check for the presence of any data at all:
$data = Input::all();
if (count($data) > 0)
{
// there is data in the POST
}
else
{
// there is no data in the POST
}
Note - You can access the data from any HTTP verb (GET, POST etc) using the same Input::get('data')

Related

Not receiving URL variables in controller with GET, codeigniter

I'm not receiving variables in my controller from a URL from Paypal indicating a successful transaction. They appear in the URL fine but my controller is not receiving them for some odd reason. I think the code is absolutely correct. What could be the reason?
Example:
Received URL: http://example.com/Paypal/success?tx=8FA47070HF454623K&st=Completed&amt=20%2e00&cc=USD&cm=&item_number=
Controller, PHP:
function success(){
//get the transaction data
$paypalInfo = $this->input->get();
$data['item_number'] = $paypalInfo["item_number"];
$data['txn_id'] = $paypalInfo["tx"];
$data['payment_amt'] = $paypalInfo["amt"];
$data['currency_code'] = $paypalInfo["cc"];
$data['status'] = $paypalInfo["st"];
//pass the transaction data to view
$this->load->view('paypal/success', $data);
}
I get this result for all variables:
Looks like item_number is not set. Performing a GET on it can cause an error.
You are using a class function to obtain the $_GET items.
Within the function $this->input->get() you should check if the var is available (if(isset($_GET[..]))) and otherwise return a default, so you don't run into these problems.
On the other hand, it seems that you don't submit a item_number to Pay Pal. May also be a problem for processing your order later on in the script and backtracing it to the original...
---- ALSO SEE ANSWER BELOW ----
Paypal sends POST vars...
Remember Paypal not send data via URL, So you couldn't receive data via GET method. You should try this
$paypalInfo = $this->input->post();
instead what you are using now. If it not works then use following
$paypalInfo = $_POST;
it will must work
Just processing $_POST gives you a huge security risk! Also for $_GET. Change $_POST to $_GET below to use $_GET in stead of $_POST.
I would suggest at least the following;
foreach ($_POST as $key->$value)
{
$cleankey = addslashes($key);
$paypalInfo[$cleankey] = addslashes($value);
}
Then;
$req_keys = array(
'item_number' => 'item_number',
'txn_id' => 'tx',
'payment_amt' => 'amt',
'currency_code' => 'cc',
'status' => 'st',
);
$data = array();
$error = array();
foreach($req_keys as $req_data_key=>$req_paypalinfo_key )
{
if(isset($paypalInfo[$req_paypalinfo_key]))
{
$data[$req_data_key] = $paypalInfo[$req_paypalinfo_key];
}
else
{
$error[] = "missing POST data:".$req_paypalinfo_key;
}
}
if(count($error) > 0)
{
var_dump($error);
}
else
{
$this->load->view('paypal/success', $data);
}
This will give you insight if your required info is there and also gives you some protection against SQL injection.

cakephp can't update table with set

I have a problem with updating database table in cakephp...
So I have a profile page where the logged in user can see and update his personal information. Here is my solution for it (yes I know it's not the best...)
if($this->request->is('post')) {
$data = $this->request->data['user-profile'];
// $uid = $this->Session->read("WebUser.id");
$uid = 1;
$user_data = $this->WebUser->find('first', array('conditions'=>array('id'=>$uid)));
$updated_fields = '';
foreach($data as $key => $value) {
if($key != 'state'){
if(empty($value)) {
$this->Session->setFlash("Please fill in all the required fields");
return;
}
}
if($user_data['WebUser'][$key] != $value) {
if($key == 'email') {
$mail_check = $this->WebUser->find('first', array('conditions'=>array('email'=>$value, 'id !='=>$uid)));
if($mail_check) {
$this->Session->setFlash("This e-mail is already registered");
return;
}
}
$updated_fields .= "'".$key."'=>'".$value."',";
}
}
if($updated_fields != '') {
$updated_fields .= "'modified'=>'".date("Y-m-d H:i:s")."'";
$this->WebUser->read(null, $uid);
$this->WebUser->set(array('first_name'=>'John','modified'=>'2014-12-30 10:53:00'));
if($this->WebUser->save()) {
$this->printr($this->data);
$this->WebUser->save();
$this->Session->setFlash("Success : Profile data is now modified", array("class"=>"success_msg"));
} else {
$this->Session->setFlash("Error : Data modifying isn't complete. Please try again!");
}
}
return;
}
So this code fetches the user info from the database and looks for those fields which are edited on profile page. Problem is when I want to save the data it give me back false and didn't save it... Does someone have a solution for this?
Try putting
$this->WebUser->validationErrors;
in else part and check whether there are any validation errors or not.
Like this:
if($this->WebUser->save()) {
$this->printr($this->data);
$this->WebUser->save();
$this->Session->setFlash("Success : Profile data is now modified", array("class"=>"success_msg"));
} else {
echo "<pre>";print_r($this->WebUser->validationErrors);die();
$this->Session->setFlash("Error : Data modifying isn't complete. Please try agin!");
}
Did you tried to set id directly?
$this->WebUser->id = $uid;
Also, CakePHP is automatically update modified field in your table after any transactions. So you don't have to set it directly (but you can if you want any other date value).
About validation. I recommend you to read about Data Validation in CakePHP, because that validation is not good, it's can be handled by models.
Also. You can get any validation errors from models using Model::$validationErrors.
debug($this->Recipe->validationErrors);
The problem with this code was that didn't wanted to save the posted data ( debug($this->WebUser->save) has give me back false). At the end I didn't found the solution why this code not worked but the conclusion is that you never need to use more users table than one. So now I have a Users and Groups tables, and different type of users are connected to their groups(Admin, User, ...).

Calling functions from within functions (with arguments) in PHP

I’m building a system that captures info from a POST method and adds them into a PHP $_SESSION. The basic logic I want to follow is:
Check the method and call the relevant function
Check if $_SESSION data already exists via a function
Check if the $post_id variable is already in the $_SESSION's array via a function
Based on the outcomes on these functions, add to the array, create a new array, or do nothing
Here is the code I have written to handle this logic so far. I am looking to get just the add_to_lightbox() function working first, and will move onto the other two after.
session_start();
// set variables for the two things collected from the form
$post_id = $_POST['id'];
$method = $_POST['method'];
// set variable for our session data array: 'ids'
$session = $_SESSION['ids'];
if ($method == 'add') {
// add method
add_to_lightbox($post_id, $session);
} elseif ($method == 'remove') {
// remove method
remove_from_lightbox($post_id);
} else ($method == 'clear') {
// clear method
clear_lightbox();
}
function session_exists($session) {
if (array_key_exists('ids',$_SESSION) && !empty($session)) {
return true;
// the session exists
} else {
return false;
// the session does not exist
}
}
function variable_exists($post_id, $session) {
if (in_array($post_id, $session)) {
// we have the id in the array
return true;
} else {
// we don't have the id in the arary
return false;
}
}
function add_to_lightbox($post_id, $session) {
if (!session_exists($session) == true && variable_exists($post_id, $session) == false) {
// add the id to the array
array_push($session, $post_id);
var_dump($session);
} else {
// create a new array with our id in it
$session = [$post_id];
var_dump($session);
}
}
It's stuck in a state where it's always getting to add_to_lightbox() and following the array_push($session, $post_id); each time. I’m unsure whether this code I’ve written is possible because of the nested functions, and how I can refactor it to get the functionality working.
Correction from before, seems like $session is an array of ids..
The problem you are having is that you're modifying the local copy of that array within add_to_lightbox function. You don't need to specifically instantiate the variable as an array, you can just use the following.
$_SESSION['ids'][] = $post_id;

Using flashdata while posting same controller twice in Codeigniter

I am trying to submit a EDIT form which edits Users Academics Details,
These Details have unique id in DB and my Code in Short Looks like below :
class edit extends ci_controller
{
function user_academics($id = NULL)
{
if(isset($id) == FALSE) //if link is ./edit/user_academics
{
$id = NULL;
$link = site_url('profile');
show_error("Invalid Page Request! <a href='$link' Go to Profile </a>");
}
$user_id = $this->session->userdata('user_id');
$data['fill'] = $this->edit_model->get_user_academics($id);
if($user_id != $data['fill']['user_id']) // check if logged in user is accessing his record or others
{
$link = site_url('profile');
show_error("This is an Invalid Request ! <a href='$link'>Go to Profile </a>");
}
else // actual work starts here
{
$this->session->set_flashdata('ua_id',$id); // update_academics will get this data
$this->load->view('edit/edit_3_view',$data);
}
}
function update_academics()
{
$ua_id = $this->session->flashdata('ua_id'); // flash data used here .
if( !$ua_id )
{
show_error('Sorry, This request is not valid!');
}
$academics = array(
// All post values
);
$this->edit_model->update_user_academics($academics,$ua_id);
//print_r($academics);
redirect('profile');
}
}
Now the problem is
- If I open two different records to edit, then It will set only one Session Flash value.
- And No matter what I edit , the existing values of the last flash value gets updated.
Please Suggest me another way or Correct me if I am wrong in above code . Thanks
save that flashdata in array, like:
$myArr = array('value 1', 'value 1');
//set it
$this->session->set_flashdata('some_name', $myArr);
And in view:
$dataArrs = $this->session->flashdata('some_name');
//loop thru $dataArrs to show the flashdata
Flash data is simply like variable which is available only in next request, you can bypass this behavior by using two different keys with record id in it, so that when you use flash data for showing message you can access key with particular record id.

Validation Parameter Get Method in fuelphp

i have a problem when i want to validate using GET Method in fuelphp
i'm looking up in this documentation
// run validation on just post
if ($val->run())
{
// process your stuff when validation succeeds
}
else
{
// validation failed
}
that's code only validate if the method is Post or default post.
how to validate method get?
To run the validation against an array:
if ($val->run( array( $validation_rule => $value_to_validate) ))
{
// process your stuff when validation succeeds
}
else
{
// validation failed
}
Example:
$val = Validation::factory();
$val->add('email')->add_rule('valid_email');
if ($val->run( array('email'=>$email) ))
{
// $email is valid
}
else
{
// $email is not valid
}

Categories