Last active
April 29, 2017 14:49
-
-
Save raikk/40a82dd51c3b16fcfb2c3d45da07d25a to your computer and use it in GitHub Desktop.
Core PHP oop login register and crud operation including file upload
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class DbHandler { | |
private $conn; | |
// private $token; | |
public function __construct($DB_con) { | |
$this->conn = $DB_con; | |
} | |
public function createUser($name, $email, $password, $repassword, $utoken) { | |
// $error = array(); | |
$error = ''; | |
$required_fields = array($name, $email, $password, $repassword); | |
$fields = array_map('trim', $required_fields); | |
if (in_array(null, $fields)) { | |
$error = 'Fields marked with an asterisk are required'; | |
} | |
else if(!$this->valid_token($utoken)){ | |
$error = "Invalid Token...!!!"; | |
} | |
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) { | |
$error = 'Please enter a valid email address !'; | |
} | |
else if(strlen($password) < 6){ | |
$error = "Password must be atleast 6 characters"; | |
} | |
else if($password !== $repassword){ | |
$error = "Password do n\' t match!!"; | |
} | |
else{ | |
$name = escape($name); | |
$email = escape($email); | |
$password_hash = escape($password); | |
// First check if user already existed in db | |
if (!$this->isUserExists($name, $email)) { | |
// Generating password hash | |
$password_hash = password_hash($password, PASSWORD_DEFAULT, ['cost'=>12]); | |
// insert query | |
$stmt = $this->conn->prepare("INSERT INTO users(name, email, password_hash, status) values(:name, :email, :password_hash, 1)"); | |
//$stmt->bind_param("ssss", $name, $email, $password_hash); | |
$result = $stmt->execute(array(':name' => $name,':email' => $email,':password_hash' => $password_hash));; | |
//$stmt->close(); | |
// Check for successful insertion | |
if ($result) { | |
// User successfully inserted | |
return 6; | |
} else { | |
// Failed to create user | |
$error = "Failed to create user"; | |
} | |
} else { | |
// User with same email already existed in the db | |
$error = "User or Email already taken"; | |
} | |
} | |
return $error; | |
} | |
public function login($name, $email, $password, $utoken) | |
{ | |
$error = ''; | |
$required_fields = array($name, $email, $password); | |
$fields = array_map('trim', $required_fields); | |
if (in_array(null, $fields)) { | |
$error = 'Username/email or password required!!!'; | |
} | |
else if(!$this->valid_token($utoken)){ | |
$error = "Invalid Token...!!!"; | |
} | |
else if(!$this->isUserExists($name, $email)){ | |
$error = "User not exist, you havn't registered yet!!!"; | |
} | |
else{ | |
$name = escape($name); | |
$email = escape($email); | |
try | |
{ | |
$stmt = $this->conn->prepare("SELECT * FROM users WHERE name=:name OR email=:mail LIMIT 1"); | |
$stmt->execute(array(':name'=>$name, ':mail'=>$email)); | |
$userRow=$stmt->fetch(PDO::FETCH_ASSOC); | |
if($stmt->rowCount() > 0) | |
{ | |
if(password_verify($password, $userRow['password_hash'])) | |
{ | |
$_SESSION['user_session'] = $userRow['id']; | |
$_SESSION['user_name'] = $userRow['name']; | |
return true; | |
} | |
else | |
{ | |
$error = "Incorrect credential"; | |
} | |
} | |
} | |
catch(PDOException $e) | |
{ | |
echo $e->getMessage(); | |
} | |
} | |
return $error; | |
} | |
public function is_timeout() | |
{ | |
$logLength = 1800; # time in seconds :: 1800 = 30 minutes | |
$ctime = strtotime("now"); # Create a time from a string | |
# If no session time is created, create one | |
if(!isset($_SESSION['sessionX'])){ | |
# create session time | |
$_SESSION['sessionX'] = $ctime; | |
}else{ | |
# Check if they have exceded the time limit of inactivity | |
if(((strtotime("now") - $_SESSION['sessionX']) > $logLength) && $this->is_loggedin()){ | |
return true; | |
}else{ | |
# If they have not exceded the time limit of inactivity, keep them logged in | |
$_SESSION['sessionX'] = $ctime; | |
} | |
} | |
} | |
public function is_loggedin() | |
{ | |
if(isset($_SESSION['user_session'])) | |
{ | |
return true; | |
} | |
} | |
public function redirect($url) | |
{ | |
header("Location: $url"); | |
} | |
public function logout() | |
{ | |
session_start(); | |
session_destroy(); | |
unset($_SESSION['user_session']); | |
unset($_SESSION['user_name']); | |
return true; | |
} | |
private function isUserExists($name, $email) { | |
$stmt = $this->conn->prepare("SELECT id from users WHERE name = :name OR email=:mail"); | |
//$stmt->bind_param("s", $email); | |
$stmt->execute(array(':name' => $name,':mail' => $email)); | |
//$stmt->bind_result(); | |
$num_rows = $stmt->rowCount(); | |
//$stmt->close(); | |
return $num_rows > 0; | |
} | |
public function valid_token($token){ | |
//if(!isset($_SESSION['token']) || $token != $_SESSION['token']) | |
return isset($_SESSION['token']) && $token == $_SESSION['token']; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require 'functions.php'; | |
session_start(); | |
$DB_host = "localhost"; | |
$DB_user = "root"; | |
$DB_pass = ""; | |
$DB_name = "task_manager"; | |
try | |
{ | |
$DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass); | |
$DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
} | |
catch(PDOException $e) | |
{ | |
echo $e->getMessage(); | |
} | |
include_once 'Db_handlers.php'; | |
include_once 'userstask.php'; | |
$db = new DbHandler($DB_con); | |
$task = new Usertask($DB_con); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function escape($data){ | |
return htmlentities(strip_tags($data)); | |
} | |
?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once 'DBConfigs.php'; | |
if($db->is_loggedin() == NULL) | |
{ | |
$db->redirect('login.php'); | |
} | |
if($db->is_timeout()) | |
{ | |
$res = $db->logout(); | |
if($res == true){ | |
$db->redirect('login.php'); | |
} | |
} | |
//User input | |
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1; | |
$perPage = isset($_GET['per-page']) && $_GET['per-page'] <= 50 ? (int)$_GET['per-page'] : 3; | |
$rec = $task->showTask($_SESSION['user_session'], $page, $perPage); | |
//var_dump($db->is_loggedin()); | |
if(isset($_GET['edit'])){ | |
$ures = $task->getUpdateDetails($_GET['edit'], $_SESSION['user_session']); | |
//$uimg = $ures['image']; | |
$utask = $ures['task']; | |
} | |
if(isset($_GET['delete'])){ | |
$dres = $task->deleteTask($_GET['delete'], $_SESSION['user_session']); | |
if($dres){ | |
//echo "deleted...."; | |
header("Location: home.php"); | |
echo "DELETED....."; | |
} | |
else{ | |
echo $dres; | |
} | |
} | |
if(isset($_POST['Add'])){ | |
$res = $task->inserstTask($_POST['task'], $_POST['user_id'], $_FILES, $_POST['token']); | |
if($res == 6){ | |
//header("Location: home.php"); | |
echo "Inserted......"; | |
} | |
else{ | |
echo $res; | |
} | |
} | |
if(isset($_POST['cancel'])){ | |
$db->redirect('home.php'); | |
} | |
if(isset($_POST['Edit'])){ | |
$etask = (isset($_POST['task'])?$_POST['task']:$ures['task']); | |
$eimg = (isset($_FILES)?$_FILES:'uploads/'.$ures['image']); | |
//print_r($eimg); | |
$eres = $task->updateTask($etask, $_POST['id'], $_SESSION['user_session'], $eimg, $_POST['token']); | |
if($eres == 6){ | |
header("Location: home.php"); | |
} | |
else{ | |
echo $eres; | |
} | |
} | |
//print_r($ures['image']); | |
$token = $_SESSION['token'] = md5(uniqid(mt_rand(),true)); | |
?> | |
<h1>Welcome <?php echo isset($_SESSION['user_name']) ? "".$_SESSION['user_name']."": "no session";?></h1> | |
<div class="right"> | |
<label><a href="logout.php"><i class="glyphicon glyphicon-log-out"></i>logout</a></label> | |
</div> | |
<form method="POST" action="" enctype="multipart/form-data"> | |
<table> | |
<tr><td>Task:</td><td><input type="text" value="<?php echo isset($_GET['edit']) ? $utask : ''; ?>" name="task"></td></tr> | |
<tr><td><input type="file" name="image" id="fileToUpload" accept="image/*"></td><td> | |
<?php | |
if(isset($ures['image'])){ | |
?> | |
<img src="uploads/<?=$ures['image'];?>" alt="Smiley face" height="100" width="100"> | |
<?php | |
} | |
?></td></tr> | |
<input type="hidden" name="token" value="<?=$token;?>"> | |
<input type="hidden" name="id" value="<?=isset($_GET['edit'])?$_GET['edit']:'';?>"> | |
<input type="hidden" name="user_id" value="<?=$_SESSION['user_session'];?>"> | |
<tr><td><input type="submit" name="<?=(isset($_GET['edit'])?'Edit': 'Add');?>" value="<?=(isset($_GET['edit'])?'Edit': 'Add ');?> Task"></td><td> | |
<?=isset($_GET['edit'])?"<input type='submit' name='cancel' value='cancel'>":"";?> | |
</td></tr> | |
</table> | |
</form> | |
<?php | |
if($rec === 0){ | |
echo "no Tasks!!! Insert Task"; | |
} | |
else{ | |
//print_r($rec); | |
?> | |
<table> | |
<thead> | |
<tr> | |
<th>Sl No.</th> | |
<th>Task</th> | |
<th>Image</th> | |
<th>Edit </th> | |
<th>Delete </th> | |
</tr> | |
</thead> | |
<tbody> | |
<?php | |
//print_r($rec); | |
$no = 1; | |
$numItems = count($rec); | |
$num2 = $numItems-1; | |
$i = 0; | |
echo $rec['total']; | |
foreach($rec as $r){ | |
if( ++$i === $num2) { | |
break; | |
} | |
$no++; | |
?> | |
<tr> | |
<td><?=$no;?></td> | |
<td><?php echo $r['task']; ?></td> | |
<td><img src="uploads/<?=$r['image'];?>" alt="Smiley face" height="100" width="100"></td> | |
<td><a href="home.php?edit=<?=$r['id'];?>">Edit</a></td> | |
<td><a href="home.php?delete=<?=$r['id'];?>">Delete</a></td> | |
</tr> | |
<?php | |
} | |
?> | |
</tbody> | |
</table> | |
<?php for($x =1; $x <= $rec['pages']; $x++):?> | |
<a href="?page=<?php echo $x; ?>&per-page=<?php echo $perPage; ?>"<?php if($page === $x) {echo 'class="selected"';}?>><?php echo $x; ?></a> | |
<?php endfor; | |
} | |
?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once 'DBConfigs.php'; | |
if($db->is_loggedin()) | |
{ | |
$db->redirect('home.php'); | |
} | |
if(isset($_POST['submit'])){ | |
$res = $db->login($_POST['username'], $_POST['username'], $_POST['password'], $_POST['token']); | |
//print_r($res); | |
//print_r($_SESSION['token']); | |
if($res == 1){ | |
header("Location: home.php"); | |
} | |
else{ | |
echo $res; | |
//echo $db->is_loggedin(); | |
//header("Location: home.php"); | |
} | |
} | |
$token = $_SESSION['token'] = md5(uniqid(mt_rand(),true)); | |
?> | |
<form method="POST" action=""> | |
<table> | |
<tr><td>Name:</td><td><input type="username" name="username"></td></tr> | |
<tr><td>Password:</td><td><input type="password" name="password"></td></tr> | |
<input type="hidden" name="token" value="<?=$token;?>"> | |
<input type="submit" name="submit" value="submit"> | |
</table> | |
</form> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once 'DBConfigs.php'; | |
$res = $db->logout(); | |
if($res == true){ | |
$db->redirect('login.php'); | |
} | |
?> | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//error_reporting(0); | |
require_once 'DBConfigs.php'; | |
function display($result){ | |
if($result === 6){ | |
$display1 ='<div class="alert alert-success">Registered Successfully</div>'; | |
return $display1; | |
} | |
$display ='<div class="alert alert-danger">'.$result.'</div>'; | |
return $display; | |
} | |
$result = ''; | |
if(isset($_POST["submit"])){ | |
$res = $db->createUser($_POST["name"], $_POST["email"], $_POST["password"], $_POST["re-password"], $_POST['token']); | |
//print_r($res); | |
} | |
$token = $_SESSION['token'] = md5(uniqid(mt_rand(),true)); | |
?> | |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<title>Bootstrap Example</title> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> | |
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> | |
<script src="func.js"></script> | |
<link rel="stylesheet" href="style.css"> | |
</head> | |
<body> | |
<!-- | |
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post"> | |
<div class="field"> | |
<label for="name">Name:</label> | |
<input type="text" name="name" value="" /> | |
</div> | |
<div class="field"> | |
<label for="email">Email:</label> | |
<input type="text" name="email" value="" /> | |
</div> | |
<div class="field"> | |
<label for="password">Password:</label> | |
<input type="password" name="password" value="" /> | |
</div> | |
<div class="field"> | |
<label for="repassword">Re-Password:</label> | |
<input type="password" name="re-password" value="" /> | |
</div> | |
<input type="hidden" name="token" value="<?=$token;?>"/> | |
<input type="submit" name="submit" value="submit" /> | |
</form>--> | |
<div class="container"> | |
<div class="row"> | |
<div class="col-md-6 col-md-offset-3"> | |
<div class="panel panel-login"> | |
<div class="panel-heading"> | |
<div class="row"> | |
<!--<div class="col-xs-6"> | |
<a href="#" class="active" id="login-form-link">Login</a> | |
</div>--> | |
<div class="col-xs-6"> | |
<a href="#" class="active" id="register-form-link">Register</a> | |
</div> | |
</div> | |
<hr> | |
</div> | |
<div class="panel-body"> | |
<div class="row"> | |
<div class="col-lg-12"><!-- | |
<form id="login-form" action="http://phpoll.com/login/process" method="post" role="form" style="display: block;"> | |
<div class="form-group"> | |
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value=""> | |
</div> | |
<div class="form-group"> | |
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password"> | |
</div> | |
<div class="form-group text-center"> | |
<input type="checkbox" tabindex="3" class="" name="remember" id="remember"> | |
<label for="remember"> Remember Me</label> | |
</div> | |
<div class="form-group"> | |
<div class="row"> | |
<div class="col-sm-6 col-sm-offset-3"> | |
<input type="submit" name="login-submit" id="login-submit" tabindex="4" class="form-control btn btn-login" value="Log In"> | |
</div> | |
</div> | |
</div> | |
<div class="form-group"> | |
<div class="row"> | |
<div class="col-lg-12"> | |
<div class="text-center"> | |
<a href="http://phpoll.com/recover" tabindex="5" class="forgot-password">Forgot Password?</a> | |
</div> | |
</div> | |
</div> | |
</div> | |
</form>--> | |
<form id="register-form" action="<?=$_SERVER['PHP_SELF'];?>" method="post" role="form" > | |
<?=(isset($res) ? display($res):'' )?> | |
<div class="form-group"> | |
*<input type="text" name="name" id="username" tabindex="1" class="form-control" placeholder="Username" value=""> | |
</div> | |
<div class="form-group"> | |
*<input type="email" name="email" id="email" tabindex="1" class="form-control" placeholder="Email Address" value=""> | |
</div> | |
<div class="form-group"> | |
*<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password"> | |
</div> | |
<div class="form-group"> | |
*<input type="password" name="re-password" id="confirm-password" tabindex="2" class="form-control" placeholder="Confirm Password"> | |
</div> | |
<div class="form-group"> | |
<div class="row"> | |
<div class="col-sm-6 col-sm-offset-3"> | |
<input type="hidden" name="token" value="<?=$token;?>"/> | |
<input type="submit" name="submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Register Now"> | |
</div> | |
</div> | |
</div> | |
</form> | |
</div> | |
</div> | |
</div> | |
</div> | |
</div> | |
</div> | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
body { | |
padding-top: 90px; | |
} | |
.panel-login { | |
border-color: #ccc; | |
-webkit-box-shadow: 0px 2px 3px 0px rgba(0,0,0,0.2); | |
-moz-box-shadow: 0px 2px 3px 0px rgba(0,0,0,0.2); | |
box-shadow: 0px 2px 3px 0px rgba(0,0,0,0.2); | |
} | |
.panel-login>.panel-heading { | |
color: #00415d; | |
background-color: #fff; | |
border-color: #fff; | |
text-align:center; | |
} | |
.panel-login>.panel-heading a{ | |
text-decoration: none; | |
color: #666; | |
font-weight: bold; | |
font-size: 15px; | |
-webkit-transition: all 0.1s linear; | |
-moz-transition: all 0.1s linear; | |
transition: all 0.1s linear; | |
} | |
.panel-login>.panel-heading a.active{ | |
color: #029f5b; | |
font-size: 18px; | |
} | |
.panel-login>.panel-heading hr{ | |
margin-top: 10px; | |
margin-bottom: 0px; | |
clear: both; | |
border: 0; | |
height: 1px; | |
background-image: -webkit-linear-gradient(left,rgba(0, 0, 0, 0),rgba(0, 0, 0, 0.15),rgba(0, 0, 0, 0)); | |
background-image: -moz-linear-gradient(left,rgba(0,0,0,0),rgba(0,0,0,0.15),rgba(0,0,0,0)); | |
background-image: -ms-linear-gradient(left,rgba(0,0,0,0),rgba(0,0,0,0.15),rgba(0,0,0,0)); | |
background-image: -o-linear-gradient(left,rgba(0,0,0,0),rgba(0,0,0,0.15),rgba(0,0,0,0)); | |
} | |
.panel-login input[type="text"],.panel-login input[type="email"],.panel-login input[type="password"] { | |
height: 45px; | |
border: 1px solid #ddd; | |
font-size: 16px; | |
-webkit-transition: all 0.1s linear; | |
-moz-transition: all 0.1s linear; | |
transition: all 0.1s linear; | |
} | |
.panel-login input:hover, | |
.panel-login input:focus { | |
outline:none; | |
-webkit-box-shadow: none; | |
-moz-box-shadow: none; | |
box-shadow: none; | |
border-color: #ccc; | |
} | |
.btn-login { | |
background-color: #59B2E0; | |
outline: none; | |
color: #fff; | |
font-size: 14px; | |
height: auto; | |
font-weight: normal; | |
padding: 14px 0; | |
text-transform: uppercase; | |
border-color: #59B2E6; | |
} | |
.btn-login:hover, | |
.btn-login:focus { | |
color: #fff; | |
background-color: #53A3CD; | |
border-color: #53A3CD; | |
} | |
.forgot-password { | |
text-decoration: underline; | |
color: #888; | |
} | |
.forgot-password:hover, | |
.forgot-password:focus { | |
text-decoration: underline; | |
color: #666; | |
} | |
.btn-register { | |
background-color: #1CB94E; | |
outline: none; | |
color: #fff; | |
font-size: 14px; | |
height: auto; | |
font-weight: normal; | |
padding: 14px 0; | |
text-transform: uppercase; | |
border-color: #1CB94A; | |
} | |
.btn-register:hover, | |
.btn-register:focus { | |
color: #fff; | |
background-color: #1CA347; | |
border-color: #1CA347; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Usertask { | |
private $conn; | |
// private $token; | |
public function __construct($DB_task) { | |
$this->conn = $DB_task; | |
} | |
public function inserstTask($task, $user_id, $image, $token){ | |
// $error = array(); | |
$error = ''; | |
$required_fields = array($task, $user_id); | |
$fields = array_map('trim', $required_fields); | |
if (in_array(null, $fields)) { | |
$error = 'Fields marked with an asterisk are required'; | |
} | |
else if(!$this->valid_token($token)){ | |
$error = "Invalid Token...!!!"; | |
} | |
else if(empty($image['image']['name'])) | |
{ | |
$error = "Error no file selected"; | |
} | |
else{ | |
if(!empty($image['image']['name'])){ | |
$files = $image['image']; | |
$uploaded = array(); | |
$failed = array(); | |
$allowed = array('png', 'jpg'); | |
$file_tmp = $files['tmp_name']; | |
$file_size = $files['size']; | |
$file_error = $files['error']; | |
$file_ext = explode('.', $files['name']); | |
$file_ext = strtolower(end($file_ext)); | |
if(in_array($file_ext, $allowed)){ | |
if($file_error === 0){ | |
if($file_size <= 2097152){ | |
$file_name_new = uniqid('', true) . '.' . $file_ext; | |
$file_destination = 'uploads/'.$file_name_new; | |
if(move_uploaded_file($file_tmp, $file_destination)){ | |
//$uploaded = $file_destination; | |
$task = escape($task); | |
$user_id = escape($user_id); | |
//$image = escape($image); | |
$stmt = $this->conn->prepare("INSERT INTO tasks(task, user_id, image) values(:task, :user_id, :image)"); | |
//$stmt->bind_param("ssss", $name, $email, $password_hash); | |
$result = $stmt->execute(array(':task' => $task,':user_id' => $user_id,':image' => $file_name_new)); | |
//$stmt->close(); | |
// Check for successful insertion | |
if ($result) { | |
// User successfully inserted | |
return 6; | |
} else { | |
// Failed to create user | |
$error = "Failed to create task..."; | |
} | |
}else{ | |
$error = $files['name']." failed to upload."; | |
} | |
}else{ | |
$error = $files['name']." is too large."; | |
} | |
}else{ | |
$error = $files['name']." errored with code {$file_error}."; | |
} | |
}else{ | |
$error = $files['name']." file extension '{$file_ext}' is not allowed."; | |
} | |
} | |
} | |
return $error; | |
} | |
public function valid_token($token){ | |
//if(!isset($_SESSION['token']) || $token != $_SESSION['token']) | |
return isset($_SESSION['token']) && $token == $_SESSION['token']; | |
} | |
public function updateTask($task, $id, $user_id, $image, $token){ | |
// $error = array(); | |
$error = ''; | |
$required_fields = array($task, $user_id); | |
$fields = array_map('trim', $required_fields); | |
if (in_array(null, $fields)) { | |
$error = 'Fields marked with an asterisk are required'; | |
} | |
else if(!$this->valid_token($token)){ | |
$error = "Invalid Token...!!!"; | |
} | |
else{ | |
if(!empty($image['image']['name'])){ | |
$st = $this->conn->prepare("SELECT image FROM tasks WHERE id=:id"); | |
$st->execute(array(':id' => $id)); | |
$iresult = $st->fetch(); | |
$ires = unlink('uploads/'.$iresult['image']); | |
$files = $image['image']; | |
$uploaded = array(); | |
$failed = array(); | |
$allowed = array('png', 'jpg'); | |
$file_tmp = $files['tmp_name']; | |
$file_size = $files['size']; | |
$file_error = $files['error']; | |
$file_ext = explode('.', $files['name']); | |
$file_ext = strtolower(end($file_ext)); | |
if(in_array($file_ext, $allowed)){ | |
if($file_error === 0){ | |
if($file_size <= 2097152){ | |
$file_name_new = uniqid('', true) . '.' . $file_ext; | |
$file_destination = 'uploads/'.$file_name_new; | |
if(move_uploaded_file($file_tmp, $file_destination)){ | |
//$uploaded = $file_destination; | |
$task = escape($task); | |
$user_id = escape($user_id); | |
$stmt = $this->conn->prepare('UPDATE tasks SET task=:task, image=:image WHERE id=:id AND user_id=:user_id'); | |
$result = $stmt->execute(array(':task' => $task,':user_id' => $user_id,':image' => $file_name_new, ':id' => $id)); | |
// Check for successful insertion | |
if ($result) { | |
// User successfully inserted | |
return 6; | |
} else { | |
// Failed to create user | |
$error = "Failed to create task..."; | |
} | |
}else{ | |
$error = $files['name']." failed to upload."; | |
} | |
}else{ | |
$error = $files['name']." is too large."; | |
} | |
}else{ | |
$error = $files['name']." errored with code {$file_error}."; | |
} | |
}else{ | |
$error = $files['name']." file extension '{$file_ext}' is not allowed."; | |
} | |
} | |
else{ | |
//user are not updating image | |
$task = escape($task); | |
$user_id = escape($user_id); | |
$stmt = $this->conn->prepare('UPDATE tasks SET task=:task WHERE id=:id AND user_id=:user_id'); | |
$result = $stmt->execute(array(':task' => $task,':user_id' => $user_id, ':id' => $id)); | |
// Check for successful insertion | |
if ($result) { | |
// User successfully inserted | |
return 6; | |
} else { | |
// Failed to create user | |
$error = "Failed to create task..."; | |
} | |
} | |
} | |
return $error; | |
} | |
public function deleteTask($id, $user_id){ | |
$error = ''; | |
$del = $this->conn->prepare("SELECT image FROM tasks WHERE id=:id AND user_id = :user_id"); | |
$del->execute(array(':id'=>$id, ':user_id' => $user_id)); | |
$result = $del->fetch(); | |
$res = unlink('uploads/'.$result['image']); | |
if($res){ | |
$sql = "DELETE FROM tasks WHERE id = :id AND user_id = :user_id"; | |
$stmt = $this->conn->prepare($sql); | |
$result = $stmt->execute(array(':id'=> $id,':user_id' => $user_id)); | |
// Check for successful insertion | |
if ($result) { | |
// User successfully inserted | |
return true; | |
} else { | |
// Failed to create user | |
$error = "Failed to delete task..."; | |
} | |
} | |
else{ | |
$error = "No such file"; | |
} | |
return $error; | |
} | |
public function getUpdateDetails($id, $user_id){ | |
$result = $this->conn->prepare("SELECT * FROM tasks WHERE id=:id AND user_id=:user_id"); | |
$result->execute(array(':id'=>$id, ':user_id'=>$user_id)); | |
$res = $result->fetch(PDO::FETCH_ASSOC); | |
return $res; | |
} | |
public function showTask($user_id, $page, $perPage){ | |
$records = array(); | |
//Positioning | |
$start = ($page > 1) ? ($page*$perPage) - $perPage : 0; | |
//Query | |
$result = $this->conn->prepare(" | |
SELECT SQL_CALC_FOUND_ROWS id, task, image | |
FROM tasks WHERE user_id=:user_id | |
LIMIT {$start}, {$perPage} | |
"); | |
$result->execute(array(':user_id' => $user_id)); | |
$result = $result->fetchAll(PDO::FETCH_ASSOC); | |
//Pages | |
$total = $this->conn->query("SELECT FOUND_ROWS() as total")->fetch()['total']; | |
$pages = ceil($total / $perPage); | |
$result['pages'] = $pages; | |
$result['total'] = $total; | |
if($result){ | |
return $result; | |
} | |
else{ | |
return 0; | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment