codeIgniter how can i create session into login controller - mysql

How can I create login session name? I tried but it didn't work for me.
Here is my code:
loginModel
public function login($name, $pass){
$this->db->select("username", "password");
$this->db->from("users");
$this->db->where("username", $name);
$this->db->where("password", $pass);
$query = $this->db->get();
$ret = $query->row();
if($query->num_rows() == 1){
return true;
}
else {
return false ;
}
}
loginControler;
public function checkLogin(){
$this->form_validation->set_rules("username", "Username", "required");
$this->form_validation->set_rules("password", "Password", "required");
if($this->form_validation->run() == false){
$this->load->view("login");
}
else {
redirect("SiteCont/index");
}
}
public function verifyUser(){
$name = $this->input->post("username");
$pass = $this->input->post("password");
$this->load->model("loginModel");
if($this->loginModel->login($name, $pass)){
return true;
}
else {
$this->form_validation->set_message("verifyUser", "geçersiz kullanıcı adı veya porala");
return false;
}
Only I need something ;
if($this->session->userdata('name')){
//show dashboard
}
else {
//show login
}
in the login page.

loginModel
public function login($name, $pass){
$this->db->select("username", "password");
$this->db->from("users");
$this->db->where("username", $name);
$this->db->where("password", $pass);
$query = $this->db->get();
$ret = $query->row();
if($query->num_rows() == 1){
//set the session data (you can add more values to array according to your needs)
$data = array(
'user_id' => $ret->user_id, //change your actual user id field
);
$this->session->set_userdata($data);
//set the session data
return true;
}
else {
return false ;
}
}
To check
if($this->session->userdata('user_id')){
//redirect to dashboard
}
else{
//redirect to login
}
This will work properly. Change name of variables according to your needs.

Related

Connecting Application to Mysql Database CPanel, utf8_general_ci

I have software or an application on a MacBook called Nano Hotel Booking, I am trying to connect it to my CPanel server but I get the error Unknown collation: 'utf8_general_ci'. Everything else works besides the error for UTF8 I have checked the setting on the Data
`
<?php
$database_host = "localhost";
$database_user = "12345";
$database_password = "12345";
$database_name = "12345";
$db_access_token = "";
$return_format = (isset($_REQUEST['return_format'])) ? $_REQUEST['return_format'] : 'json';
$res = array('success' => true, 'errormsg' => '', 'data' => '');
try
{
$filename = (isset($_FILES['uploadedfile']['name'])) ? $_FILES['uploadedfile']['name'] : '';
if(trim($filename))
{
$upload_dir = 'data';
$ar = explode('___', basename($_FILES['uploadedfile']['name']));
if(sizeof($ar) != 3) throw new Exception('Bad file name '.basename($_FILES['uploadedfile']['name']));
if(!trim($ar[0]) || !trim($ar[1])) throw new Exception('Bad folder name');
if(!trim($ar[2])) throw new Exception('Bad file name '.$ar[2]);
if(!file_exists($upload_dir))
{
if(!#mkdir($upload_dir, 0777)) throw new Exception('Can not create folder '.$upload_dir);
}
$upload_dir .= '/'.trim($ar[0]);
if(!file_exists($upload_dir))
{
if(!#mkdir($upload_dir, 0777)) throw new Exception('Can not create folder '.$upload_dir);
}
$upload_dir .= '/'.trim($ar[1]);
if(!file_exists($upload_dir))
{
if(!#mkdir($upload_dir, 0777)) throw new Exception('Can not create folder '.$upload_dir);
}
$upload_dir .= '/'.trim($ar[2]);
if(file_exists($upload_dir)) #unlink($upload_dir);
if(!move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $upload_dir))
throw new Exception('Can not upload file '.$upload_dir);
} else
{
$params = $_REQUEST;
$action = (isset($_REQUEST['action'])) ? $_REQUEST['action'] : '';
if(!$action) throw new Exception('Action not found.');
$enc_request = (isset($_REQUEST['enc_request'])) ? $_REQUEST['enc_request'] : '';
$params = #json_decode(trim(base64_decode($enc_request)));
if($params == false) throw new Exception('Request is not valid');
$params = (array)$params;
// Connect user
$s_key = '';
if(isset($params['db_access_token']))
{
$s_key = $params['db_access_token'];
}
if($s_key !== $db_access_token) throw new Exception('Bad user.');
$controller = new apiController($database_host, $database_user, $database_password, $database_name);
if($action === 'checkconnection') throw new Exception('ok');
if(method_exists($controller, $action) === false ) throw new Exception('Action is invalid.');
$controller->request = $params;
$res['data'] = $controller->$action();
}
} catch(Exception $e)
{
$res['success'] = 0;
$res['errormsg'] = $e->getMessage();
}
switch($return_format)
{
case 'json': print(json_encode($res)); exit; break;
case 'xml': print(arrayToXml($res)); exit; break;
}
class apiController
{
public $request = array();
protected $conn;
public function __construct($host = '', $user = '', $psw = '', $dbname = '')
{
#$this->conn = mysqli_connect($host, $user, $psw, $dbname);
if(!$this->conn) throw new Exception(mysqli_connect_errno().' '.mysqli_connect_error());
#mysqli_query($this->conn, "SET CHARACTER SET utf8_general_ci");
#mysqli_query($this->conn, "set names utf8");
#mysqli_query($this->conn, "SET collation_connection = utf8_general_ci");
}
public function select()
{
$sql = (isset($this->request['sql'])) ? $this->request['sql'] : '';
$array = array();
if(is_array($sql))
{
foreach($sql as $value)
{
$arr = $this->selectOne($value);
$array[] = (sizeof($arr) > 0) ? $arr[0] : array();
}
} else
{
$array = $this->selectOne($sql);
}
if($this->conn) #mysqli_close($this->conn);
return $array;
}
public function selectOne($sql = '')
{
if(!trim($sql)) throw new Exception('Empty sql.');
$offset = (isset($this->request['offset'])) ? (int)$this->request['offset'] : 0;
$limit = (isset($this->request['limit'])) ? (int)$this->request['limit'] : 20;
if($limit) $sql .= ' LIMIT '.$offset.', '.$limit;
$result = mysqli_query($this->conn, $sql);
if(!$result) throw new Exception(mysqli_error($this->conn));
$rows = mysqli_num_rows($result);
if($rows <= 0)
{
mysqli_free_result($result);
mysqli_close($this->conn);
return array();
}
$array = array();
$fields = mysqli_num_fields($result);
while ($row = mysqli_fetch_row($result))
{
$onerow = array();
for ($i=0; $i < $fields; $i++) $onerow[] = $row[$i];
$array[] = $onerow;
}
mysqli_free_result($result);
return $array;
}
public function execute()
{
$sql = (isset($this->request['sql'])) ? $this->request['sql'] : '';
$array = array();
if(is_array($sql))
{
foreach($sql as $value)
{
$array = $this->executeOne($value);
}
} else
{
$array = $this->executeOne($sql);
}
if($this->conn) #mysqli_close($this->conn);
return $array;
}
public function executeOne($sql = '')
{
$lastid = '';
$result = null;
if(!trim($sql)) throw new Exception('Empty sql.');
$str = strtoupper($sql);
if((strpos($str, 'CREATE') !== false)
&& (strpos($str, 'TABLE') !== false)
)
{
$sql = str_ireplace ('AUTOINCREMENT' , 'AUTO_INCREMENT', $sql);
$sql = str_ireplace ('COLLATE NOCASE' , '', $sql);
}
if((strpos($str, 'INSERT') !== false)
&& (strpos($str, 'INTO') !== false)
&& (strpos($str, 'VALUES') !== false)
&& (strpos($str, '(0,') !== false)
)
{
$result = mysqli_query($this->conn, 'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"');
if(!$result) throw new Exception(mysqli_error($this->conn));
}
$result = mysqli_query($this->conn, $sql);
if(!$result) throw new Exception(mysqli_error($this->conn));
if((strpos($str, 'INSERT') !== false)
&& (strpos($str, 'INTO') !== false)
&& (strpos($str, 'VALUES') !== false)
)
{
$result = mysqli_query($this->conn, 'SELECT LAST_INSERT_ID()');
if (mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_row($result))
{
$lastid = $row[0];
break;
}
}
}
$array = array();
$array[] = array($lastid);
if($result !== true) mysqli_free_result($result);
return $array;
}
public function getFieldFromSql($sql = '', $def = '')
{
if(!$sql) return $def;
$this->request['offset'] = 0;
$this->request['limit'] = 1;
$arr = $this->selectOne($sql);
if(sizeof($arr) == 0) return $def;
if(sizeof($arr[0]) == 0) return $def;
return $arr[0][0];
}
public function getFieldsFromSql($sql = '', $def = '')
{
if(!$sql) return $def;
$this->request['offset'] = 0;
$this->request['limit'] = 1;
$arr = $this->selectOne($sql);
if(sizeof($arr) == 0) return $def;
return $arr[0];
}
public function getArrayFromSql($sql = '')
{
if(!$sql) return array();
$this->request['offset'] = 0;
$this->request['limit'] = 100000;
return $this->selectOne($sql);
}
public function runScript()
{
$php = (isset($this->request['sql'])) ? trim($this->request['sql']) : '';
$nano = $this;
$php_res = #eval($php);
if($this->conn) #mysqli_close($this->conn);
if(is_array($php_res))
{
if(sizeof($php_res) > 0)
{
if(is_array($php_res[0])) return $php_res;
}
return array($php_res);
}
$array = array();
$array[] = array($php_res);
return $array;
}
}
?>
`
I have tried changing the UTF8 to almost everything else.

Send mail on actionCreate

I have a system that works by the intranet and I would like to know how best to send an alert email in actionCreate?
I did as below, the email is sent correctly, but if the internet is offline an unfriendly error message appears.
public function actionCreate()
{
$model = new Todolist();
if ($model->load(Yii::$app->request->post())) {
$file = $model->uploadImage();
if ($model->save()) {
if ($file !== false) {
$idfolder = Yii::$app->user->identity->id;
if(!is_dir(\Yii::$app->getModule('task')->params['taskAttachment'])){
mkdir(\Yii::$app->getModule('task')->params['taskAttachment'], 0777, true);
}
$path = $model->getImageFile();
$file->saveAs($path);
}
Yii::$app->session->setFlash("task-success", "Atividade incluída com sucesso!");
\Yii::$app->mailer->compose('#app/mail/task')
->setFrom('intranet#sicoobcrediriodoce.com.br')
->setTo($model->responsible->email)
->setSubject(Yii::$app->params['appname'].' - '.\Yii::$app->getModule('task')->params['taskModuleName']. ' - Nova Tarefa : #'. $model->id)
->send();
return $this->redirect(['index']);
} else {
// error in saving model
}
}
return $this->render('create', [
'model' => $model,
]);
}
Try this (don't save model if email not sended)
public function actionCreate()
{
$model = new Todolist();
if ($model->load(Yii::$app->request->post())) {
$file = $model->uploadImage();
$transaction = $model->getDb()->beginTransaction();
try{
if ($model->save()) {
if ($file !== false) {
$idfolder = Yii::$app->user->identity->id;
if(!is_dir(\Yii::$app->getModule('task')->params['taskAttachment'])){
mkdir(\Yii::$app->getModule('task')->params['taskAttachment'], 0777, true);
}
$path = $model->getImageFile();
$file->saveAs($path);
}
Yii::$app->session->setFlash("task-success", "Atividade incluída com sucesso!");
\Yii::$app->mailer->compose('#app/mail/task')
->setFrom('intranet#sicoobcrediriodoce.com.br')
->setTo($model->responsible->email)
->setSubject(Yii::$app->params['appname'].' - '.\Yii::$app->getModule('task')->params['taskModuleName']. ' - Nova Tarefa : #'. $model->id)
->send();
return $this->redirect(['index']);
}
}
catch(Exception $e)
{
$transaction->rollBack();
throwe $e;
//unlik savedFile if exist
}
}
return $this->render('create', [
'model' => $model,
]);
}
or use mail queue to save mail in databases and send via cron

Cannot pass whitespace separated value to Query

My project with PHP and MySql stuck here ,
$searchfriend = "Jason";
$status = query("SELECT status FROM users.profile WHERE name = ?" , $searchfriend );
The above statement works quite well.
When I replace,
$searchfriend = "Jason R"
It's not working. What is the solution ?
I have created my own query function with PDO.
function query()
{
$sql = func_get_arg(0);
$parameters = array_slice(func_get_args(), 1);
static $handle;
if (!isset($handle))
{
try
{
$handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER, USERNAME, PASSWORD);
$handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (Exception $e)
{
trigger_error($e->getMessage(), E_USER_ERROR);
exit;
}
}
$statement = $handle->prepare($sql);
if ($statement === false)
{
trigger_error($handle->errorInfo()[2], E_USER_ERROR);
exit;
}
$results = $statement->execute($parameters);
if ($results !== false)
{
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
else
{
return false;
}
}

Codeigniter Cannot save hashed password to database

I cannot save hashed password to my 'users' table, but if it's not hashed, the password saved. Can everybody help me?
Controller
public function add()
{
$this->data['title'] = 'add new user';
$this->data['subview'] = 'admin/user/add';
$validate = $this->user->validate;
$this->form_validation->set_rules($validate);
if ($this->form_validation->run() == TRUE){
$this->user->insert(array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'password' => $this->user->hash($this->input->post('password'))
));
$this->session->set_flashdata('message', msg_success('Data Saved'));
redirect('admin/user', 'refresh');
}
$this->load->view('admin/_layout_main', $this->data);
}
my Hash function in user_model
public function hash($string)
{
return hash('md5', $string . config_item('encryption_key'));
}
What's wrong with my code, or is there any other way to do it without any library? or How you do it basically to do this using codeigniter? Thanks
EDIT
this is my insert function from MY_Model
public function insert($data, $skip_validation = FALSE)
{
if ($skip_validation === FALSE)
{
$data = $this->validate($data);
}
if ($data !== FALSE)
{
$data = $this->trigger('before_create', $data);
$this->_database->insert($this->_table, $data);
$insert_id = $this->_database->insert_id();
$this->trigger('after_create', $insert_id);
return $insert_id;
}
else
{
return FALSE;
}
}
Im using Jamie Rumbelow Base Model for my base model, and I have follow his tutorial for insert into database

Kohana 3.2 select issue

I have table with 'servers' name in my db. So when I want to add there some data with that code it's just ok:
public function action_add()
{
$serverGameId = (int)Arr::get($_POST, 'serverGameId', '');
$newServerName = Arr::get($_POST, 'newServerName', '');
try
{
$server = new Model_Server();
$server->Name = $newServerName;
$server->GameId = $serverGameId;
$server->save();
}
catch(ORM_Validation_Exception $e)
{
echo json_encode(array("success" => false, "errors" => $e->errors('validation')));
return false;
}
$this->request->headers['Content-Type'] = 'application/json';
echo json_encode(array("success" => true, "serverId" => $server->Id));
return true;
}
Here is a model:
class Model_Server extends ORM {
protected $_table_name = 'servers';
public function rules()
{
return array(
'Name' => array(
array('not_empty'),
)
);
}
}
But I have problem when I try to select it from the table:
public function action_servers()
{
$gameId = (int)Arr::get($_POST, 'gameId', '');
if($gameId == -1) return false;
try
{
$servers = ORM::factory('server')
->where('GameId', '=', $gameId)
->find_all();
}
catch(ORM_Validation_Exception $e)
{
echo json_encode(array("success" => false, "errors" => $e->errors('validation')));
return false;
}
$this->request->headers['Content-Type'] = 'application/json';
echo json_encode(array("success" => true, "servers" => $servers, "gameId" => $gameId));
return true;
}
I already try to solve problem with change code inside of try block on:
$servers = DB::select('servers')->where('GameId', '=', $gameId);
Even when I try just get all my servers from db without '->where' it's doesn't work.
Any ideas?
Try print_r($servers); inside try block to see what you get from model.
And $servers is some class with results - use foreach to get result (one by one)
$results = array();
foreach($servers as $row) {
//echo $row->Name;
$results[] = $row->Name;
}
Or
$results = array();
foreach($servers as $row) {
//echo $row->as_array();
$results[] = $row->as_array();
}