Get data from $_SESSION - php

I'm trying to create simple server side validation, this is my method
public function create() {
$name = $_POST['name'];
session_start();
unset($_SESSION['errors']);
$count = $this->model->checkIfUserExists($name);
if($count > 0) {
$_SESSION['errors'] = array(
'message' => 'User Already Exists',
'variables' => array(
'name' => $_POST['name'],
'password' => $_POST['password'],
),
);
header('location: ' . URL . 'user/registration');
exit;
}
$data = array();
$data['name'] = $_POST['name'];
$data['password'] = $_POST['password'];
$this->model->create($data);
header('location: ' . URL);
}
and below code from registration.php
<?php
if (isset($_SESSION['errors']) && count($_SESSION['errors']) > 0) {
echo '<ul>';
foreach ($_SESSION['errors'] as $error) {
echo '<li>' . $error['message'] . '</li>';
}
echo '</ul>';
unset($_SESSION['errors']);
}
?>
but I got errors
Warning: Illegal string offset 'message' in C:\xampp\htdocs\test\views\user\registration.php on line 6
�
Notice: Undefined index: message in C:\xampp\htdocs\test\views\user\registration.php on line 6
How to fix it?

Generally, Warning: Illegal string offset ... means that you are trying to access a string as an array.
Currently, you are setting $_SESSION['errors'] to an associative array with two elements, message and variables. I believe what you are trying to achieve is to create an array with multiple errors that each have a message and variables.
Setting it like this should do:
...
$_SESSION['errors'] = array();
if ($count > 0) {
$_SESSION['errors'][] = array(
'message' = > 'User Already Exists',
'variables' = > array(
'name' = > $_POST['name'],
'password' = > $_POST['password'],
),
);
header('location: '.URL.'user/registration');
exit;
}
...
The empty square brackets add a new element to the array:
$myArray[] = $myNewElement;
This way you can easily add additional errors to the list:
$_SESSION['errors'][] = array(
'message' = > 'Error two',
'variables' = > array(...),
);
$_SESSION['errors'][] = array(
'message' = > 'Error three',
'variables' = > array(...),
);

It's because foreach goes throught items in main array. ["message", "variables"]
Assign $_SESSION['errors'] = like this: $_SESSION['errors'][] =
$_SESSION['errors'][] = array(
'message' => 'User Already Exists',
'variables' => array(
'name' => $_POST['name'],
'password' => $_POST['password'],
),
);

registration.php at first start session session_start()
<?php
session_start();
if (isset($_SESSION['errors']) && count($_SESSION['errors']) > 0) {
echo '<ul>';
foreach ($_SESSION['errors'] as $error) {
echo '<li>' . $error['message'] . '</li>';
}
echo '</ul>';
unset($_SESSION['errors']);
}
?>

Related

Loop return one result in conditioner query

I am trying to fetch data from database in code-igniter .Bur this loop return only one loop .
$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();
foreach($userchatData as $key => $userdata)
{
$userdatas[]= array(
'chat_id' => $userdata['chat_id'],
'chat_from' => $userdata['chat_from'],
'created_date' => $userdata['created_date']
);
}
$data['ChatdatabyId'] = $userdatas;
$data['responseCode'] = '200';
$data['responseMessage'] = 'User listing successfully';
echo json_encode($data);
You need to define $userdatas=array(); outside the loop. It is inside the loop that's why it overrides the data and returns the last record.
$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();
$userdatas = array();
foreach($userchatData as $key => $userdata){
$userdatas[]= array(
'chat_id' => $userdata['chat_id'],
'chat_from' => $userdata['chat_from'],
'created_date' => $userdata['created_date']
);
}
$data['ChatdatabyId'] =$userdatas;
$data['responseCode'] = '200';
$data['responseMessage'] = 'User listing successfully';
echo json_encode($data);
Hope this will help you :
$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();
foreach($userchatData as $key => $userdata)
{
$userdatas[$key]['chat_id'] = $userdata['chat_id'];
$userdatas[$key]['chat_from'] = $userdata['chat_from'];
$userdatas[$key]['created_date'] = $userdata['created_date'];
}
/*print_r($userdatas); output here*/
$data['ChatdatabyId'] = $userdatas;
$data['responseCode'] = '200';
$data['responseMessage'] = 'User listing successfully';
}
echo json_encode($data);

PHP function errors not showing

I wasn't entirely sure how to search for this question, so if it has been asked before please send me in the right direction.
I have a validation function with an array. Inside my array I have set up errors to be displayed if one of the form fields doesn't validate. If the user fills a field out wrong, they should get an error of which field was wrong and the form should be still present. However, they get a blank page with only the generic error (the one I echo when I called the function) and not the field-specific error. Can someone please tell me where I went wrong?
$output_form = 1; //control if form displays - yes
$error_text = '';
//declare form elements (empty first load)
$fname = '';
$valid_fname = 0;
$fname_regex = '/^([A-Z]|[a-z]){2,15}$/';
$fname_error_message = 'First name must be 2-15 alphabetic characters only.<br>';
$lname = '';
$valid_lname = 0;
$lname_regex = '/^([A-Z]|[a-z]){2,15}$/';
$lname_error_message = 'Last name must be 2-15 alphabetic characters only.<br>';
$phone = '';
$valid_phone = 0;
$phone_regex = '/^\(\d{3}\)\d{3}-\d{4}$/';
$phone_error_message = 'Phone number must be in (xxx)xxx-xxxx format.<br>';
$city = '';
$valid_city = 0;
$city_regex = '/^([A-Z]|[a-z]){2,15}$/';
$city_error_message = 'City must be 2-15 alphabetic characters only.<br>';
$state = '';
$valid_state = 0;
$state_regex = '/^([A-Z]|[a-z]){2}$/';
$state_error_message = 'State must be 2 alphabetic characters only.<br>';
//data posted
if (isset($_POST['submit'])) {
if ($debug) {
echo "<pre>";
print_r($_POST);
echo "</pre>";
}//end debug
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$phone = trim($_POST['phone']);
$city = trim($_POST['city']);
$state = trim($_POST['state']);
$phone_replace = preg_replace('/[\(\)\-\s]/', '', $phone);
function validate_form($fields, &$errors = []) {
$errors = [];
foreach ($fields as $name => $field) {
if (!preg_match ($field['regex'], $field['value'])) {
$errors[$name] = $field['error'];
$output_form = 1;
}
}
return empty($errors); //returns true/false
}
$fields = [
'fname' => ['regex' => $fname_regex, 'value' => $fname, 'error' => $fname_error_message],
'lname' => ['regex' => $lname_regex, 'value' => $lname, 'error' => $lname_error_message],
'phone' => ['regex' => $phone_regex, 'value' => $phone, 'error' => $fname_error_message],
'city' => ['regex' => $city_regex, 'value' => $city, 'error' => $city_error_message],
'state' => ['regex' => $state_regex, 'value' => $state, 'error' => $state_error_message],
];
$errors = [];
if (!validate_form($fields, $errors)) {
echo "<p>One of your fields is invalid. Please check and re-submit.</p>";
$output_form = 1;
return (false);
}
else {
$output_form = 0;
}
foreach($errors as $error) echo "<p>$error</p>";
Actually outputting stuff usually helps ;)

Add Variables to an array?

I want to add variables to an array, what I'm trying to do is to check if there is an error from the view within the controller and the variable will be added to an array here is an example.
$error = array ();
if (input1 == null)
{
$errormessage1 = '*';
$error[] = $errormessage1;
}
if (input2 == null)
{
$errormessage2 = '*';
$error[] = $errormessage2;
}
if (input1 != null AND input2 != null)
{
//insert to database or something
}
else
$this->load->view("view", $error);
The problem is that the values are not being inserted to the array. And the array is not printing anything after I return it to the view.php
Here is an example of my view.php
echo form_label('User Name:', 'input1 ' );
$data= array(
'name' => 'input1 ',
'placeholder' => 'Please Enter User Name',
'class' => 'input_box'
);
echo form_input($data);
if(isset($errormessage1 ))
echo $errormessage1 ;
Thank you for any help that you can give me.
I see you are trying to tell the user that username is required. right? then why don't you utilize Codeigniter form_validation library? to display the errors you use form helper method validation_errors()
Your View
<?php echo validation_errors();
echo form_label('User Name:', 'input1 ' );
$data= array(
'name' => 'input1 ',
'placeholder' => 'Please Enter User Name',
'class' => 'input_box'
);
echo form_input($data);
Your Controller
public function your_method(){
$this->load->library('form_validation');
$this->form_validation->set_rules('input1','Username','required');
//and so on for other user inputs
if($this->form_validation->run()===TRUE){
//send to model may be
}else{
$this->load->view('view');
}
}

merging two array into single inside json_encode for android

I have to combine two array into single inside Json encode. my code is,
// Controller
$email = $this->input->get('email');
$pass = $this->input->get('password');
$enc_pass = 0;
$get_pass = $this->select->selectData($email);
if(!empty($get_pass)) {
foreach($get_pass as $password)
$enc_pass = $password['user_password'];
$dec_pass = $this->encrypt->decode($enc_pass);
if($pass == $dec_pass) {
$details = array('tag' => 'login', 'status' => 'true');
echo json_encode(array_merge($get_pass, $details));
}
else {
$details = array('tag' => 'login', 'status' => 'false', 'error_msg' => 'Incorrect Email or Password');
echo json_encode($details);
}
}
else {
$details = array('tag' => 'login', 'status' => 'false', 'error_msg' => 'Incorrect Email or Password');
echo json_encode($details);
}
// Model
public function selectData($email) {
$query = $this->db->query('SELECT * FROM tbl_user WHERE email = "'.$email.'"');
$count = $query->num_rows();
if($count > 0)
return $result = $query->result_array();
else
return 0;
}
Now the output for the above code is,
{"0":{"user_id":"1","user_name":"Jithin Varghese","user_email":"jithinvarghese111#gmail.com","user_phone":"9947732296","user_status":"1"},"tag":"login","status":"true"}
Required output is,
{"user_id":"1","user_name":"Jithin Varghese","user_email":"jithinvarghese111#gmail.com","user_phone":"9947732296","user_status":"1","tag":"login","status":"true"}
How to get the required output. I have tried a lot. How to implement this.
Thankyou.

Header location - This webpage has a redirect loop

Hi I am trying to redirect to a form page however I got the following message
ERR_TOO_MANY_REDIRECTS
I have been able to figure that
header('Location: http://localhost:8888/wordpress/send');
is causing the error I have tried a number of different things including adding exit underneath the final line of code but it still seems to be looping.
<?php
/*
Template Name: Send
*/
?>
<?php
session_start();
require_once(get_template_directory().'/vendor/PHPMailer/PHPMailerAutoload.php');
$errors = [];
if(isset($_POST['customername'], $_POST['email'], $_POST['message'])) {
$fields = [
'name' => $_POST['customername'],
'email' => $_POST['email'],
'message' => $_POST['message']
];
foreach ($fields as $field => $data) {
if (empty($data)) {
$errors[] = 'The ' . $field . ' field is required';
}
}
} else {
$errors[] = 'Something went wrong.';
}
header('Location: http://localhost:8888/wordpress/send');
exit();

Categories