How to get posted value from different function? - php

I am using codeigniter 3.1 .
How to return or get posted email after submit data from different function?
HTML
<form action="settings/valid" class="form-horizontal" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="email" name="email" value="<?php echo $email ?>" />
<input type="submit"/>
</form>
PHP
public function index() {
// how to get post email ?
$email = $this->input->post("email"));
$this->template->loadContent("settings/index.php", array(
"email" => $email
)
);
}
public function valid() {
$email = $this->input->post("email"));
$this->user->add($this->user->ID, array(
"email" => $email
));
redirect(site_url("index.php"));
}

This may answer your question better.
public function index() {
// how to get post email ?
$email = $this->session->flashdata("email");
$this->template->loadContent("settings/index.php", array(
"email" => $email
)
);
}
public function valid() {
$email = $this->input->post("email"));
$this->user->add($this->user->ID, array(
"email" => $email
));
$this->session->set_flashdata("email",$email);
redirect(site_url("index.php"));
}

What you are doing is called routing. That means that it makes no sense to get the email in index, because no data has been sent to index. What you can do is redirect the user to index and pass a post argument to index.
To put it another way. Let's say you open a web page and give it your name. You cannot expect another page to know your name as well, because that page does not exist yet (it has not been generated yet by php).
But you can send the user to another page and tell that page the user's name.
For instance, in your case:
in valid()
redirect(site_url("index.php?email=".$email));
and in index()
$email = $this->input->get("email")

Related

MVC PHP - html submit name not found in controller

Alright so i have in my views a index that has a input type submit like so
<input type="submit" name="submit" value="Submit">
When using the controller like so (to tests if it works)
public function indexAction()
{
$message = 'not submited';
if(isset($_POST['submit']) === TRUE){
$message = 'submited';
}
$this->view->setVars([
'message' => $message
]);
}
and calling the variable message in my html with echo $message i get not submited, what am i missing here ?
just erase " === TRUE"
just try this:
if (isset($_POST['submt'])).
And make sure that ur form method is set to "POST" and action to "#"

Implementing standard PHP form validation within a Slim application

So I’m trying to implement php server side validation for a registration form. I’m using the slim framework along with twig templates to display the html. I’ve been trying to use this example to achieve this but I think the way I have set up my slim routing is interfering with error messages displaying properly on the registration form.
The way my application works currently is that a user navigates to the registration form page which presents the registration form. This is is shown here:
$app->get('/register', function(Request $request, Response $response)
{
return $this->view->render($response,
'register.html.twig',
[
'css_path' => CSS_PATH,
'landing_page' => $_SERVER["SCRIPT_NAME"],
'action_register' => './register/success',
//'initial_input_box_value' => null,
'page_title' => 'Login App - Register',
]);
})->setName('register');
The 'action_register' => './register/success', represents the form ‘action’ attribute in the html twig form and indicates where and how the form data is processed and the response to the submitted form. This can be seen here: (note that the first few lines of the register/success page is the example used from the guide i’ve been using for php validation)
$app->post('/register/success', function(Request $request, Response $response) use ($app)
{
$nameError = " ";
if(isset($_POST['submit']))
{
if (empty($_POST["username"])) {
$nameError = "Name is required";
} else {
$name = test_input($_POST["username"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameError = "Only letters and white space allowed";
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$arr_tainted_params = $request->getParsedBody();
$sanitizer_validator = $this->get('validate_sanitize');
$password_hasher = $this->get('hash_password');
$tainted_email = $arr_tainted_params['email'];
$tainted_username = $arr_tainted_params['username'];
$tainted_password = $arr_tainted_params['password'];
$model = $this->get('model');
$sql_wrapper = $this->get('sql_wrapper');
$sql_queries = $this->get('sql_queries');
$db_handle = $this->get('dbase');
$cleaned_email = $sanitizer_validator->validate_email($tainted_email);
$cleaned_username = $sanitizer_validator->validate_username($tainted_username);
$cleaned_password = $sanitizer_validator->validate_password($tainted_password);
$hashed_cleaned_password = $password_hasher->hash_password($cleaned_password);
$model->set_user_values($cleaned_username, $cleaned_email, $hashed_cleaned_password);
$model->set_sql_wrapper($sql_wrapper);
$model->set_sql_queries($sql_queries);
$model->set_db_handle($db_handle);
if ($sanitizer_validator->get_validate_messages() == ' ')
{
$model->store_user_details();
$_SESSION["loggedin"] = true;
$_SESSION["username"] = $cleaned_username;
$arr_storage_result_message = '';
echo $sanitizer_validator->get_validate_messages(); //this will be turned into a proper alert prompt at a later date
}
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true)
{
return $this->view->render($response,
'display_user.html.twig',
[
'css_path' => CSS_PATH,
'landing_page' => $_SERVER["SCRIPT_NAME"],
//'action_register' => 'index.php/register',
//'initial_input_box_value' => null,
'page_title' => 'Login App - Display',
'username' => $cleaned_username,
'hashed_password' => $cleaned_password,
]);
}
});
The idea is that the user creates an account and is then logged in whereby the 'display_user.html.twig', is displayed. Otherwise error messages regarding form validation should be displayed on the registration form itself. However the registration form is only displayed on the /register page. But the registration form posts the data and processes it on the registration/success page.
So I’m not sure if the php validation guide code is in the wrong place or that my slim routing is incorrect for this purpose of form validation. I think the problem lies in the fact that when the form is submitted it redirects trhe user to a new page namely register/success.
In summary i’m trying to implement php form validation such as this within a slim application using twig templates.
I’ll also include the register.html.twig page of the registration form if that helps:
{% extends 'header_footer.html.twig'%}
{% block content %}
<h3>Register A New Account</h3>
<form method = "post" action = " {{ action_register }} ">
<p>Email: <input type="text" name="email" ><br></p>
<p>Username: <input type="text" name="username" ><br></p>
<span class="error">* <?php echo $nameError;?></span> //code used in the php validation guide
<p>Password: <input type="text" name="password" ><br></p>
<!--<p>Password Confirm: <input type="text" name="password_confirm"><br></p> THIS WILL BE IMPLEMENTED LATER-->
<input type="submit" value="Create Account">
</form>
{% endblock %}
You can't use PHP in Twig like that.
Take a look at these:
Slim-Flash
slim-twig-flash
Slim-Validation
With Flash and Slim-Validation you can achieve your desired error messages.
If you don't want to use the above components then you could simply pass your $nameError variable to the template:
PHP:
return $this->view->render($response,
'display_user.html.twig',
[
'nameError' => $nameError, // HERE
'css_path' => CSS_PATH,
'landing_page' => $_SERVER["SCRIPT_NAME"],
//'action_register' => 'index.php/register',
//'initial_input_box_value' => null,
'page_title' => 'Login App - Display',
'username' => $cleaned_username,
'hashed_password' => $cleaned_password,
]
);
Twig:
{% if nameError %}<span class="error">* {{ nameError }}</span>{% endif %}

form in codeigniter not posting

I am creating a form in codeignitor and every time I try to submit something the page does nothing in chrome or in firefox gives me this message:
The address wasn't understood
Firefox doesn't know how to open this address, because one of the
following protocols (localhost) isn't associated with any program or
is not allowed in this context.
You might need to install other software to open this address.
In internet explorer it trys to find an application to open the page.
I can access the same address directly but it won't let me do it when I submit the form.
this is the code for the form:
<?php
$hidden = array('account_id' => '1');
echo form_open('post', '', $hidden);
?>
<label for="post">Post:</label>
<input type="text" name="post" id="post"/>
<br/>
<input type="submit" value="post" />
</form>
This is the post controller:
<?php
class Post extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('posts_model');
$this->load->helper('url_helper');
$this->load->helper('form');
}
function index() {
$data['title'] = "posted";
$this->posts_model->add_post();
$this->load->view('templates/header', $data);
$this->load->view('comment/index', $data);
$this->load->view('templates/footer');
}
}
?>
This is the function in the posts_model:
function add_post() {
$data = array('person_acc_id' => $this-> input -> post('account_id'),
'post' => $this -> input -> post('post'),
'deleted' => 0,
'edited' => 0,
'post_time' => date('Y-m-d H:i:s', time()));
$this -> db -> insert('post', $data);
}
Actually you didn't set any method to form. Means your form action is Wrong.
In your function index() you call the view. So Then its load from in that. So if I click form submit <form> come to POST Controller. So it again execute function index() again. This will run like loop til you fix it.
So what you have to do is.
In controller Create new method to receive data
public function validate_form()
{
#your Form validate Code goes here
}
In view <form> should be
echo form_open('post/validate_form', '', $hidden);
this will act like
<form method="post" accept-charset="utf-8" action="http:/example.com/index.php/post/validate_form" account_id="1" />
To Know about Form Validation
Just check your config.php in application/config, then change your link like this:
$config['base_url'] = 'http://localhost/yourApp/';
I guess your value before is like this:
$config['base_url'] = 'localhost/yourApp/';
My code was actually fine. Once I put it on a real server it works. It would not work with localhost.

PHP Codeigniter ; Preventing form resubmit

I am creating a search page in my CodeIgniter project.
On submit, the form calls the controller function, data is fetched via model function and the resulting array is passed to the view
The problem is that when I refresh the result page the form is resubmitting because the $_POST data is still there in the request headers.
How can I avoid that resubmit confirmation message
Following is the code for my form :
<!--form-->
<form id="find" action="<?php echo base_url()?>search/find" method="post">
<input type="text" name="search_key" class="tb4" id="search_key" placeholder="Search here"/>
<input type="button" value="search"/>
</form>
Following is the code for my controller:
/*
* function for fetching search results
* #param void
* #return void
*/
public function find()
{
$data['search_result']=$this->search_model->search($this->input->post('search_key'));
$this->load->view('template/header');
$this->load->view('pages/search_result',$data);
$this->load->view('template/footer');
}
Kindly help me with this.I can't use redirect instead of loading the view since I am bound to pass the result array $data to the view.
Try redirect to itself
public function find()
{
$data['search_result']=$this->search_model->search($this->input->post('search_key'));
if($this->input->post('search_key')) {
redirect('yourcontroller/find');
}
$this->load->view('template/header');
$this->load->view('pages/search_result',$data);
$this->load->view('template/footer');
}
Simple solution is to have a hidden timestamp field in the form.
<?php echo form_hidden( 'TS', time() ); ?>
When the form is processed, save this timestamp in the session,
$this->session->set_userdata( 'form_TS', $this->input->post( 'TS' ) );
Before processing the form check that two timestamps doesn't match
if ( $this->input->post( 'TS' ) != $this->session->userdata('form_TS') )
{...}
IF you want to avoid the resubmit then please after save redirect on same controller like this
It can be solved using session. If there is any POST form submit,
ie
if (count($_POST) > 0){
$this->session->set_userdata('post_data', $_POST );
redirect('same_controller');
}
else{
if($this->session->userdata('post_data')){
$_POST = $this->session->userdata('post_data');
$this->session->unset_userdata('post_data');
}
}
Kindly use this:
$post_data = $this->session->userdata('post_data');
if ($post_data == $_POST){
$this->session->unset_userdata('post_data');
redirect(current_url(), 'refresh');
}else{
$this->session->set_userdata('post_data', $_POST );
}

catch always get called

I'm having problem saving data to the database since catch exception is always being called. try always get ignored. I don't really know what's happening. I've been working for this for hours and I can't get it to work. I'm using kohana 3.3 and kostache.
So here's the controller.
Controller
APPATH/classes/controller/album.php
public function action_create()
{
$view = Kostache_Layout::factory();
$layout = new View_Pages_Album_List();
$album = ORM::factory('Album_Information');
$album_name = $this->request->post('inputAlbum');
$artist = $this->request->post('inputArtist');
$album->Album_Name = $album_name;
$album->Artist = $artist;
try
{
$album->save();
HTTP::redirect('album');
}
catch(ORM_Validation_Exception $e)
{
$layout->errors = $e->errors('models');
}
}
$this->response->body($view->render($layout));
}
Templates
APPATH/templates/pages/album/list.mustache
<h3>Add A New Album</h3>
<form action="album/create" method="post">
<label for="inputAlbum">Album Name:</label>
<input id="inputAlbum" type="text" name="inputAlbum" /><br />
<label for"inputAlbum" class="error">{{#errors}}{{inputAlbum}}{{/errors}}</label>
<label for="inputArtist">Album Artist:</label>
<input id="inputArtist" type="text" name="inputArtist" /><br />
<label for="inputArtist" class="error">{{#errors}}{{inputArtist}}{{/errors}}</label>
<input type="submit" name="submit" value="Add" />
</form>
Model Rules
APPATH/classes/model/album/information.php
class Model_Album_Information extends ORM
{
protected $_primary_key = 'ID';
protected $_table_name = 'album_information';
public function rules()
{
return array(
'inputAlbum' => array(
array('not_empty'),
),
'inputArtist' => array(
array('not_empty'),
),
);
}
Messages
APPATH/messages/models/album.php
return array(
'inputAlbum' => array(
'not_empty' => ':You must provide Album Name',
),
'inputArtist' => array(
'not_empty' => ':You must provide Album Artist',
),
);
The errors are showing when there's no input on the input field when i hit on the submit button, no problem with that, but even there's an input the errors are still being shown. So catch is always being called. When i remove try and catch I can easily save data to the database but there's no validation.
Thank you and more power.
You expect the ORM class to magically know the value of $album->Album_Name came from a HTTP form input named inputAlbum. It won't.
Create rules for the Album_Name and Artist properties of the ORM object itself. Not the possible input method.
The Controller knows what data to pass to models. The Model is only concerned with the data it received. Not where it came from.

Categories