Codeigniter $this->input->post is always FALSE - php

I am trying to send an httpRequest to a codeigniter controller function. I am using the REST console to test the function .
I am trying to send 3 POST variables .
UserName
Email
UserID
Here's the code to handle the request
public function NewUser()
{
if($this->input->post())
{
$FID = $this->input->post('UserID');
$UserName = $this->input->post('UserName');
$Email = $this->input->post('Email');
echo "working";
echo $FID;
echo $UserName;
}
else
{
echo "not working";
}
}
But this doesn't work. It always output's not working. When I change everything to geteverything starts working fine.
What could be the issue ? Post Request is not working anywhere throughout this codeigniter project.
EDIT
I created a new script, with the following code.
<?php
var_dump($_POST);
echo $_POST['UserName'];
echo $_POST['FacebookID'];
echo $_POST['Email'];
echo "********************************";
?>
It is saying undefined index . What could be the issue ? Please help. It works fine for $_GET

$this->input->post() is obliviously return the false because you are not mentioning the name of which value you want to retrieve using post.Make changes here in your code :
if(isset($_POST))
or
if(!empty($_POST))
See POST
you can also do this:
if($this->input->post('username'))//username is the name of post variable

you should try
isset($_REQUEST)
or
!empty($_REQUEST)
to check data is coming or not

To get the method in codeigniter 3 (docs) you can use the following code:
echo $this->input->method(TRUE); // Outputs: POST
echo $this->input->method(FALSE); // Outputs: post
echo $this->input->method(); // Outputs: post
example:
public function NewUser()
{
if($this->input->method() === 'post')
{
$FID = $this->input->post('UserID');
$UserName = $this->input->post('UserName');
$Email = $this->input->post('Email');
echo "working";
echo $FID;
echo $UserName;
}
else
{
echo "not working";
}
}

Try
if( count($this->input->post()) > 0 )
{
}
else
{
}

I had a similar problem. Due to using internationalization, URLs get redirected from user/login to user/en/login. When that redirect happens, the POST array gets lost.
I am not sure if this is your problem as well, but check if your page redirects after submission.

In Codeigniter we can check which HttpRequest it is using 2 below Input class' method :
1. server('REQUEST_METHOD')
$this->input->server() is identical to Core PHP's $_SERVER variable.
example:
if ($this->input->server('REQUEST_METHOD') == 'GET') {
echo "It's GET Request";
} else if ($this->input->server('REQUEST_METHOD') == 'POST') {
echo "It's POST Request";
}
2. method()
Since Codeigniter 3 we can use method() also for checking request type.
method([$upper = FALSE])
Parameters:
$upper (bool) – Whether to return the request method name in upper or lower case
Returns: HTTP request method
Return type: string
explanantion: It Returns the $_SERVER['REQUEST_METHOD'], with the option to set it in uppercase or lowercase.
example:
echo $this->input->method(TRUE); // Outputs: POST
echo $this->input->method(FALSE); // Outputs: post
echo $this->input->method(); // Outputs: post

Related

Values not passed from ctp file to controller in CakePHP

I have tried several solution posted in this forum and others as well but it has not helped so far. So I am posting my question finally. BTW, I am using CakePHP 3.6.
I am trying to pass a variable ($product->id) via submit button in view.ctp to my controller action "addit" but I just get "Undefined variable: id " (I have tried addit($id) and addit() either of case I have the same result.)
view.ctp
<p>
<?php echo $this->Form->create('NULL',['url'=>['controller'=>'products','action'=>'addit']]);?>
<?php echo $this->Form->input('id', ['type' => 'hidden', 'value' => $product->id]); ?>
<?php echo $this->Form->button('Add to cart now');?>
<?php echo $this->Form->end();?>
</p>
Controller:Products
public function addit() {
$this->autoRender = false;
if ($this->request->is('post')) {
// $this->Products->addProduct($this->request->data['Cart']['product_id']);
echo "".$this->Products->get($id);//for test
} else {
echo "".$this->Products->get($id);//for test
}
}
According to Cakephp 3.6
All POST data can be accessed using
Cake\Http\ServerRequest::getData(). Any form data that contains a data
prefix will have that data prefix removed. For example:
// An input with a name attribute equal to 'MyModel[title]' is accessible at
$title = $this->request->getData('MyModel.title');
You can get value of $id variable like this:
$id = $this->request->getData('id');
Further Reading: Request Body Data
Is this what you want to do?
$id = $this->request->getData('id');
debug($this->Products->get($id)); //for test

Codeigniter: passing a post variable from one function to another in a controller

Am getting a variable called $msisdn from a view using post in one function (search_results). After doing the processing, I would like to use the same variable in another function(assign_role) currently,I am unable to do that since am getting this error
Severity: Notice Message: Undefined variable: msisdn
. Below is my search_result function where am getting the post data:
public function search_results(){
$msisdn = $this->input->post('search_data');//getting data from the view
if ($msisdn == false){
$this->load->view('add_publisher');
} else{
$this->assign_role($msisdn); //passing the variable to another function
$this->load->model('search_model');
$data['result'] = $this->search_model->search_user($msisdn);
$data1['box'] = $this->search_model->search_select($msisdn);
$result = array_merge($data, $data1);
$this->load->view('add_publisher',$result);
echo json_encode($result);
}
}
I want to use $msisdn from above function in this function below:
public function assign_role($msisdn){
//echo $msisdn['numm'];
$publisher = $this->input->post('select');
if ($publisher == false) {
$this->load->view('add_publisher');
} else {
$data = array(
'publisher' => true,
);
$this->load->model('insert_model');
$data1 = $this->insert_model->search_group($msisdn, $data);
if ($data1 == true) {
echo "Recorded updated succesfully";
$this->load->view('add_publisher');
} else {
echo "Recorded not updated";
$this->load->view('add_publisher');
}
}
}
Please help me to achieve this.
Passing variables from one function to another in the same controller can be achieved by using sessions. In Codeigniter, one can use flashdata like:
$this->session->set_flashdata('info', $MyVariable);
Remember, flashdata is only available for the next server request then it will be automatically cleared.
Then it can be retrieved as:
$var = $this->session->flashdata('info');
If you want to keep the variable for one more server request, you can do this:
$this->session->keep_flashdata('info');
Hope this will help someone faced with the problem.

Zend flash messenger

I have a form and the submit button check if true or false.
If it's true redirect to another page.
If it's false stay on the same page and print the error message.
The error message is print out with a flash messenger.
But, in some case it doesn't print in the first try when submit is false, it always print out on the second click.
Did I did something wrong?
And also, is there a way to set difference flash messenger name? Because, on my others pages that have flash messenger, print out the error when page is refreshed.
Here's the code:
if(isset($_POST['submit'])) {
// code to inputfields
if(true) {
//redirect to some page
} else {
// print the flash error on the same page
$this->_helper->flashMessenger->addMessage(" This email is already taken");
$this->view->messages = $this->_helper->flashMessenger->getMessages();
}
}
HTML:
<center>
<div style="color:red">
<?php if (count($this->messages)) : ?>
<?php foreach ($this->messages as $message) : ?>
<div id="field_name">
<strong style="text-transform:capitalize;">Email </strong>
- <?php echo $this->escape($message); ?>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
</center>
flashmessenger is really designed to be used on a redirect of some kind, so any message you see probably comes from the prior action's execution. Your current code would not flash any message during the first 'post'.
you may have some luck if you try something like:
public function init()
{
//This will catch any messege set in any action in this controller and send
//it to the view on the next request.
if ($this->_helper->FlashMessenger->hasMessages()) {
$this->view->messages = $this->_helper->FlashMessenger->getMessages();
}
}
public function someAction()
{
if(isset($_POST['submit'])) {
// code to inputfields
if(true) {
//redirect to some page
} else {
// print the flash error on the same page
$this->_helper->flashMessenger->addMessage(" This email is already taken");
//will redirect back to original url. May help, may not
$this->_redirect($this->getRequest()->getRequestUri());
}
}
}
Here's an action I coded that demonstrates what you seem to be attempting.
public function updatetrackAction()
{
//get the page number
$session = new Zend_Session_Namespace('page');
$id = $this->getRequest()->getParam('id');
//get the entity object
$model = new Music_Model_Mapper_Track();
$track = $model->findById($id);
//get the form
$form = new Admin_Form_Track();
$form->setAction('/admin/music/updatetrack/');
//test for 'post' 'valid' and update info
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$data = $form->getValues();
$newTrack = new Music_Model_Track($data);
$update = $model->saveTrack($newTrack);
//add message
$this->message->addMessage("Update of track '$update->title' complete!");
//redirects back to the same page number the request came from
$this->getHelper('Redirector')->gotoSimple('update', null, null, array('page' => $session->page));
}
} else {
//if not post display current information
//populate() only accepts an array - no objects -
$form->populate($track->toArray());
$this->view->form = $form;
}
}

Codeigniter - Checking if a GET request is made

Im using CodeIgniter to write a site ... I understand $_GET requests are now used like so www.website.com/function/value .. and in the controller getting a url segment is written like so:
$userId = $this->uri->segment(3, 0);
Im just wondering, when a controller loads, i want to check if there is any uri segments, if there is then push to one view, else if there isnt a uri segment push to another.
Is that possible?
cheers.
You can use your controller arguments for that too.
When accessing /user/profile/1 your controller named User will call the method profile() and pass the number 1 as the first argument to your method. Like so:
class User extends CI_Controller {
{
public function index()
{
$this->load->view("user_index");
}
public function profile ( $userId = null )
{
if( (int)$userId > 0 )
$this->load->view("user_profile");
else
$this->load->view("another_view");
}
}
This is a very basic sample and I'm just trying to show the idea.
Seems like your asking two questions...
First, to check if the request is get
public function get_test()
{
if($_SERVER['REQUEST_METHOD'] == "GET")
{
//do something from get
echo "GET";
}
else
{
//do something not get
echo "NOT GET";
}
}
The next question seemed to be checking uri segments
public function get_test()
{
if($_SERVER['REQUEST_METHOD'] == "GET")
{
//do something from get
//echo "GET";
if($this->uri->segment(3)) //is true as is not empty
{
echo $this->uri->segment(3);
}
else
{
echo "I am nothing without my URI Segment";
}
}
else
{
//do something not get
echo "NOT GET";
}
}
As I understand you can use PHP default value.
function myFunction($var1 = NULL) {... if($var1 === NULL) ...}
Now if you do not pass the param you will get the NULL value.
I am still not using version 2 of codeigniter but this framework do not accept get requests; unless you mess with the configuration. Theres a function $this->input->get('myGet') you should look around at de the codeigniter.com/user_guide

Make form remember earlier submitted values with CodeIgniter

I have this contact form with codeigniter, and what I want to do is, when the form is submitted but does not pass validation, I want the fields to contain earlier submitted values.
There's one thing though: when the form is loaded all the fields already have a certain value assigned, so for example the "name field" shows "name" inside the field. And I want this to stay that way, unless "name" is changed and the form is submitted, in that case it should have the new value.
So for the moment I have this:
<?php echo form_input('name', 'Name*');?>
<?php echo form_input('email', 'Email*');?>
But I don't know how to make the form remember any new submitted values.
Anyone any idea?
I'd recommend using CodeIgniter's set_value method.
<?php echo form_input('name', set_value('name', 'Name*')); ?>
I think the answer lies in the controller.
Personally, I started letting the forms controller function handling the validation:
<?php
class Page extends Controller
{
...
function showform()
{
$this->load->helper(array('form', 'url'));
$data = array("name" => "Name*", "email" => "Email*");
$failure = false;
if( $this->input->post("name") )
{
$data["name"] = $this->input->post("name");
$data["email"] = $this->input->post("email");
if( !valid_email($data["email"]) )
{
$failure = true;
$data["error_message"] = "E-mail couldn't validate";
}
if( !$failure )
redirect('/page/thankyou/', 'refresh');
}
$this->load->vars($data);
$this->load->view("theform");
}
...
}
And in your view, you would do something like this:
<?php echo form_input('name', $name);?>
<?php echo form_input('email', $email);?>
If you are submitting to the same controller, you can get the previously submitted variables through $_POST (or $_GET depending on which form method you chose).
// use $_POST['name'] if set, else use 'Name*'
<?= form_input('name', (!empty($_POST['name']) ? $_POST['name'] : 'Name*'); ?>

Categories