Query not working on PostgreSQL database - php

I have a query where I check if a user it's already stored on the database, but the problem it's that it's perfectly working on MYSQL but not on PostgreSQL where I need it..what can I do? The steps are: user register for an account. If it already exists in the database it returns an message, if no, send an email where he needs to confirm the registration. The confirmation doesn't work(the adress where the user can enter and activate his account).
This is the confirmation code(email_verification.php):
<?php
ob_start();
$success = false;
// Errors reporting, used if needed
error_reporting(E_ALL);
ini_set('display_errors', 'on');
// General configuration like base, used if needed
include_once ('include/config.inc.php');
// Mail functions
include_once ('include/mail.functions.php');
// Start session if needed
session_start();
// DBConn
include_once ('class/DB/DBConn.includeall.php');
$db = new DBConn(NULL);
// Includere clasa login
require_once ('class/class_login.php');
// Set up current language
$lang = "ro";
$_SESSION[PRE.'lang'] = $lang;
$message = '';
if(isset($_GET['cod_activare']))
{
$query = "
SELECT * FROM tregister
WHERE cod_activare = :cod_activare
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':cod_activare' => $_GET['cod_activare']
)
);
$no_of_row = $statement->rowCount();
if($no_of_row > 0)
{
$result = $statement->fetchAll();
foreach($result as $row)
{
if($row['email_status'] == '0')
{
$update_query = "
UPDATE tregister
SET email_status = '1'
WHERE id = '".$row['id']."'
";
$statement = $connect->prepare($update_query);
$statement->execute();
$sub_result = $statement->fetchAll();
if(isset($sub_result))
{
$message = '<label class="text-success">Email verificat cu success! <br />Poti efectua checkin-ul aici - Efectueaza check-in</label>';
}
}
else
{
$message = '<label class="text-info">Adresa de mail deja verificata</label>';
}
}
}
else
{
$message = '<label class="text-danger">Link invalid</label>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Hotel Amethyst</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<h3><?php echo $message; ?></h3>
</div>
</body>
</html>
<?php
ob_end_flush();
?>
And here it's the register.php:
<?php
ob_start();
$success = false;
// Errors reporting, used if needed
error_reporting(E_ALL);
ini_set('display_errors', 'on');
// General configuration like base, used if needed
include_once ('include/config.inc.php');
// Mail functions
include_once ('include/mail.functions.php');
// Start session if needed
session_start();
// DBConn
include_once ('class/DB/DBConn.includeall.php');
$db = new DBConn(NULL);
// Includere clasa login
require_once ('class/class_login.php');
// Set up current language
$lang = "ro";
$_SESSION[PRE.'lang'] = $lang;
$access = 0;
// Check if the cookie for "remember me" exists
if(isset($cookie_name))
{
if(isset($_COOKIE[$cookie_name]))
{
parse_str($_COOKIE[$cookie_name]);
$login = new Login($db);
if ($login->_checkLogin($usr, $hash) == true)
{
$access = 1;
}
}
}
$user = (isset($_POST['user']) && !empty($_POST['user'])) ? $_POST['user'] : "" ;
$email = (isset($_POST['email']) && !empty($_POST['email'])) ? $_POST['email'] : "" ;
$cod_activare = md5(rand());
$email_status=0;
$db = pg_connect("host=local port=5432 dbname=login_robinson user=robinson password=123");
$query = "INSERT INTO tregister(nume,email,cod_activare,email_status) VALUES ('$user','$email','$cod_activare','$email_status')";
$result = pg_query($query);
if(isset($_POST['submit'])){
$base_url = "http://local/login-robinson/www/";
$mail_body = "
Buna ziua ".$_POST['user'].",\n
Multumim pentru inregistrare. Te rog deschide acest link pentru a incepe procesul de check-in - ".$base_url."email_verification.php?activation_code=".$cod_activare."
Cu stima,\nHotel Amethyst
";
$from = 'Activare rezervare';
$subject = 'De pe site';
if (mail ($email, $subject, $mail_body, $from)){
echo "<script>
alert('Utilizator inregistrat cu success! Te rog verifica adresa de mail!');
window.location.href='login.php';
</script>";
}
else{
echo "<script>
alert('S-a produs o eroare! Te rog mai verifica odata formularul!');
</script>";
}
if($user !=''&& $email !='')
{
$success=true;
}
}
?>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<!-- <base href="http://dev.incorom.local/ticketing/www/login.php" /> -->
<title>Inregistrare</title>
<?php
include('include/links.php');
include('include/scripts.php');
?>
</head>
<body style="display: block !important;" ng-cloak="" ng-class="{ 'layout-fixed' : app.layout.isFixed, 'layout-boxed' : app.layout.isBoxed, 'layout-dock' : app.layout.isDocked, 'layout-material': app.layout.isMaterial, 'aside-offscreen' : app.sidebar.isOffscreen, 'aside-mini' : app.sidebar.isMini, 'aside-right' : app.sidebar.isRight, 'footer-hidden': app.footer.hidden, 'in-app': !$state.includes('page')}">
<div class="animated fadeOutZoom">
<div class="container container-sm animated fadeInDown">
<div class="center-block mt-xl">
<img src="images/logo_iconlab.png" alt="Image" class="center-block img-rounded">
<div class="panel">
<div class="panel-body">
<p class="pv text-bold">Date de inregistrare rezervare</p>
<form class="mb-lg" method="post" action="register.php" id="form">
<div class="row">
<div class="col-md-12">
<div class="form-group has-feedback mb">
<input type="text" placeholder="Nume" autocomplete="off" class="form-control" name="user" id="user" required /><span class="fa fa-envelope form-control-feedback text-muted"/></span>
</div><br>
<div class="form-group has-feedback mb">
<input type="email" placeholder="Adresa de mail" autocomplete="off" class="form-control" name="email" id="email" required /><span class="fa fa-envelope form-control-feedback text-muted"/></span>
</div><br>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-block btn-info btnblue mb" name="submit">Inregistrare</button>
</div>
</div>
<div id="main_area" class="row-fluid">
</form>
</div>
</div>
</div>
</div>
</body>
</html>
<?php
ob_end_flush();
?>
The registration works OK but I can register the same email for an infinite number of times.

Related

My GET requests re-direct correctly locally but not online.. :/

======== Projet_4/index.php =======
<?php
session_start();
include('./mvc/controller/main.php');
if(!empty($_POST['pseudo']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['rePassword'])){
$userAction = new ActionsUser();
$userAction->subscribeUser();
} elseif(!empty($_POST['pseudo']) && !empty($_POST['password'])){
$userAction = new ActionsUser();
$_SESSION['pseudoUser'] = $_POST['pseudo'];
$userAction->connectionUser();
}
if(isset($_POST['disconnectUser'])){
?><script>alert('Vous êtes déconnecté !')</script><?php
$disconnect = new ActionsUser();
$disconnect->disconnectUser();
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Bungee" rel="stylesheet">
<script crossorigin="anonymous" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" href="css/phoneFormat.css">
<link rel="stylesheet" href="css/tabFormat.css">
<link rel="stylesheet" href="css/desktopFormat.css">
<title>Blog du Writer</title>
</head>
<body>
<header>
<h1 id="titleBody">Le Wr!ter</h1>
<p>
<img src="img/writer.png" id="iconTitle" title="Contactez-nous !" alt="iconTitle">
</p>
</header>
<nav>
<ul id="menu">
<li class="li1">Accueil</li>
<li class="li2">Inscription</li>
<li class="li3">Livre d'or</li>
<li class="li4">Chat</li>
<li class="li5">Contact</li>
</ul>
</nav>
<?php
include('./mvc/view/slider.php');
displaySlider();
?>
<?php
include('./mvc/view/displayForm.php');
displayForm();
?>
</body>
</html>
======= Projet_4/mvc/model/checkForm.php ========
<?php
class CheckForm {
public function memberExistInscription(){
include('./mvc/model/databaseConnect.php');
if (!empty($_POST['pseudo']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['rePassword']) ) {
$pseudo = htmlspecialchars($_POST['pseudo']);
$email = htmlspecialchars($_POST['email']);
$req = $dbh->prepare("SELECT * FROM users
WHERE email= ? OR pseudo= ?
");
$req->execute(array($email, $pseudo));
$users = $req->fetch();
if($users['pseudo'] == $pseudo){
$this->errorSubscribeExistPseudo();
}elseif ($users['email'] == $email){
$this->errorSubscribeExistEmail();
}
elseif ($users['pseudo'] == null && $users['email'] == null){
$this->insertUser();
}
} else{
$this->errorUser();
}
}
public function memberExistConnection(){
include('./mvc/model/databaseConnect.php');
if (!empty($_POST['pseudo']) && !empty($_POST['password'])){
$pseudo = htmlspecialchars($_POST['pseudo']);
$passwordSalt = htmlspecialchars(hash("sha512" ,"azzjfa".$pseudo."15z1d"));
$password = htmlspecialchars(hash("sha256" , $_POST['password'].$passwordSalt));
$req = $dbh->prepare("SELECT * FROM users
WHERE pseudo= ?
");
$req->execute(array($pseudo));
$users = $req->fetch();
if($users['pseudo'] == $pseudo && $users['password'] == $password){
if(!isset($_COOKIE['pseudo'])){
$timerCookie = 60 ;
setcookie('pseudo', "a48f484fz" , $timerCookie);
}
$this->connectUser();
}elseif($pseudo == $users['pseudo'] && $users['password'] != $password){
$this->errorUserPassword();
}elseif ($users['pseudo'] == null){
$this->errorUser();
}
}
}
public function insertUser(){
include('./mvc/model/databaseConnect.php');
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip_address = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else {
$ip_address = $_SERVER['REMOTE_ADDR'];
}
if (!empty($_POST['pseudo']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['rePassword']) ){
$pseudo = htmlspecialchars($_POST['pseudo']);
$email = htmlspecialchars($_POST['email']);
$passwordSalt = hash("sha512" , "azzjfa".$pseudo."15z1d");
$password = hash("sha256" , $_POST['password'].$passwordSalt);
$req = $dbh->prepare("INSERT INTO users (pseudo , email , password, passwordSalt, ip)
VALUES (? , ? , ?, ?, ?)");
$req->execute(array($pseudo , $email , $password, $passwordSalt, $ip_address));
}
}
public function connectUser(){
header("Location:./?success=1");
exit();
}
public function disconnectUser(){
header("Location:./?disconnectUser=1");
exit();
}
public function errorUser(){
header("Location:./?error=1");
exit();
}
public function errorUserPassword(){
header("Location:./?errorPassword=1");
exit();
}
public function errorSubscribeExistPseudo(){
header("Location:./?errorSubscribeExistPseudo=1");
exit();
}
public function errorSubscribeExistEmail(){
header("Location:./?errorSubscribeExistEmail=1");
exit();
}
}
====== Projet_4/mvc/view/displayForm.php =====
<?php
function displayForm(){
echo '
<div id="containerForms">
<form action="./index.php" method="POST" id="formSubscribe">
<h3 id="titleSubscription">S\'inscrire</h3><br>
<div class="col">
<label for="inputText">Pseudo</label>
<input type="text" name="pseudo" class="form-control" placeholder="Pseudo" required>
</div><br>
<div class="col">
<label for="exampleFormControlInput1">E-mail</label>
<input type="email" name="email" class="form-control" id="exampleFormControlInput1" placeholder="nom#exemple.com">
</div><br>
<div class="col">
<label for="inputPassword4">Mot de passe</label>
<input type="password" name="password" class="form-control" id="inputPassword1" placeholder="Mot de passe" required>
</div><br>
<div class="col">
<label for="inputPassword4">Saisir à nouveau</label>
<input type="password" name="rePassword" class="form-control" id="inputPassword2" placeholder="Mot de passe" required>
</div><br>
<div class="col">
<button type="submit" class="btn btn-outline-success" id="submitSubscribe">Envoyer</button>
</div>
</form>
<form action="./index.php" id="formConnection" method="POST">
<h3 id="titleConnection">Se connecter</h3><br>
<div class="col">
<label for="exampleFormControlInput1">Pseudo</label>
<input type="text" name="pseudo" class="form-control" id="exampleFormControlInput2" placeholder="KevinDu12 ">
</div><br>
<div class="col">
<label for="inputPassword4">Mot de passe</label>
<input type="password" name="password" class="form-control" id="inputPassword3" placeholder="Mot de passe" required>
</div><br>
<div class="col">
<button type="submit" class="btn btn-outline-success">Envoyer</button>
</div>
</form>
</div>
';
}
?>
=========== Projet_4/mvc/model/error.php ============
<?php
if(isset($_GET['error'])){
echo '<script>alert("Erreur");</script>';
echo 'Error';
} elseif(isset($_GET['success'])){
include ('./mvc/view/redirectUser.php');
$userSpace = new RedirectUser();
$userSpace->checkAccessUser();
echo '<script>alert("Success");</script>';
echo 'Success';
} elseif(isset($_GET['errorPassword'])){
echo '<script>alert("Mauvais mot de passe");</script>';
echo 'Error Password';
} elseif(isset($_GET['errorSubscribeExistPseudo'])){
echo '<script>alert("Désolé ce Pseudo est déja pris.. :/");</script>';
echo 'Error Subscribe Exist Pseudo';
} elseif(isset($_GET['errorSubscribeExistEmail'])){
echo '<script>alert("Désolé cette Email est déja prise.. :/");</script>';
echo 'Error Subscribe Exist Email';
}
======= Projet_4/mvc/model/databaseConnect.php =====
<?php
$host_name = 'localhost';
$database = 'writer';
$user_name = 'root';
$password = '';
try {
$dbh = new PDO("mysql:host=$host_name; dbname=$database;", $user_name, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Erreur!: " . $e->getMessage() . "<br/>";
die();
}
============ Projet_4/mvc/controller/actionsUser.php
<?php
class ActionsUser {
public function receptForm(){
include('./mvc/model/checkForm.php');
}
public function subscribeUser(){
$this->receptForm();
$subscribeUser = new CheckForm();
$subscribeUser->memberExistInscription();
}
public function connectionUser(){
$this->receptForm();
$connect = new CheckForm();
$connect->memberExistConnection();
}
public function disconnectUser(){
$this->receptForm();
$disconnect = new CheckForm();
$disconnect->disconnectUser();
}
}
?>
=========== My Problem ========
Once the project hosted online I am not directed to the pages I want, my requests in GET do not appear in the URL, no alert () while local no worries .. My code is not not commented and being beginner nothing is very organized, it's a bit bazard .. against the database works locally and online .. Registration and connection work .. I do not understand at all .. O__ *

Auto fill-in data (input field) from MySQL Database in PHP (PDO)

This post contains:
3 PHP pages
MySQL table picture
Picture of the form
As the title says, I need to extract some information from my database.
So far I have the following:
Index page <-- You need to login here with a personal code. (this is where I get the 'Session username' from that already works at the contact page)
Config page <-- Used for database access and all
Contact page <-- In here I would like to auto fill-in the users data.
Database table consists of:
username; email; realName (and some other stuff I don't need here)
So in the contact page I would like to see the following:
Card number = username (this already works)
Auto fill-in: realName and email according to the username.
Maybe it is possible to extract the info when logging in and storing these in the POST variable already? But how?
Database:
Table I need to use: 'members'
The info given by the user himself/herself = username
The info I need to auto fill-in = realName and email
Picture of the form.
The email should be in the SESSION statement, so I can send a confirmation email to the person, and the realName should be entered from the database.
These are the files currently running:
config.php:
<?php
ob_start();
session_start();
//set timezone
date_default_timezone_set('Europe/Brussels');
//database credentials
define('DBHOST','*****');
define('DBUSER','*****');
define('DBPASS','*****');
define('DBNAME','*****');
//application address
define('DIR','http://*****/');
define('SITEEMAIL','noreply#*****');
try {
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
//include the user class, pass in the database connection
include('classes/user.php');
include('classes/phpmailer/mail.php');
$user = new User($db);
?>
contact form:
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: index.php'); }
?>
<html>
<head>
<title>*****</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!--[if lte IE 8]><script src="siteassets/assets/js/ie/shiv.js"></script><![endif]-->
<link rel="stylesheet" href="siteassets/assets/css/main.css" />
<!--[if lte IE 8]><link rel="stylesheet" href="siteassets/assets/css/ie8.css" /><![endif]-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#next').keyup(calculate);
$('#nextprice').keyup(calculate);
$('#current').keyup(calculate);
$('#currentprice').keyup(calculate);
});
function calculate(e)
{
$('#total').val($('#next').val() * $('#nextprice').val() + $('#current').val() * $('#currentprice').val());
}
</script>
</head>
<body class="landing">
<div id="page-wrapper">
<!-- Header -->
<header id="header" class="alt">
<nav id="nav">
<ul>
<li>
Menu
<ul>
<li>Current Project</li>
<li>Next Projects</li>
<li>Previous Projects</li>
<li>Who are we?</li>
</ul>
</li>
<li>contact</li>
<li><a href='logout.php'>Logout</a></li>
</ul>
</nav>
</header>
<!-- Banner -->
<section id="banner">
<h2>*****</h2>
<p>Slogan.</p>
<ul class="actions">
<li>Current Project</li>
<li>Next Projects</li>
<li>Previous Projects</li>
<li>Who are we?</li>
<li>contact</li>
</ul>
</section>
<!-- Main -->
<section id="main" class="container 75%">
<div class="box">
<?
if($_SERVER['REQUEST_METHOD']=="POST")
{
if(strlen($_POST['name2']) == 0)
{ $error_msg ="- Please, provide us with your name.<br>"; }
if(!empty($error_msg))
{
//Een van de velden werd niet goed ingevuld
echo "<b>Your message can't be send due to the following reason:</b> <br><br>";
echo $error_msg;
echo "<br>Click on <a href='javascript:history.back(1)'>Go back</a> and provide us with your name.<br><br>";
}
else
{
$recipient = "*****";
$subject = "******";
$header = "From: " . $_POST['uwemail'] . "\n";
$mail_body = "Contact script werd op " . date("d-m-Y") . " om " . date("H:i") . " uur uitgevoerd.\n";
$mail_body .= "*****:\n\n";
$mail_body .= "Naam: " . $_POST['name2'] . "\n";
$mail_body .= "Met als kaartnummer: " . $_POST['card2'] . "\n";
$mail_body .= "******: " . $_POST['current2'] . "\n";
$mail_body .= "******: " . $_POST['next2'] . "\n";
$mail_body .= "Voor een totaal van: " . $_POST['total2'] . " EUR.";
$mail_body .= "\n\n -- ****** --";
mail($recipient, $subject, $mail_body, $header);
print "<b>IMPORTANT!</b>";
print "<br><br>*****.";
print "<br><br>***** ";
print $_POST['total2'];
print " *****";
print "<br><br>******.";
print "<br><br>******";
}
}
else
{
?>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="POST" name="contact">
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
Your personal card number
<input type="text" name="card2" id="card" value="<?php echo $_SESSION['username']; ?>" placeholder="Card Number" readonly/>
</div>
<div class="6u 12u(mobilep)">
Please enter your name. (mandatory)
<input type="text" name="name2" id="name" value="" placeholder="Your name" />
</div>
</div>
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
Current Project - Smile
<input type="text" name="current2" id="current" value="" placeholder="How many tickets would you like?" />
</div>
<div class="6u 12u(mobilep)">
Next Project - Sand
<input type="text" name="next2" id="next" value="" placeholder="How many tickets would you like?" />
</div>
</div>
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
<input type="hidden" id="currentprice" value="10" />
</div>
<div class="6u 12u(mobilep)">
<input type="hidden" id="nextprice" value="10" placeholder="" />
</div>
</div>
<div class="6u 12u(mobile)">
<input name="uwemail" placeholder="Email" type="hidden" value="******"/>
</div>
<div class="6u 12u(mobilep)">
Total price.(In EUR)
<input type="text" name="total2" id="total" value="" readonly/>
</div>
</div>
<div class="row uniform">
<div class="12u">
<ul class="actions align-center">
<li><input type="submit" name="submit"value="Place Order"/></li>
</ul>
</div>
</div>
</form>
<?php
}
?>
</div>
</section>
<!-- Footer -->
<footer id="footer">
<ul class="copyright">
<li>© *****. All rights reserved.</li>
</ul>
</footer>
</div>
<!-- Scripts -->
<script src="siteassets/assets/js/jquery.min.js"></script>
<script src="siteassets/assets/js/jquery.dropotron.min.js"></script>
<script src="siteassets/assets/js/jquery.scrollgress.min.js"></script>
<script src="siteassets/assets/js/skel.min.js"></script>
<script src="siteassets/assets/js/util.js"></script>
<!--[if lte IE 8]><script src="siteassets/assets/js/ie/respond.min.js"></script><![endif]-->
<script src="siteassets/assets/js/main.js"></script>
</body>
</html>
Index page (where they have to login)
<?php
//include config
require_once('includes/config.php');
//process login form if submitted
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($user->login($username,$password)){
$_SESSION['username'] = $username;
header('Location: home.php');
exit;
} else {
$error[] = 'Wrong username or password or your account has not been activated.';
}
}//end if submit
?>
<html>
<head>
<title>******</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!--[if lte IE 8]><script src="assets/js/iv.js"></script><! [endif]-->
<link rel="stylesheet" href="assets/css/main.css" />
<!--[if lte IE 9]><link rel="stylesheet" href="assets/css/ie9.css" /><![endif]-->
<!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie8.css" /><![endif]-->
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /> </noscript>
</head>
<body class="is-loading">
<!-- Wrapper -->
<div id="wrapper">
<!-- Main -->
<section id="main">
<header>
<h1>*****</h1>
<h1><a style="color:#FFFFFF" href=''>Coming soon.</a></h1>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<form role="form" method="post" action="" autocomplete="off">
<h2>Please Login</h2>
<hr>
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<p class="bg-danger">'.$error.'</p>';
}
}
if(isset($_GET['action'])){
//check the action
switch ($_GET['action']) {
case 'active':
echo "<h2 class='bg-success'>Your account is now active you may now log in.</h2>";
break;
case 'reset':
echo "<h2 class='bg-success'>Please contact us for a new card.</h2>";
break;
case 'resetAccount':
echo "<h2 class='bg-success'>Password changed, you may now login.</h2>";
break;
}
}
?>
<div class="form-group">
<input type="text" name="username" id="username" class="form-control input-lg" placeholder="Enter your card number" value=" <?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1">
</div>
<div class="form-group">
<input type="hidden" name="password" id="password" class="form-control input-lg" value="*****" tabindex="3" >
</div>
<br>
<div class="row">
<div class="col-xs-6 col-md-6"><input type="submit" name="submit" value="Login" class="btn btn-primary btn-block btn-lg" tabindex="5"></div>
</div>
<hr>
<div class="row">
<div class="col-xs-9 col-sm-9 col-md-9">
<a style="color:#FFFFFF" href='*********'>Lost your card? Contact us.</a>
</div>
</div>
</form>
</div>
</div>
</div>
</header>
</section>
<!-- Footer -->
<footer id="footer">
<ul class="copyright">
<li>© ******</li>
</ul>
</footer>
</div>
<!-- Scripts -->
<!--[if lte IE 8]><script src="assets/js/respond.min.js"> </script><![endif]-->
<script>
if ('addEventListener' in window) {
window.addEventListener('load', function() { document.body.className = document.body.className.replace(/\bis-loading\b/, ''); });
document.body.className += (navigator.userAgent.match(/(MSIE|rv:11\.0)/) ? ' is-ie' : '');
}
</script>
</body>
</html>
EDITED: Since you're having user class (ex.: $user->is_logged_in()), then in $_POST[] method ignore $_POST['name2'] as it can still be changed through DEV tools and instead change that to $_SESSION['username'] (assuming that's the correct value). This is much more reliable than using HTML field. The PHP part (of query) also differs because you're using PDO, but I can't help with this one because I'm using mysqli_, not PDO (sorry about that), but query itself should be similar.
"SELECT * FROM `table` WHERE `number` = '".$_POST['number']."'"
But don't forget to escape your string, otherwise, your query is vulnerable.
I fixed the problem.
In the user.php file I had everything prepared already, but I just didn't understand why it didn't work.
Turned out to be a simple error XD
<?php
include('password.php');
class User extends Password{
private $_db;
function __construct($db){
parent::__construct();
$this->_db = $db;
}
private function get_user_hash($username){
try {
$stmt = $this->_db->prepare('SELECT password, username, memberID, realName, email FROM members WHERE username = :username AND active="Yes" ');
$stmt->execute(array('username' => $username));
return $stmt->fetch();
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
}
public function login($username,$password){
$row = $this->get_user_hash($username);
if($this->password_verify($password,$row['password']) == 1){
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['memberID'] = $row['memberID'];
$_SESSION['realName'] = $row['realName'];
$_SESSION['email'] = $row['email'];
return true;
}
}
public function logout(){
session_destroy();
}
public function is_logged_in(){
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
return true;
}
}
}
?>
I forgot to add the realName and email to this line: (idiot me :D)
$stmt = $this->_db->prepare('SELECT password, username, memberID, realName, email FROM members WHERE username = :username AND active="Yes" ');

Get an error by changing a post, simple php editing form

All!
I can't change a form I did. It is all functional on my local host (xampp), but when I upload on the server it doesn't work.
I believe the problem is on the query, the login is working so I don't think it's on the database connection or getting the data. I'm getting that $message = "Error"; on the else statement, I also tried to see if the form is working by echo $titulli; echo $content; and it worked.
I user error_reporting(E_ALL & ~E_NOTICE); and got these problems (warnings)
Warning: mysql_real_escape_string(): Access denied for user 'user'#'localhost' (using password: NO) in /home/user/public_html/test/admin-panel.php on line 12
Warning: mysql_real_escape_string(): A link to the server could not be established in /home/user/public_html/test/admin-panel.php on line 12
here is the code:
<?php
session_start();
include_once 'db_connect.php';
if(isset($_GET['update']) && !empty($_GET['update'])) {
$id = $_GET['update'];
$id1=mysql_real_escape_string($id);
$titulli = $_POST['emri'.$id];
$titulli1=mysql_real_escape_string($titulli);
$content = $_POST['mesazhi'.$id];
$content1=mysql_real_escape_string($content);
$date = date('Y-m-d H:i:s');
// echo $titulli;
// echo $content;
$update_query = "UPDATE `lagjja`.`content` SET `titulli` = '".$titulli1."', `content` = '".$content1."', `data` = '".$date."' WHERE `content` .`ID` = ".$id1;
$update_result = $mysqli->query($update_query);
if($update_result) {
$message = "you changes succeeded";
}
else {
$message = "Error";
//header('Location: index.php');
//die();
}
}
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
}
else {
echo "Your are not connected return to homepage";
header('refresh:2; url=index.php') ;
die();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta charset="UTF-8" />
<?php include("head.php"); ?>
<link rel="stylesheet" type="text/css" href="css/style-adminpanel.css" />
<title>Admin-panel</title>
</head>
<body>
<header>
logout
return to page
<div id="logo-postimit">
<img src="img/logo.png" alt="logo" />
</div>
</header>
<?php if(isset($message) && !empty($message) ) {
echo $message
;} ?>
<div id="content">
<div id="krejt-forma">
<?php
$post_query = "SELECT * FROM content LIMIT 3";
$result = $mysqli->query($post_query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) : ?>
<!-- 2.1 tab section -->
<div class="forma col-lg-4 col-md-4 col-sm-12">
<form id="post-forma" role="form" name="post-form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>?update=<?php echo $row['ID']; ?>">
<input class=" form-control titulli col-lg-12 col-md-12 col-sm-12 col-xs-12" type="text" id="emri<?php echo $row['ID']; ?>" name="emri<?php echo $row['ID']; ?>" placeholder="Titulli" value="<?php echo $row['titulli']; ?>" />
<textarea class="form-control mesazhi col-lg-12 col-md-12 col-sm-12 col-xs-12" rows="12" id="mesazhi<?php echo $row['ID']; ?>" name="mesazhi<?php echo $row['ID']; ?>" placeholder="Mesazhi"><?php echo $row['content']; ?></textarea>
<input type="submit" class="submit col-lg-12 col-md-12 col-sm-12 col-xs-12 btn btn-primary" value="Posto"></input>
</form>
</div>
<?php endwhile; } ?>
</div>
</div>
<!-- 3.0 footer -->
<footer>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<!-- bootstrap implimentation -->
<script src="js/bootstrap.min.js"></script>
<!-- bootstrap imp end -->
<script src="js/navbar.js"></script>
</footer>
</body>
</html>
here is my db_conncet.php
<?php
/* Konfigurimi i databazes */
define("HOST", "localhost");
define("USER", "laxhja");
define("PASSWORD", "password");
define("DATABASE", "laxhja");
define("SECURE", FALSE);
/* Lidhja me databaze */
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$mysqli->set_charset("utf8");
?>
<input type="submit" class="submit col-lg-12 col-md-12 col-sm-12 col-xs-12 btn btn-primary" value="Posto"></input>
change this to
<input type="submit" name="update" class="submit col-lg-12 col-md-12 col-sm-12 col-xs-12 btn btn-primary" value="Posto"/>
I solved it by changing the mysql_real_escape_string to mysqli_real_escape_string gave it 2 parameters and its done.
like this.
$con = mysqli_connect("localhost", "laxhja", "password", "laxhja");
if(isset($_GET['update']) && !empty($_GET['update'])) {
$id = $_GET['update'];
$id1=mysqli_real_escape_string($con, $id);
$titulli = $_POST['emri'.$id];
$titulli1=mysqli_real_escape_string($con, $titulli);
$content = $_POST['mesazhi'.$id];
$content1=mysqli_real_escape_string($con, $content);
$date = date('Y-m-d H:i:s');...

Updation not working using pdo in php

I am trying to update the records but the update query is not working for some reason.It is deleting and inserting fine but somehow the update doesn't work.I have checked various questions but couldn't find the answer.I have checked the data inserted in the query and its fine too.This is my code.
<?php
require 'database.php';
$ido = 0;
if ( !empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$descError = null;
$priceError = null;
// keep track post values
$name = $_POST['name'];
$desc = $_POST['desc'];
$price = $_POST['price'];
// validate input
$valid = true;
if (empty($name)) {
$nameError = 'Please enter Name';
$valid = false;
}
if (empty($desc)) {
$descError = 'Please enter Valid descriptin';
$valid = false;
}
if (empty($price) || filter_var($price, FILTER_VALIDATE_INT) == false) {
$priceError = 'Please enter a valid price';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE Items SET I_name = ? , I_desc = ? ,I_price = ? WHERE I_id = ?"; <---This is the update query part
$q = $pdo->prepare($sql);
$q->execute(array($name,$desc,$price,$ido)); <---these are the values inserted
Database::disconnect();
header("Location: index.php");
}
}
else {
echo $ido;
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM Items where I_id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($ido));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['I_name'];
$desc = $data['I_desc'];
$price = $data['I_price'];
Database::disconnect();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update Items</h3>
</div>
<form class="form-horizontal" action="update_items.php" method="post">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Name</label>
<div class="controls">
<input name="name" type="text" placeholder="Item Name" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($descError)?'error':'';?>">
<label class="control-label">Description</label>
<div class="controls">
<input name="desc" type="text" placeholder="Item Description" value="<?php echo !empty($desc)?$desc:'';?>">
<?php if (!empty($descError)): ?>
<span class="help-inline"><?php echo $descError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($priceError)?'error':'';?>">
<label class="control-label">Price</label>
<div class="controls">
<input name="price" type="text" placeholder="Item Price" value="<? php echo !empty($price)?$price:'';?>">
<?php if (!empty($priceError)): ?>
<span class="help-inline"><?php echo $priceError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Create</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
This is your form:
<form class="form-horizontal" action="update_items.php" method="post">
^ nothing here
As you can see you are posting and there is no query variable after the url you are posting to.
Then you check for the ID:
$ido = 0;
if (!empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
$ido will remain 0 as there is no $_GET['id'].
You can either modify your form to add the ID or add a hidden variable in the form with the ID and check for $_POST['id'].
I'd go for the second option:
<form class="form-horizontal" action="update_items.php" method="post">
<input type="hidden" name="id" value="<?php echo $ido; ?>">
and in php:
if (!empty($_POST)) {
$ido = $_POST['id'];

Returning hashed password characters from database

I've recently set up my own dedicated server and installed everything that is necessary to write PHP scripts etc. But I seem to have an issue when I'm returning an encrypted password from my MySQL databases, and I can't tell if it's something to do with my PHP configuration or whether it's something to do with my MySQL configuration. Basically what is happening is when I use PDO to return the encrypted password from the database it looses certain characters, so when PHP goes to compare the encrypted password the user entered on the login with the password held in the database it throws an error.
Here's an example:
The password entered by the user after encryption:
�#7��"�����8wŖQE��4YW�6�'��u�
The password returned from the database: ?#7??"?????8w?QE??4YW?6?'??u?
The '�' characters seem to be getting changed to '?' characters :S
I've checked the passwords in PHPMyAdmin to see if it was missing any characters, but the passwords match, so something is going a rye somewhere in between, and I am unsure whether it's to do with PHP settings or MySQL.
Here's my scripts:
Hash and Salt Script (modules.php):
<?php
/* Initialises the username variable. */
$username = $_SESSION['username'];
/* If the user has changed their details then this block of code will make the changes to the database.
if(isset($_POST['detailsChanged']) == 1)
{
$statement = $conn -> prepare("UPDATE people SET Firstname = :firstname, Surname = :surname, Email = :email WHERE Username = :username ");
$statement->bindParam(':firstname', $_POST['Firstname'], PDO::PARAM_INT);
$statement->bindParam(':surname', $_POST['Surname'], PDO::PARAM_INT);
$statement->bindParam(':email', $_POST['Email'], PDO::PARAM_INT);
$statement->bindParam(':username', $username, PDO::PARAM_INT);
$statement->execute();
}*/
if(isset($_SESSION["passed"]) == 1)
{
$statement = $conn->prepare("SELECT * FROM people WHERE username = '".$username."'");
$statement->execute();
$result = $statement->fetch();
$firstname = $result['Firstname'];
$surname = $result['Surname'];
$username2 = $result['Username'];
}
function pbkdf2( $p, $s, $c, $kl, $a = 'sha256' ) {
$hl = strlen(hash($a, null, true)); # Hash length
$kb = ceil($kl / $hl); # Key blocks to compute
$dk = ''; # Derived key
# Create key
for ( $block = 1; $block <= $kb; $block ++ ) {
# Initial hash for this block
$ib = $b = hash_hmac($a, $s . pack('N', $block), $p, true);
# Perform block iterations
for ( $i = 1; $i < $c; $i ++ )
# XOR each iterate
$ib ^= ($b = hash_hmac($a, $b, $p, true));
$dk .= $ib; # Append iterated block
}
# Return derived key of correct length
return substr($dk, 0, $kl);
}
?>
PDO initialisation (Login and Password removed for security reasons)(connection.php):
<?php
$login = "*******";
$password = "********";
$dsn = "mysql:host=localhost;dbname=wishpiggy";
$opt = array(
// any occurring errors wil be thrown as PDOException
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
// an SQL command to execute when connecting
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"
);
$conn = new PDO($dsn, $login, $password);
$conn->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
?>
Login Page:
<?php ob_start(); session_start(); include ('sql_connect/connection.php'); include('sql_connect/modules.php');
//This section of code checks to see if the client is using SSL, if not
// if($_SERVER["HTTPS"] != "on")
// {
// header("HTTP/1.1 301 Moved Permanently");
// header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
// exit();
// }
//This if statement checks to see if the session variable 'username' is set, and if so it will redirect the user to their profile page.
if(isset($_SESSION["username"]))
{
header("Location: /home/");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Wish Piggy</title>
<link href="css/styles.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="js/loginjs.js"></script>
</head>
<body>
<div class="index_div">
<div class="logo"><img src="img/wish_piggy.jpg" alt="" />
</div>
<div class="text"><span>89% Fulfilled</span>
</div>
<div class="bar"><img src="img/wish_piggy_bar.jpg" alt="" />
</div>
<div class="text">
<div class="text_l"><p>1,000,000 People</p>
</div>
<div class="text_r"><p>9,000,838 Wishes</p>
</div>
</div>
<div class="sign_in"><a id="show-panel" href="#"></a>
</div>
</div>
<div id="lightbox-panel">
<form id="loginForm" name="form" action="index.php" method="post" >
<input name="submitted" type="hidden" value="1" />
<div class="login_label"><img src="img/wish_piggy_login.jpg" alt="" /><a id="open_signin" href="#">SIGN UP HERE</a><p>Login</p><a id="close-panel" href="#"></a>
</div>
<div class="login_input"><input name="email" type="text" value="<?php if(isset($_COOKIE['username']) && $_COOKIE['username'] != ""){echo $_COOKIE['username']; $_SESSION["username"] = $_COOKIE['username']; $_SESSION["passed"] = 1; header("Location: /home/");}else{echo "Email";} ?>" onclick="this.value=''" />
</div>
<div class="input_label"><span>(e.g. johndoe#email.com)</span>
</div>
<div class="login_input"><input name="password" type="password" value="Password" onclick="this.value=''" />
</div>
<div class="input_label">Forgot Password
</div>
<div class="login_submit">
<div class="login_checkbox"><input name="remember" type="checkbox" value="" /> <span>Remember me</span>
</div>
<div class="login_submit_input"><input name="submit" type="submit" value=""/>
</div>
</div>
</form>
</div>
<div id="lightbox"></div>
<div id="lightbox-panel2">
<div class="inner_lightbox2"><img src="img/wish_piggy_login.jpg" alt="" /><a id="close-panel2" href="#"></a>
</div>
<div class="signup_form">
<form action="index.php" method="post">
<input name="submitted" type="hidden" value="1" />
<div class="signup_form_label"><span>Firstname:</span>
</div>
<div class="signup_form_input"><input name="firstname" type="text" />
</div>
<div class="signup_form_label"><span>Surname:</span>
</div>
<div class="signup_form_input"><input name="surname" type="text" />
</div>
<div class="signup_form_label"><span>Email:</span>
</div>
<div class="signup_form_input"><input name="email" type="text" />
</div>
<div class="signup_form_label"><span>Confirm Email:</span>
</div>
<div class="signup_form_input"><input name="emailConfirm" type="text" />
</div>
<div class="signup_form_label"><span>Password:</span>
</div>
<div class="signup_form_input"><input name="password" type="text" />
</div>
<div class="signup_form_label"><span>Confirm Password:</span>
</div>
<div class="signup_form_input"><input name="passwordConfirm" type="text" />
</div>
<div class="signup_form_label2"><img src="img/wish_piggy_captcha.jpg" alt="" />
</div>
<div class="signup_form_input2"><input name="" type="text" />
</div>
<div class="signup_form_submit"><input name="" type="button" value="register" />
</div>
</form>
</div>
</div>
<?php
if(isset($_POST["submitted"]) == 1)
{
echo "caught data!";
$email = $_POST["email"];
$password = $_POST["password"];
if($password == "")
{
die ("Your username or password is incorrect.");
}
$usernameValidated = 0;
$statement = $conn->prepare("SELECT password FROM users WHERE email = :name");
$statement->bindParam(":name", $email);
$statement->execute();
$passCompare = $statement->fetch();
$passSubmitHashed = pbkdf2($password, "butterScotch", 1000, 32);
echo $passSubmitHashed;
echo " || ";
echo $password;
if($passSubmitHashed == $passCompare['password'])
{
$usernameValidated++;
}
echo "hurrdurr || " . $passCompare['password'];
if($usernameValidated == 0)
{
die("Your username or password is incorrect..");
}
}
if(isset($_POST["submitted"]) == NULL || isset($usernameValidated) > 0)
{
echo "<style> #text_contents{display: none;}</style>";
}
if(isset($usernameValidated) >= 1)
{
$_SESSION["username"] = $username;
$expiry = 60 * 60 * 6 + time();
setcookie('username', $username, $expiry);
$_SESSION["passed"] = $_POST["submitted"];
header("Location: /profile/");
}
ob_end_flush();
?>
<div id="lightbox2"></div>
<?php ob_end_flush(); ?>
</body>
</html>
Encode the password simply using base64_encode (before saving it, and when comparing it) :)

Categories