I am trying to obtain items that are within my view input boxes.
I am using:
$email = $this->input->post('email', true);
In order to obtain the what is within the input box. But it is not obtaining anything.
The function is run with:
<?php $function = array('auth/start', $price);?>
<form action="<?php echo base_url($function);?>"method="post">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_xZrfWwuBmwBzUBynB96OgZhU"
data-amount=""
data-name="Turbine Engine"
data-description="Individual Membership"
data-image="/128x128.png">
</script>
</form>
I have the following:
Controller:
function start()
{
$username = 'a';
$price = '100';
$password = 'password';
$email = $this->input->post('email');
$end = date('Y-m-d', strtotime('+1 years'));
$additional_data = array(
'first_name' => $this->input->post('first_name'),
'middle_initial' => $this->input->post('middle_initial'),
'last_name' => $this->input->post('last_name'),
'company' => $this->input->post('company'),
'phone' => $this->input->post('phone'),
'biography' => $this->input->post('biography'),
'address' => $this->input->post('address'),
'city' => $this->input->post('city'),
'state' => $this->input->post('state'),
'zip' => $this->input->post('zip'),
'position' => $this->input->post('position'),
'country' => $this->input->post('country'),
'website' => $this->input->post('website'),
'listing' => 'N',
'type' => 'I',
'registration_end' => $end,
);
//load payment library
$this->load->library( 'stripe' );
// Get the credit card details submitted by the form
$token = $_POST['stripeToken'];
// Create the charge on Stripe's servers - this will charge the user's card
try {
//attempt to charge user
$this->stripe->charge_card( intval($price), $token, "Individual Membership" );
}
catch(Stripe_CardError $e)
{
// The card has been declined
}
//If passed then add a new user
//add the user
$this->ion_auth->register($username, $password, $email, $additional_data);
$this->session->set_flashdata('message', 'Payment Successful');
//TEST
//load parameters
$type = 'new account';
$date = date('Y-m-d');
date_default_timezone_set('Australia/Melbourne');
$time = date('h:i:s a', time());
//load the controller for adding activity
$this->load->library('../controllers/activity');
$this->activity->insert($email, $type, $date, $time);
//send to login
//$this->showView('login');
redirect("auth", 'refresh');
}
View:
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-default">
<div class="panel-body">
<!--Put Labels in order-->
<style>
label
{
display: inline-block;
width: 120px;
}
</style>
<h4>Individual Payment Page</h4>
<b>Make sure your email is correct</b>
<hr>
<p>
<?php echo form_label("Email:");?> <br />
<?php echo form_input(array('id' => 'email', 'name'=>'email','value'=>$email,'size'=>'30',
'readonly'=>'true'));?>
</p>
<!-- Make Hidden Labels to Pass the username and password-->
<p>
<?php echo form_input('username',$username);?>
<?php echo form_input('password',$password);?>
<?php echo form_input('first_name', $first_name);?>
<?php echo form_input('middle_initial',$middle_initial);?>
<?php echo form_input('last_name', $last_name);?>
<?php echo form_input('company', $company);?>
<?php echo form_input('phone', $phone);?>
<?php echo form_input('biography',$biography);?>
<?php echo form_input('address', $address);?>
<?php echo form_input('city', $city);?>
<?php echo form_input('state', $state);?>
<?php echo form_input('zip', $zip);?>
<?php echo form_input('position', $position);?>
<?php echo form_input('country', $country);?>
<?php echo form_input('website', $website);?>
</p>
<br>
<p>
<b>Click Below for Payment</b> <br>
</p>
<p><h4>1.) Regular Individual </h4><br>
<?php echo form_label("Price:");?> <br />
<?php echo form_input(array('name'=>'price','value'=>$price,'size'=>'30',
'readonly'=>'true'));?>
</p>
<?php $function = array('auth/start', $price);?>
<form action="<?php echo base_url($function);?>"method="post">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_xZrfWwuBmwBzUBynB96OgZhU"
data-amount=""
data-name="Turbine Engine"
data-description="Individual Membership"
data-image="/128x128.png">
</script>
</form>
<p><h4>2.) Regular Individual with Listing Enabled</h4><br>
<?php echo form_label("Price:");?> <br />
<?php echo form_input(array('name'=>'price_listing','value'=>$total,'size'=>'30',
'readonly'=>'true'));?>
</p>
<?php $function2 = array('auth/start_listing', $username, $password, $email, $first_name, $middle_initial, $last_name, $company, $phone, urldecode($address), $city, $state, $zip, urldecode($biography), $position, urldecode($country), urldecode($website), $total);?>
<form action="<?php echo base_url($function2);?>"method="post">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_xZrfWwuBmwBzUBynB96OgZhU"
data-amount=""
data-name="Turbine Engine"
data-description="Individual Membership"
data-image="/128x128.png">
</script>
</form>
</div>
</div>
</div>
</div>
</div>
Thank you. I appreciate any help.
In your view you have this:
//...
<?php echo form_input(array('id' => 'email', name'=>'email','value'=>$email,'size'=>'30', 'readonly'=>'true'));?>
//...
<form action="<?php echo base_url($function);?>"method="post">
// ...
</form>
But you didn't open the form before this input, so your inputs are not submitting, so open the form first like this:
echo form_open('url here');
echo form_input(array('id' => 'email', 'name'=>'email','value'=>$email,'size'=>'30', 'readonly'=>'true'));
//other inputs...
form_close();
The form_open opens/creates the opening form tag and form_close creates the closing form tag. You can also use <form> and </form> so put all your inputs inside the form before:
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button" ...></script>
Read more about Form Helper.
There is no any form_open() and form_close() in you input form. Please update your code this will solve your problem.
in order to post your text field you need to enclose it in a form tag
<input type="text" name="email" value="" />
<form action="someurl" method="post">
</form>
in this situation nothing will get posted to the server
if you need to post the text field you will need move it inside the form tags
<form action="someurl" method="post">
<input type="text" name="email" value="" />
</form>
or
form_open('someurl');
<?php echo form_label("Email:");?> <br />
<?php echo form_input(array('id' => 'email', name'=>'email','value'=>$email,'size'=>'30', 'readonly'=>'true'));?>
form_close();
make sure all the text filed are wraped inside a form
Related
Background info:
I have made a test form containing multiple pages. When recaptcha isn't intergrated I receive the info in my database. But when trying to integrate recaptcha (checkbox v2) it keeps failing and the info isn't sent to the database no more. I have tried to intergrate recaptcha on page2.php because it's the last page of the form the user has to fill in. I left my recaptcha keys in because it's just made as test.
Question:
How can I make it work? How can I integrate recaptch in a correct way?
Thanks!
The included pages are:
footer.php
<!-- Bootstrap Javascript-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script>function goBack() {window.history.back();}</script>
<!-- recaptcha -->
<script src='https://www.google.com/recaptcha/api.js'></script>
</body>
</html>
header.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('config.php');
require_once('functions.php');
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Multi-Page Form</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<!-- recaptcha -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container">
</div>
</nav>
index.php
<?php include_once('header.php'); ?>
<section id="form">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="form-container">
<h3 class="heading">Questionnaire</h3>
<p> Beste user,</p>
<p> Please fill in form A or B</p>
<br>
<p>Form A</p>
<br>
<p>Form B</p>
</div>
</div>
</div>
</div>
<section>
<?php include_once('footer.php'); ?>
page1.php
<?php include_once('header.php');?>
<section id="form">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="form-container">
<h3 class="heading">Step 1/2</h3>
<form action="page2.php" method="post">
<?php
echo "<br>";
email('Email', 'Email', '<b>Email</b>', ' ');
echo "<br>";
text('Firstname', 'Firstname', '<b>Firstname</b>', ' ');
echo "<br>";
?>
<br>
<br>
<center>
<div class="btn-group">
<button class="btn btn-dark" onclick="goBack()">« Go back</button>
<button class="btn btn-dark" type="reset" value="reset">Reset</button>
<button class="btn btn-dark" type="submit">Continue »</button>
</div>
</center>
</form>
</div>
</div>
</div>
</div>
<section>
<?php include_once('footer.php'); ?>
page2.php
<?php
include_once('header.php');
// Store data from page 1 in SESSION
if ( ! empty( $_POST ) ) {
$_SESSION['Email'] = $_POST['Email'];
$_SESSION['Firstname'] = $_POST['Firstname'];
}
// recaptcha
$public_key = "6LdojMIUAAAAAH8uQNeM8lW5pmP_T_NlWlb5_-9S";
$private_key = "6LdojMIUAAAAALhEfrQFR3jExbPLubKjys6CZL_9";
$url = "https://www.google.com/recaptcha/api/siteverify";
?>
<section id="form">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="form-container">
<h3 class="heading">Step 2/2</h3>
<form action="page3.php" method="post">
<?php
// choices for checkbox
$options = array(
'No ' => 'No ',
'Neutral ' => 'Neutral ',
'Yes ' => 'Yes ',
);
// choices for checkbox2
$options2 = array(
'Internet ' => 'Internet ',
'Friends ' => 'Friends ',
'Work ' => 'Work ',
'Other' => 'Other' ,
);
echo "<br>";
checkbox2( 'Info_media', 'Info_media', '<b>How do you know this?</b>', $options2 );
echo "<br>";
text_non_required('Other', 'Other', 'Explain "Other"?', ' ');
echo "<br>";
checkbox( 'Question_1', 'Question_1', '<b>Do you agree with the answer?</b>', $options );
echo "<br>";
text('Remark', 'Remark', 'Do you have remarks?', ' ');
?>
<br>
<br>
<center>
<!-- recaptcha -->
<div class="g-recaptcha" data-sitekey="<?php print $public_key; ?>"></div>
<br>
<div class="btn-group">
<button class="btn btn-dark" onclick="goBack()">« Go back</button>
<button class="btn btn-dark" type="reset" value="reset">Reset</button>
<button class="btn btn-dark" name="submit_form" type="submit">Continue »</button>
<!-- recaptcha -->
<?php
/* Check if the form has been submitted */
if(array_key_exists('submit_form',$_POST))
{
$response_key = $_POST['g-recaptcha-response'];
$response = file_get_contents($url.'?secret='.$private_key.'&response='.$response_key.'&remoteip='.$_SERVER['REMOTE_ADDR']);
/* json decode the response to an object */
$response = json_decode($response);
/* if success */
if($response->success == 1)
{
header("Location: http://localhost/recaptcha_test/page3.php");
}
else
{
echo "You are a robot.";
}
}
?>
</div>
</center>
</form>
</div>
</div>
</div>
</div>
<section>
<?php include_once('footer.php'); ?>
page3.php
<?php
include_once('header.php');
// Store data in session
if ( ! empty( $_POST ) ) {
$_SESSION['Info_media'] = $_POST['Info_media'];
$_SESSION['Other'] = $_POST['Other'];
$_SESSION['Question_1'] = $_POST['Question_1'];
$_SESSION['Remark'] = $_POST['Remark'];
}
?>
<section id="form">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="form-container">
<h3 class="heading">You are done.</h3>
<br>
<br>
<center>Thank you.</center>
<br>
<?php
whitelist_convert_send ();
?>
</div>
</div>
</div>
</div>
<section>
<?php include_once('footer.php'); ?>
functions.php
<?php
function __($text) {
return htmlspecialchars($text, ENT_COMPAT);
}
function checked($value, $array) {
if ( in_array( $value, $array ) ) {
echo 'checked="checked"';
}
}
function text( $name, $id, $label, $placeholder, $type = 'text' ) {?>
<div class="form-group">
<label for="<?php echo $id; ?>"><?php echo $label; ?></label>
<input type="<?php echo $type; ?>" required name="<?php echo $name; ?>" class="form-control"
id="<?php echo $id; ?>" placeholder="<?php echo $placeholder; ?>"
value="<?php echo isset($_SESSION[$name]) ? __($_SESSION[$name]) : ''; ?>">
</div>
<?php }
function text_non_required( $name, $id, $label, $placeholder, $type = 'text' ) {?>
<div class="form-group">
<label for="<?php echo $id; ?>"><?php echo $label; ?></label>
<input type="<?php echo $type; ?>" name="<?php echo $name; ?>" class="form-control"
id="<?php echo $id; ?>" placeholder="<?php echo $placeholder; ?>"
value="<?php echo isset($_SESSION[$name]) ? __($_SESSION[$name]) : ''; ?>">
</div>
<?php }
function email( $name, $id, $label, $placeholder, $type = 'email' ) {?>
<div class="form-group">
<label for="<?php echo $id; ?>"><?php echo $label; ?></label>
<input type="<?php echo $type; ?>" required name="<?php echo $name; ?>" class="form-control"
id="<?php echo $id; ?>" placeholder="<?php echo $placeholder; ?>"
value="<?php echo isset($_SESSION[$name]) ? __($_SESSION[$name]) : ''; ?>">
</div>
<?php }
function checkbox( $name, $id, $label, $options = array() ) {?>
<div class="form-group">
<p><?php echo $label; ?></p>
<?php foreach ($options as $value => $title ) : ?>
<label class="checkbox-inline" for="<?php echo $id; ?>">
<input type="radio" required name="<?php echo $name; ?>[]" value="<?php echo $value; ?>" <?php isset($_SESSION[$id]) ? checked($value, $_SESSION[$id]) : ''; ?>>
<span class="checkbox-title"><?php echo $title; ?></span>
</label>
<?php endforeach; ?>
</div>
<?php }
function checkbox2 ($name, $id, $label, $options2 = array() ) {?>
<div class="form-group">
<p><?php echo $label; ?></p>
<?php foreach ($options2 as $value => $title) :
?>
<label class="checkbox-inline" for="<?php echo $id; ?>">
<input type="radio" required name="<?php echo $name; ?>[]"
value="<?php echo $value; ?>"
<?php isset($_SESSION[$id]) ? checked($value, $_SESSION[$id]) : ''; ?>
>
<span class="checkbox-title"><?php echo $title; ?></span>
</label>
<?php endforeach; ?>
</div>
<?php
}
function whitelist_convert_send () {
//globalise variables
global $Email;
global $Firstname;
global $Info_media;
global $Other;
global $Question_1;
global $Remark;
global $MCQ_0;
global $MCQ_1;
// Whitelist
$Email = $_SESSION['Email'];
$Firstname = $_SESSION['Firstname'];
$Info_media = $_SESSION['Info_media'];
$Other = $_SESSION['Other'];
$Question_1 = $_SESSION['Question_1'];
$Remark = $_SESSION['Remark'];
// arrays to value in string for performing statistics
foreach ($Info_media as $value) {
$MCQ_0 = $value;}
foreach ($Question_1 as $value) {
$MCQ_1 = $value;}
// Connectie database (naam server, gebruikersnaam, wachtwoord, naam database)
$conn = new mysqli('localhost', 'root', '', 'Wolf');
/*Testing databaseconnection
if ($conn){
echo "we are connected";}
else {
die ('database connection failed');} */
if (!$conn){ die ('database connection failed' . msqli_error ());}
$stmt = $conn->prepare("INSERT INTO test_database (Email, Firstname, Info_media, Other, Question_1, Remark) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $Email, $Firstname, $MCQ_0, $Other, $MCQ_1, $Remark);
// Execute
$insert = $stmt->execute();
// Einde sessie
session_destroy();
}
You probably misunderstood how recaptcha is working.
You integrate the recaptcha code (js + div) in your form
On the result page you check if the captcha check was sucessful (php)
Currently you are doing both things in page2.php. When this page is loading, it checks if recaptcha was successful, but the recaptcha was not even included and the user didn't had the opportunity to solve it yet :-)
So you should integrate it in page1 and check it in page2.
page1.php
Integrate the recaptcha div in your form
<form action="page2.php" method="post">
<div class="g-recaptcha" data-sitekey="6LdojMIUAAAAAH8uQNeM8lW5pmP_T_NlWlb5_-9S"></div>
<?php
echo "<br>";
email('Email', 'Email', '<b>Email</b>', ' ');
...
ofc you can integrate the site key with php too (like you have done it on page2.php) or change the position inside the form
page2.php
Remove the recaptcha div from this page.
The recaptcha success check should be somewhere in the beginning of this page. You should render the whole form only when $response->success == 1 succeed (see the attached code). This probably requires some additional restructuring of page2.php
<?php
//recaptcha check
$response_key = "";
//get submitted recaptcha "user response" from last page
if(array_key_exists('g-recaptcha-response',$_POST)){
$response_key = $_POST['g-recaptcha-response'];
}
$response = file_get_contents($url.'?secret='.$private_key.'&response='.$response_key.'&remoteip='.$_SERVER['REMOTE_ADDR']);
/* json decode the response to an object */
$response = json_decode($response);
if($response->success == 1){
//render form from page 2
?>
<form action="page3.php" method="post">
...
<?php
}
else{
echo "You are a robot.";
//
}
?>
As an alternative you could integrate recaptcha in page2.php and check the result in page3.php - it just depends in which step you want the recaptcha checkbox
When I submit a form for the url example.com/index.php/topic/1/test-topic-test CodeIgniter does not recognize that a post form is submitted.
Routes:
$route["topic/(:num)/([a-z]+)"]["post"] = "forums/topic_post_reply/$1/$2";
Forums.php controller:
public function topic_post_reply($id, $name)
{
$message = $this->input->post("topic_reply_content");
if(!empty($message) && !empty($this->session->userdata('id')))
{
$data = [
"content" => $message,
"author" => $this->session->userdata('id'),
"reply_date" => time(),
"parent" => $id
];
$this->db->insert("forum_topics_replies", $data);
}
else
{
die("Something went wrong");
}
}
Form:
<form class="uk-form-stacked" action="<?php echo base_url(); ?>index.php/topic/<?php echo $this->uri->segment(2); ?>/<?php echo $this->forums_model->slug($this->uri->segment(3)); ?>" method="post">
<div class="uk-form-inline">
<textarea class="uk-textarea" name="topic_reply_content" rows="4" placeholder="Write a lovely reply..."></textarea>
</div>
<div class="laevis-reply-hidden">
<div class="uk-margin-small" style="margin-bottom:0">
<input type="submit" class="uk-button uk-button-primary uk-width-1-1" value="Post">
</div>
</div>
Why isn't this working?
I had to have the post route above all other routes for the same url or it would not work. I also had to change it to $route["topic/(:num)/:any"]["post"].
I'm querying the DB and sending sending a $data array from my controller to my view, where I'm using CI's form helper with set_value(field_name, default) but the data is not being loaded.
This is what I'm currently doing in my view:
<input type="hidden" id="artist-id" name="record_artist_id" value="<?php echo set_value('record_artist_id', $record_artist_id); ?>">
I thought I had to use the input helper so I tried:
<label for="record-name"><span class="required">*</span>Name:</label>
<?php
echo form_input([
'type' => 'text',
'name' => 'record_name',
'id' => 'record-name' ,
'class' => 'form-control',
'value' => set_value('record_name')
]);
?>
But still not working.
This is working though:
<input id="record-name" name="record_name" type="text" value="<?php echo (isset($record_name)) ? $record_name : ''; ?>" class="form-control">
The form helper is being loaded in autoload.php
$autoload['helper'] = array('url', 'file', 'form', 'base');
I don't know if this is related but I'm getting the view as a string and then passing it to a template, something like:
public function add_content($view, $content = NULL){
$this->content = $this->load->view($view, $content, TRUE);
return $this->content;
}
and later on in a different method:
// render content
$this->load->view('partials/content', ['content' => $this->content]);
Any idea about what I am doing wrong?
Try This
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
error_reporting(1);
class Welcome extends CI_Controller {
public function index()
{
$this->load->view('welcome_message');
}
public function test()
{
$this->load->helper('form','url');
$this->load->library("form_validation");
// echo "vijay";
$post=$this->input->post();
if($post)
{
// echo "<pre>";print_r($post);die;
$this->form_validation->set_rules('record_name', 'Record Name', 'trim|required');
$this->form_validation->set_rules('quantity', 'quantity Name', 'trim|required|numeric');
if($this->form_validation->run()==true)
{
redirect('/');
return 0;
}
}
$data['message']= validation_errors();
$this->load->view('test',$data);
}
}
View
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to CodeIgniter</title>
</head>
<body>
<div id="container">
<h1>Welcome to CodeIgniter!</h1>
<div id="body">
</div>
<p>
<?= !empty($message) ? $message : '' ?>
</p>
<form method="post">
<label for="record-name"><span class="required">*</span>Name:</label>
<?php
$record_name_input = array('type' => 'text',
'name' => 'record_name',
'id' => 'record-name',
'class' => 'form-control',
'value' => set_value('record_name')
);
echo form_input($record_name_input);
?>
<h5>Username</h5>
<input type="text" name="quantity" value="<?php echo set_value('quantity', '0'); ?>" size="50" />
<?php
echo form_submit("submit", "submit data");
?>
</form>
</div>
</body>
</html>
Until you won't use $this->form_validation->run() til that set_value('field_name') won't work
I have a code that submits data into a cake json 'database', but when I submit using PHP. When I reload the page, the file repeats the code of the last object in the JSON file when I get it. How do I avoid this?
This is my PHP
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error = "<label class='text-danger'>Enter Name</label>";
}
else if(empty($_POST["type"]))
{
$error = "<label class='text-danger'>Enter Type</label>";
}
else if(empty($_POST["diff"]))
{
$error = "<label class='text-danger'>Enter Difficulty</label>";
}
else
{
if(file_exists('../../databases/cakes.json'))
{
$current_data = file_get_contents('../../databases/cakes.json');
$array_data = json_decode($current_data, true);
$extra = array(
'person' => array(
'name' => $_POST['name'],
'difficulty' => $_POST["diff"],
'type' => $_POST["type"],
'isNew' => 'true',
'isVeg' => 'false',
)
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('../../databases/cakes.json', $final_data))
{
//.-.
}
}
else
{
$error = 'JSON File not exits';
}
}
}
?>
<body>
<div id="layout"></div>
<div id="content">
<div id="add">
<div class="form-title"><h1>Add Cake</h1></div>
<form method="post">
<?php
if(isset($error))
{
echo $error;
}
?>
<br />
<div class="input-field">
<label for="name">Cake Name</label>
<input type="text" name="name"/>
</div>
<br />
<div class="input-field">
<label for="diff">Difficulty</label>
<div class="select">
<select name="diff" id="slct">
<option>Choose an option</option>
<option value="male">EZ</option>
<option value="female">Meh</option>
<option value="matthew">Mildy Hard</option>
</select>
</div>
</div>
<br />
<div class="input-field">
<label for="type">Type</label>
<input type="text" name="type"/><br />
Need Suggestions?<br>
</div>
<input class="addCake" type="submit" name="submit" value="Add Cake!"/><br />
See some other cakes
<?php
if(isset($message))
{
echo $message;
}
?>
</form>
Submission Works.
Result:
[[{"cake":{"name":"tes1","diff":"EZ","type":"Deli","isNew":"true","isVeg":"false"}}]]
But when I reload the page I see two of this things...
Result:
[[{"cake":{"name":"tes1","diff":"EZ","type":"Deli","isNew":"true","isVeg":"false"},{"name":"tes1","diff":"EZ","type":"Deli","isNew":"true","isVeg":"false"}}]]
Use ($_SERVER['REQUEST_METHOD'] == 'POST') instead of ($_POST["submit"])
$array_data = array_merge($array_data, $extra); instead of $array_data[] = $extra;
I am using Ben Edmunds Ion Auth Library.
I am having a problem with any function that uses the csrf_nonce methods - it is failing the check on post.
I have checked that the flashdata is getting set (I can see it in the form as a hidden input [edit_user for example]), but when you submit the form the flashdata check is failing.
I am using the database for the session if that makes any difference.
Code snippets;
Controller
function edit_user($id) {
$this->data['title'] = "Edit User";
if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
redirect('auth', 'refresh');
} //!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()
$user = $this->ion_auth->user($id)->row();
$groups = $this->ion_auth->groups()->result_array();
$currentGroups = $this->ion_auth->get_users_groups($id)->result();
//process the phone number
if (isset($user->phone) && !empty($user->phone)) {
$user->phone = explode('-', $user->phone);
} //isset($user->phone) && !empty($user->phone)
//validate form input
$this->form_validation->set_rules('first_name', $this->lang->line('edit_user_validation_fname_label'), 'required|xss_clean');
$this->form_validation->set_rules('last_name', $this->lang->line('edit_user_validation_lname_label'), 'required|xss_clean');
$this->form_validation->set_rules('email', $this->lang->line('create_user_validation_email_label'), 'required|valid_email');
$this->form_validation->set_rules('company', $this->lang->line('edit_user_validation_company_label'), 'required|xss_clean');
$this->form_validation->set_rules('groups', $this->lang->line('edit_user_validation_groups_label'), 'xss_clean');
if (isset($_POST) && !empty($_POST)) {
// do we have a valid request?
if ($id != $this->input->post('id')) {
show_error($this->lang->line('error_csrf'));
} //$this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id')
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'company' => $this->input->post('company'),
'email' => $this->input->post('email')
);
//Update the groups user belongs to
$groupData = $this->input->post('groups');
if (isset($groupData) && !empty($groupData)) {
$this->ion_auth->remove_from_group('', $id);
foreach ($groupData as $grp) {
$this->ion_auth->add_to_group($grp, $id);
} //$groupData as $grp
} //isset($groupData) && !empty($groupData)
//update the password if it was posted
if ($this->input->post('password')) {
$this->form_validation->set_rules('password', $this->lang->line('edit_user_validation_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
$this->form_validation->set_rules('password_confirm', $this->lang->line('edit_user_validation_password_confirm_label'), 'required');
$data['password'] = $this->input->post('password');
} //$this->input->post('password')
if ($this->form_validation->run() === TRUE) {
$check = $this->ion_auth->update($user->id, $data);
if (FALSE == $check) {
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect("auth/edit-user/$id", 'refresh');
} else {
//check to see if we are creating the user
//redirect them back to the admin page
$this->session->set_flashdata('message', "User Saved");
redirect("auth/users", 'refresh');
}
} //$this->form_validation->run() === TRUE
} //isset($_POST) && !empty($_POST)
//display the edit user form
$this->data['csrf'] = $this->_get_csrf_nonce();
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
//pass the user to the view
$this->data['user'] = $user;
$this->data['groups'] = $groups;
$this->data['currentGroups'] = $currentGroups;
$this->data['first_name'] = array(
'name' => 'first_name',
'id' => 'first_name',
'type' => 'text',
'value' => $this->form_validation->set_value('first_name', $user->first_name)
);
$this->data['last_name'] = array(
'name' => 'last_name',
'id' => 'last_name',
'type' => 'text',
'value' => $this->form_validation->set_value('last_name', $user->last_name)
);
$this->data['company'] = array(
'name' => 'company',
'id' => 'company',
'type' => 'text',
'value' => $this->form_validation->set_value('company', $user->company)
);
$this->data['email'] = array(
'name' => 'email',
'id' => 'email',
'type' => 'email',
'value' => $this->form_validation->set_value('email', $user->email)
);
$this->data['password'] = array(
'name' => 'password',
'id' => 'password',
'type' => 'password'
);
$this->data['password_confirm'] = array(
'name' => 'password_confirm',
'id' => 'password_confirm',
'type' => 'password'
);
$this->_render_page('auth/admin/users/update', $this->data);
}
function _get_csrf_nonce() {
$this->load->helper('string');
$key = random_string('alnum', 8);
$value = random_string('alnum', 20);
$this->session->set_flashdata('csrfkey', $key);
$this->session->set_flashdata('csrfvalue', $value);
return array(
$key => $value
);
}
function _valid_csrf_nonce() {
if ($this->input->post($this->session->flashdata('csrfkey')) !== FALSE &&
$this->input->post($this->session->flashdata('csrfkey')) == $this->session->flashdata('csrfvalue')) {
return TRUE;
} //$this->input->post($this->session->flashdata('csrfkey')) !== FALSE && $this->input->post($this->session->flashdata('csrfkey')) == $this->session->flashdata('csrfvalue')
else {
return FALSE;
}
}
View;
<h1><?php echo lang('edit_user_heading');?></h1>
<p><?php echo lang('edit_user_subheading');?></p>
<!--<div id="infoMessage" class="info"><?php echo $message;?></div>-->
<?php
if (isset($message)) {
?>
<div id="infoMessage" class="alert alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
<h4>Message</h4>
<?php echo $message;?>
</div>
<?php
}
?>
<?php echo form_open(uri_string(), 'class="form-horizontal"'); ?>
<div class="control-group <?php echo form_error_class('first_name') ?>">
<label class="control-label" for="first_name">
<?php echo lang('edit_user_fname_label'); ?>
</label>
<div class="controls">
<input type="text"
id="first_name"
name="first_name"
placeholder="<?php echo lang('edit_user_fname_label'); ?>"
value="<?php echo set_value('first_name', $first_name['value']); ?>"
class="error"/>
<?php echo form_error('first_name'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('last_name') ?>">
<label class="control-label" for="last_name">
<?php echo lang('edit_user_lname_label'); ?>
</label>
<div class="controls">
<input type="text"
id="last_name"
name="last_name"
placeholder="<?php echo lang('edit_user_lname_label'); ?>"
value="<?php echo set_value('last_name', $last_name['value']); ?>"
class="error"/>
<?php echo form_error('last_name'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('company') ?>">
<label class="control-label" for="company">
<?php echo lang('edit_user_company_label'); ?>
</label>
<div class="controls">
<input type="text"
id="company"
name="company"
placeholder="<?php echo lang('edit_user_company_label'); ?>"
value="<?php echo set_value('company', $company['value']); ?>"
class="error"/>
<?php echo form_error('company'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('email') ?>">
<label class="control-label" for="email">
<?php echo lang('edit_user_email_label'); ?>
</label>
<div class="controls">
<input type="text"
id="email"
name="email"
placeholder="<?php echo lang('edit_user_email_label'); ?>"
value="<?php echo set_value('email', $email['value']); ?>"
class="error"/>
<?php echo form_error('email'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('password') ?>">
<label class="control-label" for="password">
<?php echo lang('edit_user_password_label'); ?>
</label>
<div class="controls">
<input type="password"
id="password"
name="password"
placeholder="<?php echo lang('edit_user_password_label'); ?>"
value="<?php echo set_value('password'); ?>"
class="error"/>
<?php echo form_error('password'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('password_confirm') ?>">
<label class="control-label" for="password_confirm">
<?php echo lang('edit_user_password_confirm_label'); ?>
</label>
<div class="controls">
<input type="password"
id="password_confirm"
name="password_confirm"
placeholder="<?php echo lang('edit_user_password_confirm_label'); ?>"
value=""
class="error"/>
<?php echo form_error('password_confirm'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('groups') ?>">
<div class="controls <?php echo form_error_class('groups') ?>">
<h3><?php echo lang('edit_user_groups_heading');?></h3>
<?php
foreach ($groups as $group) {
?>
<label class="checkbox">
<?php
$gID=$group['id'];
$checked = null;
$item = null;
foreach($currentGroups as $grp) {
if ($gID == $grp->id) {
$checked= ' checked="checked"';
break;
}
}
?>
<input type="checkbox" name="groups[]" value="<?php echo $group['id'];?>"<?php echo $checked;?>>
<?php echo $group['name'];?>
</label>
<?php
}
?>
</div>
</div>
<?php echo form_hidden('id', $user->id);?>
<?php echo form_hidden($csrf); ?>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn btn-success" value="<?php echo lang('edit_user_submit_btn'); ?>" />
</div>
</div>
<?php echo form_close();?>
First check
$this->session->set_flashdata('message',
$this->ion_auth->errors()
);
having set value
I have found the solution (or this fix works just for me).
I changed the session driver in the config to use native sessions from cookie.
Line 284 of config.php => $config['sess_driver'] = 'native';
Golden rule: never trust CI sessions!
Some notions about FLASHDATA
CSRF and Flashdata:
FLASHDATA will only be available for the NEXT server request, and are then automatically cleared!
e.g.:
AJAX calls function_1, which sends CSRF key/value back to function_1_success
function_1_success sets hidden input fields for CSFR key and value
and enables function_2, which compares POST variables with flashdata
this is how it works (with or without AJAX, that was just an example).
How it doesn't work: if you create a php function which does
$this->session->set_flashdata('item', 'value') and then try to read with echo $this->session->flashdata('item') you will get an empty string, only after a refresh of this function,your flashdata values show