How to import csv file into mysql using codeigniter - php

I want to import csv into mysql using codeigniter.
This is my source code.
view
<?php $this->load->view("admin/v_header");?>
<?php $this->load->view("admin/v_top_menu");?>
<?php $this->load->view("admin/v_sidebar");?>
<div class="content">
<div class="header">
<h1 class="page-title">Import Data Dosen</h1>
</div>
<?php $this->load->view("admin/v_alert_msg");?>
<form class="form-horizontal" action="<?php echo base_url();?>admin/save_dosen" method="POST" enctype="multipart/form-data">
<fieldset>
<legend>Import Data Dosen</legend>
<div class="control-group">
<label class="control-label"><b>Pilih File :</b></label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-barcode"></i></span>
<input type="file" name="csv_dosen" id="csv_dosen"/>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">
<i class="icon-ok icon-white"></i>Save
</button>
</div>
</div>
</fieldset>
</form>
</div>
<?php $this->load->view("admin/v_footer");?>
library
<?php
error_reporting(0);
class Csv_impot {
var $csvfile, $delimitatore, $nometable;
var $_FIELD;
function csv_import($cf = "", $del = "", $nt = "") {
$this->csvfile = $cf;
$this->delimitatore = $del;
$this->nometable = $nt;
}
function export() {
$csvhandle = file($this->csvfile);
$field = explode($this->delimitatore, $csvhandle[0]);
$kolom = "";
foreach ($field as $array_kolom) {
$kolom.="`" . trim($array_kolom) . "`,";
}
$kolom = trim(substr($kolom, 0, -1));
//echo $kolom;
for ($i = 1; $i <= count($csvhandle); $i++) {
$valori = explode($this->delimitatore, $csvhandle[$i]);
$values = "";
foreach ($valori as $val) {
$val = trim($val);
if (eregi("NULL", $val) == 0)
$values.="'" . addslashes($val) . "',";
else
$values.="NULL,";
}
$values = trim(substr($values, 0, -1));
$query = "INSERT INTO " . $this->nometable . "(" . $kolom . ") values(" . trim($values) . ");";
$QUERY[$i] = $query;
}
return $QUERY;
}
}
controller
function import_dosen()
{
$this->data['title']="Import Data Dosen";
$this->load->view("admin/v_import_dosen", $this->data);
}
function save_dosen()
{
if(isset($_FILES['csv_dosen']['name']))
{
$csv_dosen=$_FILES['csv_dosen']['name'];
$handle = fopen($csv_dosen,"r");
$this->load->library('csv_import');
$csv=new csv_import(".$handle.",",","dosen");
$query=$csv->export();
$this->m_dosen->eksekusi($query);
// $check_file= explode(".", $csv_dosen);
// if(strtolower($check_file[1])=="csv")
// {
// $csv_dosen=$_FILES['csv_dosen']['temp_name'];
// $handle = fopen($csv_dosen,"r");
// while (($data = fgetcsv($handle, 1000,",")) !== FALSE)
// {
// echo "haha";
// }
// }
// else{echo "bukan file csv";}
//$handle = fopen($csv_dosen,"r");
//$csv_dosen_type=$_FILES['csv_dosen']['type'];
//$csv_dosen_size=$_FILES['csv_dosen']['size'];
}
//echo $handle;
}
models
<?php
class M_dosen extends CI_model
{
function __contruct()
{
parent::__construct();
}
function eksekusi($query)
{
//echo "<br/>";
//echo count($query);
for($i=1;$i<count($query);$i++)
{
$this->db->query($query[$i]);
//echo $query[$i];
//echo "<br/>"
}
}
}
?>
when I run this code, an erro display that [function.fopen]: failed to open stream: No such file or directory.
How I solved this promblem?
I hope you can help to solve this problem.
Thanks.

As per your library, you have to pass file name to your Csv_impot constructor. But you are passing file Handler.
so change your code as below.
//general oops method:
$csv=new csv_import($csv_dosen,",","dosen");
//In CI,
$this->load->library('csv_import',array($csv_dosen,",","dosen")); // no need to create object again. Array of values will be parameter for constructor.

Related

Reading CSV giving different outputs in different computers

So in my platform i have a functionality which reads email, first name and last name from a csv file and then save them in database on to an array. All is working fine in my computers, but however in 2 of my co workers pc the list is returning 0 elements and it has 37, however running it in multiple browsers on my 2 computers it works perfectly fine. We are all using the same list to test.
<form action="" method="POST" enctype="multipart/form-data">
<label>Nome da lista:</label>
<input class="form-control" typr="text" name="nome" placeholder="Nome" /></br>
<label>Lista (Ficheiro CSV):</label>
<input type="file" name="file" id="file">
<button type="submit" id="enviar" name="submit" style="max-width:100px; background: #ed1a3d; margin-top:10px;" class="btn btn-primary btn-lg btn-block btn-icon-split">
Criar
</button>
</form>
<?php
global $user;
if(isset($_POST['submit'])) {
if ($_FILES['file']['tmp_name']) {
$nome = $_POST['nome'];
$file = $_FILES['file']['tmp_name'];
$user->criarLista($nome, $file);
} else {
$user->mensagem(1, "Não existe nenhum ficheiro");
}
}
?>
And this is the criarLista function (Which means create list ):
public function criarLista($nome,$file){
$user = $this->user;
$get = $this->connect->query("SELECT * FROM users WHERE email = '$user'");
$fetch = $get->fetch_array(MYSQLI_ASSOC);
$user_id = $fetch['id'];
if($insert = $this->connect->prepare("INSERT INTO lista(user_id,nome) VALUES(?,?)")){
$insert->bind_param("is", $user_id,$nome);
$insert->execute();
$list_id = $insert->insert_id;
$file = preg_replace('#\\x1b[[][^A-Za-z]*[A-Za-z]#', '', $file);
$file = strip_tags($file);
$lines = file($file);
$emails = array();
$fnames = array();
$lnames = array();
$linha = 0;
foreach($lines as $line) {
if($linha == 0){
}else{
if (strpos($line, ',') !== false) {
$arr = explode(",", $line);
// Email \ FNAME | LAST
$emailx = trim($arr[0]);
$emailx = trim(preg_replace("/[\\n\\r]+/", "", $emailx));
array_push($emails,$emailx);
if(isset($arr[1])){
$fname = trim($arr[1]);
$fname = str_replace('"','',$fname);
array_push($fnames,$fname);
}
if(isset($arr[2])){
$lname = trim($arr[2]);
array_push($lnames,$lname);
}
}else{
array_push($emails,trim($line));
}
}
$linha++;
}
array_map('trim', $emails);
array_map('trim', $fnames);
array_map('trim', $lnames);
$emails = implode(",",$emails);
$fnames = implode(",",$fnames);
$lnames = implode(",",$lnames);
if($insert_list = $this->connect->prepare("INSERT INTO listas(lista_id,email,primeiro_nome,ultimo_nome) VALUES(?,?,?,?)")){
$insert_list->bind_param("isss", $list_id,$emails,$fnames,$lnames);
$insert_list->execute();
$this->mensagem(2,"Lista adicionada com sucesso");
}else{
echo
'
<div class="alert alert-danger">
Erro: '.$this->connect->error.'
</div>
';
}
}else{
echo
'
<div class="alert alert-danger">
Erro: '.$this->connect->error.'
</div>
';
}
}
Is there anything that may create this incompability between some computers?

File (image) Upload issue in codeigniter

Actually, I have saved all the data in database after i have show in front end,in my side issue is i have created upload image function to save database after i fetch and display the front end,upload function is taking to save full path like :C:/xampp/www/htdocs/rentozy/admin/images/media/rajkumar-1515559187/1.jpg. all the images saved folder also but in front end is coming like this only : C:/xampp/www/htdocs/rentozy/admin/images/media/rajkumar-1515559187/1.jpg please i need save database like this : (images/media/rajkumar-1499778784/19510.jpg) please help me how will resolve this this is my first sit is codeigniter please help how will pass like this url.
Here my code for controller:
function addNewMedia()
{
if($this->isAdmin() == TRUE)
{
$this->loadThis();
}
else
{
$this->load->library('form_validation');
$this->form_validation->set_rules('name','Name','trim|required|max_length[128]|xss_clean');
$this->form_validation->set_rules('event_image','Pg Image');
// $this->form_validation->set_rules('media_image','Image');
// $this->form_validation->set_rules('date_added','Date','trim|required');
if($this->form_validation->run() == FALSE)
{
$this->addNew();
}
else
{
$data = array(); $upload_data = array();
$this->load->library('upload');
$data['name'] = $this->input->post('name');
$folder_srting = $data['name']."-".time();
$data['name'] = $this->input->post('name');
// print_r($folder_srting);
$folder_string = str_replace(' ', '-', $folder_srting);// Replaces all spaces with hyphens.
$folder_string = preg_replace('/[^A-Za-z0-9\-]/', '', $folder_srting);// Removes special chars.
$folder_name = preg_replace('/-+/', '-', strtolower($folder_string));// Replaces multiple hyphens with single one.
print_r($folder_name);
//$data['name'] = $this->input->post('name');
//$pg_id = $this->input->post('pg_id');
if ($_FILES['event_image']['error'] != 4)
{
$folder = $this->checkdirectory($folder_name);
//print_r($folder_name);
$this->upload->initialize($this->set_upload_options($folder));
if ( ! $this->upload->do_upload('event_image'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error); die;
}
else
{
$upload_data['banner_data'] = $this->upload->data();
//print_r($upload_data['banner_data']);die;
$upload_data['bannerfilepath'] = $upload_data['banner_data']['full_path'];
//print_r($upload_data['bannerfilepath']);die;
}
foreach($upload_data['banner_data'] as $bannerfilepath){
$data['banner_image_path'] = str_ireplace(FCPATH,"", $upload_data['banner_data']['full_path']);
//print_r($data['banner_image_path']);die;
}
$event_image = $data['banner_image_path'];
//print_r($event_image);die;
}
// $name = ucwords(strtolower($this->input->post('name')));
$event_image = $event_image;
//print_r($event_image);die;
$name = $this->input->post('name');
$address = $this->input->post('pg_address');
$incharge_name = $this->input->post('pg_incharge_name');
$incharge_mobile = $this->input->post('pg_incharge_mobile');
$email = $this->input->post('pg_email');
$mediaInfo = array('name'=>$name,'event_image'=>$event_image,'pg_address'=>$address,'pg_incharge_name'=>$incharge_name,'pg_incharge_mobile'=> $incharge_mobile,'pg_email'=>$email,'folder_name'=>$folder);
//echo "<pre>";print_r($mediaInfo);die;
$this->load->model('media_model');
//echo "<pre>";print_r($mediaInfo);die;
$result = $this->media_model->addNewMedia($mediaInfo);
if($result > 0)
{
$this->session->set_flashdata('success', 'New Pg created successfully');
}
else
{
$this->session->set_flashdata('error', 'Pg creation failed');
}
redirect('mediaListing');
}
}
}
function editMedia()
{
if($this->isAdmin() == TRUE)
{
$this->loadThis();
}
else
{
$this->load->library('form_validation');
$eventId = $this->input->post('pg_id');
$this->form_validation->set_rules('name','Name','trim|required|max_length[128]|xss_clean');
$this->form_validation->set_rules('event_image','Pg Image');
//$this->form_validation->set_rules('event_description','Event Description','required|max_length[200]');
// $this->form_validation->set_rules('start_date','Start Date','trim|required');
//$this->form_validation->set_rules('end_date','End Date','trim|required');
//$this->form_validation->set_rules('additional_images','Additional Images');
//$this->form_validation->set_rules('short_description','Short Description','required');
if($this->form_validation->run() == FALSE)
{
$this->editNew($eventId);
}
else
{
$data = array(); $upload_data = array();
$this->load->library('upload');
$existing_folder = $_POST['folder_name'];
//print_r($existing_folder);die;
if(isset($_POST['image_exists']) && $_POST['image_exists']!= '')
$temp_attachment = $_POST['image_exists'];
$folder = $this->checkdirectory($existing_folder);
if (isset($_FILES['event_image']['name']) && $_FILES['event_image']['error'][0] != 4 && $_FILES['event_image']['name']!='') {
$this->upload->initialize($this->set_upload_options($folder));
if ( ! $this->upload->do_upload('event_image'))
{
$error = array('error' => $this->upload->display_errors());
//print_r($error); die;
}
else
{
$upload_data['banner_data'] = $this->upload->data();
$upload_data['bannerfilepath'] = $upload_data['banner_data']['full_path'];
}
// GET REQUIRED BANNER IMAGES FILE PATH FROM FULL PATH
foreach($upload_data['banner_data'] as $bannerfilepath){
$data['banner_image_path'] = str_ireplace(FCPATH,"", $upload_data['banner_data']['full_path']);
print_r($data['banner_image_path']);die;
}
$event_image = $data['banner_image_path'];
//print_r($event_image);die;
}
else{
// echo "sfgjdf";
$event_image = $temp_attachment;
// print_r($event_image);die;
}
$event_image = $event_image;
$name = $this->input->post('name');
$pg_address = $this->input->post('pg_address');
$pg_incharge_name = $this->input->post('pg_incharge_name');
$pg_incharge_mobile = $this->input->post('pg_incharge_mobile');
$pg_email = $this->input->post('pg_email');
// $additional_images = $additional_images;
$mediaInfo = array('name'=>$name,'event_image'=>$event_image,'pg_address'=>$pg_address,'pg_incharge_name'=>$pg_incharge_name,'pg_incharge_mobile'=>$pg_incharge_mobile,'pg_email'=>$pg_email,'folder_name'=>$folder);
//echo "<pre>";print_r($mediaInfo);die;
$result = $this->media_model->editMedia($mediaInfo, $eventId);
if($result == true)
{
$this->session->set_flashdata('success', 'Pg updated successfully');
}
else
{
$this->session->set_flashdata('error', 'Pg updation failed');
}
redirect('mediaListing');
}
}
}
here my model:
function addNewMedia($mediaInfo)
{
$this->db->trans_start();
$this->db->insert('tbl_master_property', $mediaInfo);
$insert_id = $this->db->insert_id();
$this->db->trans_complete();
return $insert_id;
}
function getMediaInfo($eventId)
{
$this->db->select('pg_id, name,event_image,pg_address,pg_incharge_name,pg_incharge_mobile,pg_email,folder_name');
$this->db->from('tbl_master_property');
$this->db->where('status', 0);
$this->db->where('pg_id', $eventId);
$query = $this->db->get();
return $query->result();
}
function editMedia($mediaInfo, $eventId)
{
$this->db->where('pg_id', $eventId);
$this->db->update('tbl_master_property', $mediaInfo);
return TRUE;
}
here my view file code:
<?php
define("IMAGE_PATH", "http://localhost/rentozy/admin/");
$eventId = '';
$name = '';
$pg_address = '';
$pg_incharge_name = '';
$pg_incharge_mobile = '';
$pg_email ='';
$event_image = '';
$folder_name = '';
if(!empty($mediaInfo))
{
foreach ($mediaInfo as $ef)
{
$eventId = $ef->pg_id;
$name = $ef->name;
$pg_address = $ef->pg_address;
$pg_incharge_name = $ef->pg_incharge_name;
$pg_incharge_mobile = $ef->pg_incharge_mobile;
$pg_email = $ef->pg_email;
$event_image = $ef->event_image;
$folder_name = $ef->folder_name;
}
}
?>
<script type="text/javascript" src="http://js.nicedit.com/nicEdit-latest.js"></script> <script type="text/javascript">
//<![CDATA[
bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });
//]]>
</script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
<i class="fa fa-users"></i> Property Management
<small>Add / Edit Property</small>
</h1>
</section>
<section class="content">
<div class="row">
<!-- left column -->
<div class="col-lg-12 col-sm-12 col-md-12 col-xs-12">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title">Enter Property Details</h3>
</div><!-- /.box-header -->
<!-- form start -->
<form role="form" action="<?php echo base_url() ?>editMedia" method="post" id="editEvent" role="form" enctype="multipart/form-data" files="true">
<div class="box-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="event_name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name" name="name" value="<?php echo $name; ?>" maxlength="128" readonly>
<input type="hidden" value="<?php echo $eventId; ?>" name="pg_id" id="eventId" />
<input type="hidden" value="<?php echo $folder_name; ?>" name="folder_name"/>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6" style="padding-bottom:15px;">
<div class="form-group">
<label for="description" class="pull-left">Pg Address</label>
<textarea rows="6" cols="50" name="pg_address" class="pull-left" style="width:100%;" value="<?php echo $pg_address;?>" id="pgaddress"><?php echo $pg_address;?></textarea>
</div>
</div>
<div class="col-md-6" style="padding-bottom:15px;">
<div class="form-group">
<label for="description" class="pull-left">Pg Incharge Name</label>
<div class="clearfix"></div>
<textarea rows="6" cols="50" name="pg_incharge_name" class="pull-left" style="width:100%;" value="<?php echo $pg_incharge_name;?>" id="pg_incharge_name" ><?php echo $pg_incharge_name;?></textarea>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="start-date">Pg Incharge Mobile</label>
<input type="text" class="form-control required pg_incharge_mobile" value="<?php echo $pg_incharge_mobile;?>" id="pg_incharge_mobile" name="pg_incharge_mobile">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="end-date">Pg Email</label>
<input type="text" class="form-control pg_email" value="<?php echo $pg_email;?>" id="pg_email" name="pg_email">
</div>
<div class="col-md-6">
<div class="col-md-6">
<div class="form-group">
<label for="event_image">Pg Image</label>
<input type="file" value="<?php echo $event_image; ?>" class="form-control file_change1" id="eventimage" name="event_image">
<img src="<?php echo IMAGE_PATH.$event_image;?>" width="100px" height="50px">
<input type="hidden" name="image_exists" value="<?php echo $event_image;?>" class="form-control" id="eventimage" placeholder="Enter Image Text" aria-describedby="fileHelp">
<div><?php echo $event_image;?></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
I don't know if you've thought about it, but you could easily use PHP's str_replace to do what you need.
<?php
$path = $upload_data['banner_data']['full_path'];
$dir = 'C:/xampp/www/htdocs/rentozy/admin/';
$url = str_replace( $dir, '', $path );
echo $url;
In CodeIgniter, if you are saving to a path that is a directory off of document root, you can use the FCPATH constant to make this easy. So if your path to your upload folder is in a directory named /uploads/, and /uploads/ is at document root, then:
<?php
$path = $upload_data['banner_data']['full_path'];
$dir = FCPATH . 'uploads/';
$url = str_replace( $dir, '', $path );
echo $url;
This is just an example, but it is easy

Page For Entering One-time-password Does Not Appear After Sending OTP to User Using PHP

I am working on a class project, but I am stuck a little bit.
I am working on a login form, which authorizes a user to enter a one-time-password that is being sent to the user's email.
So far, the otp and the current time and date are being saved to the database successfully.
I have also managed to send the code to the user's email but once it is sent, the page does not navigate to the form where the user is supposed to enter the one-time-password.
All that works is this part here:
<form method="post" action="">
.
.
.
<div class="form-top-left">
<h3>Log in</h3>
</div>
<div class="form-top-right">
<i class="fa fa-key"></i>
</div>
<p id="profile-name" class="profile-name-card"></p>
<?php if(!empty($error_message)) { ?>
<div class="error-message"><?php if(isset($error_message)) echo $error_message; ?></div>
<?php } ?>
<span id="reauth-email" class="reauth-email"></span>
<input type="email" id="inputEmail" name="form_email" class="form-control" placeholder="Email address" required autofocus>
<input type="password" name="form_password" id="inputPassword" class="form-control" placeholder="Password" required>
<input class="btn btn-lg btn-primary btn-block btn-signin" type="submit" name="login" value="Sign in">
<div class="text-center">
<a href="wlt_passwordreset.php" class="forgot-password">
Forgot the password?
</a>
</div>
<hr>
<form class="form-signin" action="http://localhost/Dreamweaver/regist.php">
<input type="submit" value="Sign Up" class="btn btn-lg btn-primary btn-block btn-signup">
.
.
.
</form>
What could be the problem?? Can someone please help me on this.Thank you.
Here is the html part:
<html>
<head>
<title>Home</title>
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-static-top" role="navigation" style="margin-bottom:20px">
<div class="navbar-header">
<a class="navbar-inverse" href="http://localhost/Dreamweaver/index.php"><img src="img/neza.png" alt="logo"></a>
</div>
<!-- /.navbar-header -->
</nav>
</div>
<div class="container">
<div class="card card-container">
<form class="form-signin" method="post" action="">
<?php
if($success == 1) {
?>
<div class="form-wrap">
<h2>A verification code has been sent to <?php $row["form_email"] ?>. Please enter it below to verify your account.</h2>
<?php if(!empty($error_message)) { ?>
<div class="error-message"><?php if(isset($error_message)) echo $error_message; ?></div>
<?php } ?>
<div class="form-group">
<label for="key">Verification Code:</label>
<input type="password" name="otp" id="key" class="form-control">
</div>
<input type="submit" id="btn-login" class="btn btn-custom btn-lg btn-block" name="submit_otp" value="Verify Account">
<h2>Did not receive the verification code?</h2>
<!---- <form id="login-form"> ------>
<input type="submit" id="btn-login" class="btn btn-custom1 btn-lg btn-block" value="Resend Code">
<!----- </form> ----->
</div> <!---/form-wrap----->
<?php
} elseif ($success == 2) {
header("Location: fomu.php");
}else {
?>
<div class="form-top-left">
<h3>Log in</h3>
</div>
<div class="form-top-right">
<i class="fa fa-key"></i>
</div>
<p id="profile-name" class="profile-name-card"></p>
<?php if(!empty($error_message)) { ?>
<div class="error-message"><?php if(isset($error_message)) echo $error_message; ?></div>
<?php } ?>
<span id="reauth-email" class="reauth-email"></span>
<input type="email" id="inputEmail" name="form_email" class="form-control" placeholder="Email address" required autofocus>
<input type="password" name="form_password" id="inputPassword" class="form-control" placeholder="Password" required>
<input class="btn btn-lg btn-primary btn-block btn-signin" type="submit" name="login" value="Sign in">
<div class="text-center">
<a href="wlt_passwordreset.php" class="forgot-password">
Forgot the password?
</a>
</div>
<hr>
<form class="form-signin" action="http://localhost/Dreamweaver/regist.php">
<input type="submit" value="Sign Up" class="btn btn-lg btn-primary btn-block btn-signup">
</form>
<?php
}
?>
</form>
</div><!-- /card-container -->
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="text-centre">
<a class="text-new" href="#">Privacy|</a>
<a class="text-new" href="#">Security|</a>
<a class="text-new" href="#">Fees</a>
</div>
</div> <!---/row--->
</div> <!---/container--->
</div><!-- /container1-->
<!-- jQuery -->
<script src="js/jquery-1.11.1.min.js"></script>
<script src="logwin.js"></script>
<script src="bootstrap.min.js"></script>
<script src="js/mscript.js"></script>
<script src="js/scripts.js"></script>
<script src="js/jquery.backstretch.min.js"></script>
</body>
</html>
Here is the dbtest.php used to INSERT TO the db:
<?php
class DBController {
private $host = "localhost";
private $user = "root";
private $password = "myPassword";
private $database = "myDB";
private $conn;
function __construct() {
$this->conn = $this->connectDB();
}
function connectDB() {
$conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
return $conn;
}
function runQuery($query) {
$resultset = [];
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
return $resultset;
}
function numRows($query) {
$result = mysqli_query($this->conn,$query);
$rowcount = mysqli_num_rows($result);
return $rowcount;
}
function updateQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function insertQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function deleteQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function generate_OTP($length = 8, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789'){
$chars_length = (strlen($chars) - 1);
$string = $chars{rand(0, $chars_length)};
for ($i = 1; $i < $length; $i = strlen($string)){
$r = $chars{rand(0, $chars_length)};
if ($r != $string{$i - 1}) $string .= $r;
}
return $string;
}
function getConn(){
return $this->conn;
}
}
?>
Here is the PHP code that I am referring to:
<?php
session_start();
$success = "";
require_once('dbtest.php');
$db = new DBController();
if(isset($_POST["login"])) {
$result = $db->runQuery("SELECT * FROM registered_users WHERE
form_email='" . $_POST["form_email"] . "' AND status = 'active' ");
if (!empty($result)){
foreach($result as $row){
//Verify password
if ( $row['form_password'] === crypt( $_POST["form_password"], $row['form_password'] ) ) {
$otp = $db->generate_OTP();
require_once("mail_function.php");
$mail_status = sendOTP($_POST["form_email"],$otp);
if($mail_status == 1) {
$query = "UPDATE registered_users SET `otp` = '" . $otp . "', `is_expired` = 0, `create_at` = '" . date("Y-m-d H:i:s"). "' WHERE form_email = '" . $_POST["form_email"] . "'";
$result = $db->updateQuery($query);
if(!empty($result)){
$current_id = mysqli_insert_id($db->getConn());
if(!empty($current_id)) {
$success = 1;
}
}
}
}
else {
$error_message = "Email or password is incorrect!";
}
}
}
else {
$error_message = "Email or password is incorrect!";
}
}
if(isset($_POST["submit_otp"])) {
$result = $db->runQuery("SELECT * FROM registered_users WHERE otp='" . $_POST["otp"] . "' AND is_expired!=1 AND NOW() <= DATE_ADD(create_at, INTERVAL 24 HOUR)");
if(!empty($result)) {
$query = "UPDATE registered_users SET `is_expired` = 1 WHERE otp = '" . $_POST["otp"] . "'";
$result = $db->updateQuery($query);
$success = 2;
}else {
$success = 1;
$error_message = "Invalid OTP!";
}
}
?>
Bad syntax: you have the <html> tag inside the <form>, that should not happen. The <html> should only be used once at the beginning to open it and end at the end to close it.
UPDATE:
Also, mysqli_insert_id() expects the link identifier of the last mysqli_connect used. In your code, youre supplying it with $conn, but $conn is not whats being used in the DBController class.
To fix this:
add this method to you DBController class:
function getConn(){
return $this->conn;
}
then change this:
$result = $db_handle->insertQuery($query);
if (!empty($result)) {
$current_id = mysqli_insert_id($conn);
if (!empty($current_id)) {
$success = 1;
}
}
to this:
$result = $db_handle->insertQuery($query);
if (!empty($result)) {
$current_id = mysqli_insert_id($db_handle->getConn());
if (!empty($current_id)) {
$success = 1;
}
}
UPDATE2:
You asked this "After adding this method function getConn(){ return $this->conn; } I find some errors working with mysqli_fetch_array(). I am using if(!empty($result->num_rows)){while($rowcount = $result->fetch_assoc()){$row['password'];}}"
look at what runQuery() does:
function runQuery($query) {
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
it runs your SQL query, then if there are any results, it returns an array $resultset.. The problem is that you are not accounting for empty results. So lets add that, change it to this:
function runQuery($query) {
$resultset = [];
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
return $resultset;
}
Now it will return an empty array, or an array with your results.
And you can call it with:
$result = $db->runQuery("SELECT * FROM registered_users WHERE form_email='" . $_POST["form_email"] . "' AND status = 'active' ");
and use $result like this:
if(!empty($result)){
foreach($result as $row){
echo $row['password'];
}
}

Sessions Struggles - PHP

For my application, there are three levels of users:
top level (00)
mid "district" level
lower level
The interface built allows users to create messages that will be distributed to a mobile app.
I had it working fine, but was then later tasked to add the mid-level. Now, even though the messages appear to update properly, I am encountering an issue that, instead of displaying "Message Updated" and the form after a message is submitted, I am receiving the "You do not have permission to access this page" message.
This does NOT occur with the mid/district level, only the lower and upper levels. Some reason, for these two, it is not properly reading $_SESSION['store'] after the form is submitted (though it works as expected when the page is loaded normally, not via POST).
I would greatly appreciate any guidance:
<?php
session_start();
function format($input) {
$input = trim($input);
$input = stripcslashes($input);
$input = htmlspecialchars($input);
return $input;
}
$con = new PDO("sqlite:managers.db");
$store = $_SESSION['store'];
$stores;
$file;
$district;
$file = "messages/" . $store . ".txt";
if(!file_exists($file)) {
$temp = fopen($file, "w"); // create file
fclose($temp);
}
if(strpos("d", $store) == 0) {
$district = true;
$sql = "SELECT district FROM managers WHERE store = '$store'";
$statement = $con->query($sql);
$row = $statement->fetch();
$storesArray = explode(",", $row[0]);
}
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$newMessage = format($_POST['message']);
$writer = fopen($file, "w");
fwrite($writer, $newMessage);
fclose($writer);
if($district) {
foreach($storesArray as $store) {
$fileName = "messages/d" . $store . ".txt";
if(!file_exists($fileName)) {
$temp = fopen($fileName, "w"); // create file
fclose($temp);
}
$writer = fopen($fileName, "w");
fwrite($writer, $newMessage);
fclose($writer);
}
}
}
$handler = fopen($file, "r");
$currentMessage = fread($handler, filesize($file));
fclose($handler);
?>
// some code omitted //
<?php
if($store == "" || $store == null) {
echo "<p>You do not have permission to view this page</p>";
} else {
echo "<h2>Manage Messages"; if($store == "00") {
echo "<a href='admin.php'><input type='button' id='adminBack' value='Back' /></a></h2>";
} else {
echo "<a href='adminUI.php'><input type='button' id='adminBack' value='Back' /></a></h2>";
}
if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "<h2>Message Updated!</h2>";
}
echo "<form class='admin' class='col-md-6' method='post' action='manageMessages.php'>
<div class='form-group'>
<label for='message'> Message: </label>
<textarea class='form-control' id='message' name='message' >$currentMessage</textarea>
<input type='submit' value='Post Message' />
</div>
</form>";
}
?>
</div>
<!-- end page specific content -->
The login page that sets the session:
<?php
session_start();
function format($input) {
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return $input;
};
$store; $pass; $valid;
echo "<script>function redirect() {
location.assign('manageMessages.php');
}
function adminRedirect() {
location.assign('admin.php');
}</script>";
if($_GET['logout']) {
session_unset();
session_destroy();
}
if($_SERVER['REQUEST_METHOD'] == "POST") {
if(!empty($_POST['store']) && !empty($_POST['pass'])) {
$store = format($_POST['store']);
$pass = format($_POST['pass']);
$con = new PDO("sqlite:managers.db");
$sql = "SELECT *FROM managers WHERE store = '$store' AND password = '$pass'";
$statement = $con->query($sql);
$rows = $statement->fetchAll();
$count = count($rows);
if($count != 1) {
$valid = false;
} else {
$valid = true;
}
}
else {
$valid = false;
}
}
?>
// excess code //
<?php
$location;
if($valid) {
$_SESSION['store'] = $store;
if($store == "00") {
echo "<script>setTimeout(adminRedirect(), 1);</script>";
} else {
echo "<script>setTimeout(redirect(), 1);</script>";
} } elseif ($valid === false) {
echo "<h3>Please enter a valid store/password combination!</h3>";
}
?>
<h2>Admin Login</h2>
<form class="admin" method="post" action="adminUI.php">
<div class="form-group">
<label for="store">Store Number: </label>
<input type="text" class="form-control" name="store" id="store" />
<label for="pass">Password:</label>
<input type="text" class="form-control" name="pass" id="pass" />
<input type="submit" value="Login" />
</div>
</form>
Your $store variable is being overwritten by your foreach:
foreach($storesArray as $store)
You must use a different name for that foreach, something like:
foreach($storesArray as $store2)

Strange validation error for form

The error i got was:
Notice: Undefined index: visible in C:\xampp\htdocs\introducingphp\includes\validation_function.php on line 22
It should not happen since i already instantiated all the variables including visible
Validation_function.php
<?php
$errors = array();
function fieldname_as_text($fieldname) {
$fieldname = str_replace("_", " ", $fieldname);
$fieldname = ucfirst($fieldname);
return $fieldname;
}
// * presence
// use trim() so empty spaces don't count
// use === to avoid false positives
// empty() would consider "0" to be empty
function has_presence($value) {
return isset($value) && $value !== "";
}
function validate_presences($required_fields) {
global $errors;
foreach($required_fields as $field) {
$value = trim($_POST[$field]);
if (!has_presence($value)) {
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
// * string length
// max length
function has_max_length($value, $max) {
return strlen($value) <= $max;
}
function validate_max_lengths($fields_with_max_lengths) {
global $errors;
// Expects an assoc. array
foreach($fields_with_max_lengths as $field => $max) {
$value = trim($_POST[$field]);
if (!has_max_length($value, $max)) {
$errors[$field] = fieldname_as_text($field) . " is too long";
}
}
}
// * inclusion in a set
function has_inclusion_in($value, $set) {
return in_array($value, $set);
}
?>
new_page.php (the page that has the one-page submit form that does validation)
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/db_connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php require_once("includes/validation_function.php"); ?>
<?php find_selected_page(); ?>
<?php
// Can't add a new page unless there is a subject as a parent
if (!$current_subject) {
// subject ID was missing or invalid or
//subject couldn't be found in database
redirect_to("manage_content.php");
}
?>
<?php
if (isset($_POST['submit'])) {
// Process the form
//validations
$required_fields = array("menu_name", "position", "visible",
"content");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 60);
validate_max_lengths($fields_with_max_lengths);
if (empty($errors)) {
// perform Create
//add the subject_id
$subject_id = $current_subject["id"];
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
//escape content
$content = mysql_prep($_POST["content"]);
// 2. Perform database query
$query .= "INSERT INTO pages (";
$query .= " subject_id, menu_name, position, visible,
content";
$query .= ") VALUES (";
$query .= " {$subject_id}, '{$menu_name}', {$position},
{$visible}, '{$content}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result ) {
// Success
$_SESSION["message"] = "Page Created.";
redirect_to("manage_content.php?subject=" .
urlencode($current_subject["id"]));
}else {
// Failure
$_SESSION["message"] = "Page creation failed.";
}
}
} else {
// This is probably a GET request
} // End: If(isset($_POST['submit']))
?>
<?php $layout_context = "admin"; ?>
<?php include("header.php"); ?>
<div id="main">
<div id="navigation">
<?php echo navigation($current_subject, $current_page); ?>
</div>
<div id="page">
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
<h2>Create Page</h2>
<form action="new_page.php?subject=<?php echo
urlencode($current_subject["id"]); ?>" method="post">
<p>Menu name:
<input type="text" name="menu_name" value="" />
</p>
<p>Position:
<select name="position">
<?php
$page_set =
find_all_pages_for_subject($current_subject["id"], false);
$page_count = mysqli_num_rows($page_set);
for($count=1; $count <= ($page_count + 1); $count++) {
echo "<option value=\"{$count}\">{$count}</option>";
}
?>
</select>
</p>
<p>Visible
<input type="radio" name="visible" value="0" /> NO
<input type="radio" name="visible" value="1" /> Yes
</p>
<p>Content:<br />
<textarea name="content" rows="20" cols="80"></textarea>
</p>
<input type="submit" name="submit" value="Create Page" />
</form>
<br />
<a href="manage_content.php?subject=<?php echo
urlencode($current_subject["id"]); ?>">Cancel</a>
</div>
</div>
<?php include("includes/footer.php"); ?>
You probably have a typo on the input HTML field. You can use:
if (isset($_POST[$field])) {
on validate_presences() function to be sure that the value exists.
When you try to do trim($_POST[$field]); you assume, the field exists in the $_POST array - for visible it does not in this case. You could move the trim to has_presence()
function has_presence($value) {
return isset($value) && trim($value) !== "";
}
function validate_presences($required_fields) {
global $errors;
foreach($required_fields as $field) {
if (!has_presence($value)) {
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
Now when you will only have the trim if the variable exists.
Okay, marking the radio check button makes it work now. Thanks for all your inputs guys. It has helped me a great deal.

Categories