Check IP in SQL Server database using php - php

I want a query to check if the user IP is already in database, and if it is, to not allow that user to make a new account.
Here's Register.php, if you want, I will post it all
<!-- Body Start -->
<div id="body">
<?php
if(!$login)
{
$form = true;
if(isset($_POST['userbox']))
{
$user_ip = $_SERVER['REMOTE_ADDR'];
$user = $_POST['userbox'];
$mail = $_POST['email'];
$pw = $_POST['password'];
$pw2 = $_POST['password2'];
//require_once('includes/recaptchalib.php');
//$resp = recaptcha_check_answer (CMS_PRKEY,
// $_SERVER["REMOTE_ADDR"],
// $_POST["recaptcha_challenge_field"],
//$_POST["recaptcha_response_field"]);
$user = mysql_real_escape_string($user);
$mail = mysql_real_escape_string($mail);
if(check_mail($mail) && $pw == $pw2 && check_name($user) && strlen($user) < 21 && strlen($user) > 5)
{
$sql0 = "SELECT szUserID FROM TGLOBAL_GSP.dbo.TACCOUNT WHERE szUserID = '".$user."'";
$q0 = odbc_exec($ms_con, $sql0);
$nFree = odbc_num_rows($q0);
if($nFree == 0)
{
$sql0 = "SELECT MAX(dwUserID) AS Result FROM TGLOBAL_GSP.dbo.TACCOUNT";
$q0 = odbc_exec($ms_con, $sql0);
$count0 = odbc_fetch_array($q0);
$count = $count0['Result'];
$date = date("Y-m-d H:i:s");
$sql = "INSERT INTO TGLOBAL_GSP.dbo.TACCOUNT(szUserID, szPasswd, bCheck, dFirstLogin, szMail, szLastLoginIp)
VALUES('".$user."','".$pw."', '1', {ts'".$date."'},'".$mail."','".$user_ip."')";
$stmt = odbc_prepare($ms_con, $sql);
odbc_execute($stmt, array($count + 1, $user, $pw, $mail));
echo '<p>Dein Account wurde erfolgreich erstellt! Du kannst dich nun einloggen.<br />» Zum Login</p>';
$form = false;
}
else
{
$error = 'Der Benutzername ist bereits vergeben!';
}
}
else
{
$error = 'Das Passwort, die eMail-Adresse oder der Benutzername waren nicht korrekt!';
}
}
if($form)
{
echo '<h4>Register</h4>';
echo'
<form action="register.php" method="post">
<label>Name <small><em>(required)</em></small></label>
<input type="text" name="userbox" id="userbox" />
<label>eMail-Adresse <small><em>(required)</em></small></label>
<input type="text" name="email" id="email" />
<label>Passwort <small><em>(required)</em></small></label>
<input type="password" name="password" id="password" />
<label>Password wiederholen <small><em>(required)</em></small></label>
<input type="password" name="password2" id="password2" /><br /><br />';
//require_once('includes/recaptchalib.php');
//echo recaptcha_get_html(CMS_PUKEY);
echo '<br /><input type="submit" value="Account anlegen" class="read_more2" />
</form>';
if(isset($error))
{
echo '<br /><p>'.$error.'</p>';
}
}
}
else
{
echo '<p>Du kannst keinen Account erstellen, da du eingeloggt bist!<br />» Zurück zur Startseite</p>';
}
?>
</div>
<!-- Body end -->

Related

how to show php validations error on page

I have a form and all the validations, now I want to show the error messages in front of the text field not in the url. How do I do this?
Here is my PHP code:
<?php
if ((isset($_POST['submit']))){
$email = strip_tags($_POST['email']);
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$fullname_valid = $email_valid = $username_valid = $password_valid = false;
if(!empty($fullname)){
if (strlen($fullname) > 2 && strlen($fullname)<=30) {
if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
$fullname_valid = true;
# code...
}else {$fmsg .="fullname can contain only alphabets <br>";}
}else{$fmsg1 .="fullname must be 2 to 30 char long <br>";}
}else{$fmsg2 .="fullname can not be blank <br>";}
if (!empty($email)) {
if (filter_var($email , FILTER_VALIDATE_EMAIL)) {
$query2 = "SELECT email FROM users WHERE email = '$email'";
$fire2 = mysqli_query($con,$query2) or die("can not fire query".mysqli_error($con));
if (mysqli_num_rows($fire2)>0) {
$msg .=$email."is already taken please try another one<br> ";
}else{
$email_valid=true;
}
# code...
}else{$msg .=$email."is an invalid email address <br> ";}
# code...
}else{$msg .="email can not be blank <br>";}
if(!empty($username)){
if (strlen($username) > 4 && strlen($username)<=15) {
if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {
$query = "SELECT username FROM users WHERE username = '$username'";
$fire = mysqli_query($con,$query) or die("can not fire query".mysqli_error($con));
if(mysqli_num_rows($fire)> 0){
$umsg ='<p style="color:#cc0000;">username already taken</p>';
}else{
$username_valid = true;
}
# code...
# code...
}else {$msg.= "username can contain only alphabets <br>";}
}else{$msg.= "username must be 4 to 15 char long <br>";}
}else{$msg.="username can not be blank <br>";}
if (!empty($password)) {
if (strlen($password) >=5 && strlen($password) <= 15 ) {
$password_valid = true;
$password = md5($password);
# code...
}else{$msg .= $password."password must be between 5 to 15 character long<br>";}
# code...
}else{$msg .= "password can not be blank <br>";}
if ($fullname_valid && $email_valid && $password_valid && $username_valid) {
$query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
$fire = mysqli_query($con,$query) or die ("can not insert data into database".mysqli_error($con));
if ($fire){
header("Location: dashboard.php");}
}else{
header("Location: createaccount.php?msg=".$msg);
}
}
?>
and this is my html code:
<div class="container">
<form name="signup" id="signup" method="POST">
<h2>sign up</h2>
<div class="form-input">
<input name="email" type="email" name="email" id="email" placeholder="enter email" required="email is required">
</div>
<input name="mobile" type="number" id="mobile" placeholder="enter mobile number" required="mobile is required">
<span id="message"></span>
<div class="form-input">
<input name="fullname" type="full name" id="fullname" name="full name" placeholder="full name" required="what's your fullname">
</div>
<div>
<input name="username" type="username" id="username" name="username" placeholder="username" required="username is required">
</div>
<div>
<input name="password" type="password" id="password" name="password" placeholder="password" required="password is required">
</div>
<div>
<input type="submit" name="submit" id="submit"
value="sign up" class="btn btn-primary btn-block">
forgot password?
<h3>have an account? log in</h3>
</div>
</form>
How do I get the error message in front of my text field, and also how do I get the specified error in front of the specified text field? I don't want to use ajax or javascript. I want to do it with PHP. I have tried this but no luck.
<?php if(isset($errorfname)) { echo $errorfname; } ?>
send msg to get params is not good idea.
Use session
$_SESSION['error_msg'] = $msg
header("Location: createaccount.php");
and add get error in php
$errors = '';
if(isset($_SESSION['error_msg'])) { $errors = $_SESSION['error_msg']; } ?>
and in html show $errors
By looking at your form does not have an action attribute therefore one can concluded that you are submitting the form at the same page as the form PHP_SELF
So if you want to display the error next to the field I would advice that you first declare an empty variables for each text error on top of your page then echo the variables next to each field.
<?php
$emailError = "";
$fullnameError = "";
$usernameError = "";
$passwordError = "";
$errors = 0;
if ((isset($_POST['submit']))) {
$email = strip_tags($_POST['email']);
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$fullname_valid = $email_valid = $username_valid = $password_valid = false;
if (!empty($fullname)) {
if (strlen($fullname) > 2 && strlen($fullname) <= 30) {
if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
$fullname_valid = true;
# code...
} else {
$fullnameError = "fullname can contain only alphabets <br>";
$errors++;
}
} else {
$fullnameError = "fullname must be 2 to 30 char long <br>";
$errors++;
}
} else {
$fullnameError = "fullname can not be blank <br>";
$errors++;
}
if (!empty($email)) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$query2 = "SELECT email FROM users WHERE email = '$email'";
$fire2 = mysqli_query($con, $query2) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire2) > 0) {
$emailError = $email . "is already taken please try another one<br> ";
} else {
$email_valid = true;
}
# code...
} else {
$emailError = $email . "is an invalid email address <br> ";
$errors++;
}
# code...
} else {
$emailError = "email can not be blank <br>";
}
if (!empty($username)) {
if (strlen($username) > 4 && strlen($username) <= 15) {
if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {
$query = "SELECT username FROM users WHERE username = '$username'";
$fire = mysqli_query($con, $query) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire) > 0) {
$usernameError = '<p style="color:#cc0000;">username already taken</p>';
$errors++;
} else {
$username_valid = true;
}
} else {
$usernameError = "username can contain only alphabets <br>";
$errors++;
}
} else {
$usernameError = "username must be 4 to 15 char long <br>";
$errors++;
}
} else {
$usernameError = "username can not be blank <br>";
$errors++;
}
if (!empty($password)) {
if (strlen($password) >= 5 && strlen($password) <= 15) {
$password_valid = true;
$password = md5($password);
# code...
} else {
$passwordError = $password . "password must be between 5 to 15 character long<br>";
$errors++;
}
# code...
} else {
$passwordError = "password can not be blank <br>";
$errors++;
}
//if there's no errors insert into database
if ($errors <= 0) {
if ($fullname_valid && $email_valid && $password_valid && $username_valid) {
$query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
$fire = mysqli_query($con, $query) or die("can not insert data into database" . mysqli_error($con));
if ($fire) {
header("Location: dashboard.php");
}
}
}
}
?>
<div class="container">
<form name="signup" id="signup" method="POST">
<h2>sign up</h2>
<div class="form-input">
<input name="email" type="email" name="email" id="email" placeholder="enter email" required="email is required">
<!-- display email error here -->
<?php echo $emailError?>
</div>
<input name="mobile" type="number" id="mobile" placeholder="enter mobile number" required="mobile is required">
<span id="message"></span>
<div class="form-input">
<input name="fullname" type="full name" id="fullname" name="full name" placeholder="full name" required="what's your fullname">
<?php echo $fullnameError?>
</div>
<div>
<input name="username" type="username" id="username" name="username" placeholder="username" required="username is required">
<?php echo $usernameError?>
</div>
<div>
<input name="password" type="password" id="password" name="password" placeholder="password" required="password is required">
<?php echo $passwordError?>
</div>
<div>
<input type="submit" name="submit" id="submit" value="sign up" class="btn btn-primary btn-block">
forgot password?
<h3>have an account? log in</h3>
</div>
</form>
NB: I would advice that you look into password_hash() and
password_verify()to hash your passwords, they provide better
security as compared tomd5()` and make sure your database column is
atleast 60 characters in length.. I would also advice to look into
prepared statements.
The following can help :
How can I prevent SQL injection in PHP?
Using PHP 5.5's password_hash and password_verify function
I think the best way is include from template in result
if ($fire){
header("Location: dashboard.php");
}else{
include("createaccount.php");
}
And in createaccount.php
<div class="container">
<form name="signup" id="signup" method="POST">
<h2>sign up</h2>
<p class="errors"><?= $msg ?></p>
...

Fatal error: Uncaught PDOException:PDO There is no active transaction in /home/qndt0n0hz1u8/public_html/register.php:185 Stack trace

I am new to server mysql database, i just hosted my server with godaddy, connected to the database, my select query is working fine. After several trouble shooting i decided to use pdo transactions but am getting this error
My php registration script for insertion into database which is not working is show below:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors','1');
require_once('dbh.php');
require_once'config.php';
if( $_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['f_name']) && isset($_POST['u_name']) && ($_POST['f_name']) !="" && ($_POST['u_name']) !="" && ($_POST['Email']) !="" && ($_POST['phonenumber']) !="" ) {
/* id should be an auto-increment field in the db */
$f_name = isset($_POST['f_name']) ? $_POST['f_name'] : false;
$u_name = isset($_POST['u_name']) ? $_POST['u_name'] : false;
$password = isset($_POST['password']) ? $_POST['password'] : false;
$password1 = isset($_POST['password1']) ? $_POST['password1'] : false;
$Email = isset($_POST['Email']) ? $_POST['Email'] : false;
$phonenumber = isset($_POST['phonenumber']) ? $_POST['phonenumber'] : false;
$sponsor = isset($_GET['sponsor']) ? $_GET['sponsor'] : false;
echo $sponsor;
$error_fname = "";
$eror_fname = "";
$errror_fname = "";
$eror_uname = "";
$errror_uname = "";
$error_uname = "";
$eror_password = "";
$errror_password = "";
$error_password = "";
$eror_email = "";
$error_email = "";
$errror_email = "";
$eror_phonenumber = "";
$error_phonenumber = "";
$errror_phonenumber = "";
$error_captcha = "";
$error_sponsor = "";
$errorSmt = "";
if(isset($_POST['f_name']) && isset($_POST['u_name']) && isset(($_POST['Email'])) && isset($_POST['phonenumber']) ) {
$errror_fname = $f_name.' is OK';
//check for duplicate username
$con= new PDO("mysql:host=$serverhost;dbname=silverhub;" , $serverusername, $serverpassword);
$query = $con->prepare("SELECT userid FROM users WHERE u_name=? LIMIT 1");
$u_Check = $query->bindParam(1, $u_name, PDO::PARAM_STR);
$u_Check = $query->execute();
$u_Check = $query->rowCount();
if( $u_Check=$query->rowCount() > 0) {
$eror_uname = ' Sorry'.$u_name.' already taken, please choose another';
}else{
$errror_uname = $u_name.' is OK';
}
//check for duplicate referral
$query = $con->prepare("SELECT sponsor FROM users WHERE userid=? LIMIT 1");
$s_Check = $query->bindParam(1, $userid, PDO::PARAM_INT);
$s_Check = $query->execute();
$s_Check= $query ->fetch(PDO::FETCH_ASSOC);
if( $s_Check['sponsor'] == $u_name) {
$error_sponsor = 'Sorry, user cannot refer himself';
}
//check referral Email
$query = $con->prepare("SELECT userid FROM users WHERE Email=? LIMIT 1");
$e_Check = $query->bindParam(1, $Email, PDO::PARAM_STR);
$e_Check = $query->execute();
$e_Check = $query->rowCount();
if( $p_Check=$query->rowCount() > 0) {
$eror_email = $Email.' already taken, please choose another';
}else{
$errror_email = $Email. ' is OK';
}
//check for duplicate phonenumber
$query = $con->prepare("SELECT userid FROM users WHERE phonenumber=? LIMIT 1");
$p_Check = $query->bindParam(1, $phonenumber, PDO::PARAM_STR);
$p_Check = $query->execute();
$p_Check = $query->rowCount();
if( $al_Check=$query->rowCount() > 0) {
$eror_phonenumber = $phonenumber.' already taken, please choose another';
}else{
$errror_phonenumber = $phonenumber. ' is OK';
}
}
// if(!preg_match("/^[a-zA-Z0-9]*$/",$f_name) && strip_tags(trim($f_name))) {
// $error_fname = 'invalid, fullname must be alphanumerics with no whitespace';
// echo 'invalid, fullname must be alphanumerics with no whitespace';
// }
if(!preg_match("/^[a-zA-Z0-9]*$/",$u_name) && strip_tags(trim($u_name))) {
$error_uname = 'invalid, username must be alphanumerics with no whitespace';
}
if(strlen($u_name) < 3 || strlen($u_name) > 16) {
$error_uname = 'Username must be between 3 - 16 characters';
}
if($password !== $password1) {
$error_password = 'Password and RepeatPassword do not match';
}
if(strlen($password) < 5) {
$error_password = 'Weak password, Password must be more than 5 characters';
}
if(strlen($phonenumber) > 11 && trim(htmlentities($phonenumber))) {
$error_phonenumber = 'Phonenumbers must be an 11 digit number';
}
if(!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
$error_email = ' invalid email address, please verify your email address';
}
if(!preg_match("/^[a-zA-Z0-9]*$/",$sponsor) && strip_tags(trim($sponsor))) {
$error_sponsor = 'invalid sponsor name, must be alphanumeric ';
}
if(empty($_POST['recaptcha'])) {
$error_captcha = 'Enter the Verification Code Above';
}
elseif($_POST['recaptcha'] != $_SESSION['recaptcha']) {
$error_captcha = 'Verification Code did not match, try again';
}elseif($_POST['recaptcha'] == $_SESSION['recaptcha']) {
$error_captcha = 'Verification Matched, Click Register';
}
if($u_name && $eror_fname =="" && $error_fname =="" && $errror_fname !=="" && $eror_uname =="" && $error_uname =="" && $errror_uname !=="" && $error_password =="" && $eror_email == "" && $error_email == "" && $errror_email !== "" && $eror_phonenumber =="" && $error_phonenumber =="" && $errror_phonenumber !=="" ) {
class reg extends dbh {
public function userCheck($f_name, $u_name,$password,$Email,$phonenumber,$sponsor) {
try {
$con = new PDO("mysql:host=$this->serverhost;dbname=silverhub;", $this->serverusername, $this->serverpassword);
$con->beginTransaction();
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$passenc = password_hash($password, PASSWORD_DEFAULT, array('cost'=>11));
$emailCode = rand().$phonenumber;
$smsCode = rand().$u_name;
$Active = 0;
$Has_reserved_person = 'NO';
$MainTime = time();
$con= new PDO("mysql:host=$this->serverhost;dbname=silverhub;", $this->serverusername, $this->serverpassword);
$sql = "INSERT INTO users (f_name,u_name,password,Email,emailCode,phonenumber,smsCode,sponsor,Active,Has_reserved_person,MainTime) VALUES (?,?,?,?,?,?,?,?,?,?,?)";
$insert = $con->prepare($sql);
$insert->bindParam(1,$f_name,PDO::PARAM_STR);
$insert->bindParam(2,$u_name,PDO::PARAM_STR);
$insert->bindParam(3,$passenc );
$insert->bindParam(4,$Email,PDO::PARAM_STR);
$insert->bindParam(5,$emailCode,PDO::PARAM_STR);
$insert->bindParam(6,$phonenumber,PDO::PARAM_STR);
$insert->bindParam(7,$smsCode,PDO::PARAM_STR);
$insert->bindParam(8,$sponsor,PDO::PARAM_STR);
$insert->bindParam(9,$Active);
$insert->bindParam(10,$Has_reserved_person);
$insert->bindParam(11,$MainTime);
$insert->execute();
$con->commit();
if($insert->execute()){
echo 'insert successfull';
}else{
echo "Execute query error, because:" . print_r($con->errorinfo());
return false;
}
} catch (PDOException $e){
throw $e;
}
}
}
$object = new reg();
$object->userCheck( $f_name, $u_name, $password, $Email, $phonenumber, $sponsor);
}
}
?>
Here is my HTML FORM input:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html !doctype>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<div id="container">
<div id="sec">REGISTER WITH US</div>
<img src="images/images(33).jpg">
<form action='register.php' method='POST' class='ajax-reg'>
<!-- HOW does a user enter a value here if it is HIDDEN??? Removed `required` attribute -->
<div class='form-group'>
<p> Note!!! Fields with astericks must be filled</p>
<input type='hidden' class='form-control' name='userid' placeholder='enter your id' />
</div>
<br>
<div class='form-group'>
<label>fullname*</label>
<input type="text" class="form-control" onblur ="fnamecheck()" id="f_name" name="f_name" placeholder="Enter your fullname" value="<?php echo #$_POST['f_name']?>" /><span id ="fullnameStatus"></span>
</div>
<br>
<div class='form-group'>
<label>username*</label>
<input type="username" class="form-control" name="u_name" id ="u_name" onblur ="usernamecheck()" placeholder="Enter your username" value="<?php echo #$_POST['u_name']?>" /><span id ="usernameStatus"></span>
</div>
<br>
<div class='form-group' >
<label>password*</label>
<input type="password" class="form-control" name="password" id="password" onblur ="passcheck()" placeholder="type in your password" />
</div>
<br>
<div class='form-group' >
<label>RepeatPassword*</label>
<input type="password" class="form-control" name="password1" id ="password1" onblur ="passcheck()" placeholder= "Retype in your password" /><span id ="passwordStatus"></span>
</div>
<br>
<div class='form-group'>
<label>email*</label>
<input type="email" class="form-control" name="Email" id ="Email" onblur ="emailcheck()" placeholder="Enter your email" value="<?php echo #$_POST['Email']?>" /><span id ="emailStatus"></span>
</div>
<br>
<div class='form-group'>
<label>phonenumber*</label>
<input type="number" class="form-control" name="phonenumber" id = "phonenumber" onblur ="phcheck()" placeholder="Enter your phonenumber" value="<?php echo #$_POST['phonenumber']?>" /><span id ="phonenumberStatus"></span>
</div>
<br>
<div>
<?php if (isset($_GET['sponsor']) && $_GET['sponsor'] != "") {?>
<input type="hidden" class="form-control" name="sponsor" id ="sponsor" onblur ="usernamecheck()" placeholder="type in your sponsor username here" value="<?php $sponsor = $_GET['sponsor'];?>" />
<?php }?>
</div>
<br>
<div id="captcha"><img src="captcha.php"></div>
<br>
<div id="refresh"><p> Refresh To Change Code</p></div>
<div id="captcha">
<input type="text" class="form-control" name="recaptcha" id = "recaptcha" onblur ="recaptchacheck()" placeholder="Enter The Code Above" /><span><?php echo #$error_captcha?></span><span id ="recaptchaStatus"></span>
</div>
<div class='form-group'>
<!-- this checkbox needs a name!! Assign name `terms` -->
<input type="checkbox" name="terms" required />
</div>
<div id="terms"> </a><a href="terms.php" >I agree with terms and conditions</a></div>
<div>
<input type='submit' class='btn btn-success' name='submit_signup' value='REGISTER' />
</div>
<br>
</form>
<br>
<div></div>
</div>
<footer>
</footer>
<script lang="javascript" type="text/javascript" src="jqueryfunctions.js"></script>
<script lang="javascript" type="text/javascript" src="ajaxfiles.js">
</script>
</body>
</html>

How do i verify query record with form input

In my code below i have two form section first one is to fetch information from database and second one is verify a record in the database my problem is how do verify a record and redirect to error page or if the input form do not march any record redirect to index page this my code;
<?php
include_once 'init.php';
$error = false;
//check if form is submitted
if (isset($_POST['book'])) {
$book = mysqli_real_escape_string($conn, $_POST['book']);
$action = mysqli_real_escape_string($conn, $_POST['action']);
if (strlen($book) < 6) {
$error = true;
$book_error = "booking code must be alist 6 in digit";
}
if (!is_numeric($book)) {
$error = true;
$book_error = "Incorrect booking code";
}
if (empty($_POST["action"])) {
$error = true;
$action_error = "pick your action and try again";
}
if (!$error) {
if(preg_match('/(check)/i', $action)) {
echo "6mameja";
}
if (preg_match('/(comfirm)/i', $action)) {
if(isset($_SESSION["user_name"]) && (trim($_SESSION["user_name"]) != "")) {
$username=$_SESSION["user_name"];
$result=mysqli_query($conn,"select * from users where username='$username'");
}
if ($row = mysqli_fetch_array($result)) {
$id = $row["id"];
$username=$row["username"];
$idd = $row["id"];
$username = $row["username"];
$ip = $row["ip"];
$ban = $row["validated"];
$balance = $row["balance"];
$sql = "SELECT `item_name` , `quantity` FROM `books` WHERE `book`='$book'";
$query = mysqli_query($conn, $sql);
while ($rows = mysqli_fetch_assoc($query)) {
$da = $rows["item_name"]; $qty = $rows["quantity"];
$sqll = mysqli_query($conn, "SELECT * FROM promo WHERE code='$da' LIMIT 1");
while ($prow = mysqli_fetch_array($sqll)) {
$pid = $prow["id"];
$price = $prow["price"];
$count = 0;
$count = $qty * $price;
$show = $count + $show;
}
}
echo "$show";
echo "$balance";
if ($show<$balance) {
if (isset($_POST["verify"])) {
$pass = mysqli_real_escape_string($conn, $_POST["pass"]);
if ($pass != "$username") {
header("location: index.php");
}
elseif ($pass = "$username") {
header("location: ../error.php");
}
}
echo '<form action="#" method="post" name="verify"><input class="text" name="pass" type="password" size="25" /><input class="text" type="submit" name="verify" value="view"></form>';
echo "you cant buy here";
exit();
}
} else {
$errormsg = "Error in registering...Please try again later!";
}
}
}
}
?>
<form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="booking">
<fieldset>
<legend>Check Booking</legend>
<div class="form-group">
<label for="name">Username</label>
<input type="text" name="book" placeholder="Enter Username" required value="<?php if($error) echo $book; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($book_error)) echo $book_error; ?></span>
</div>
<input type="submit" name="booking" value="Sign Up" class="btn btn-primary" />
<table>
<input type="radio" name="action" value="comfirm" <?php if(isset($_POST['action']) && $_POST['action']=="comfirm") { ?>checked<?php } ?>>
<input type="radio" name="action" value="check" <?php if(isset($_POST['action']) && $_POST['action']=="check") { ?>checked<?php } ?>> Check booking <span class="text-danger"><?php if (isset($action_error)) echo $action_error; ?></span>
</div>
</table>
</fieldset>
</form>
in achievement am expected to redirect to error or index page but my code above refress back to first form what are my doing wrong. Big thanks in advance

My redirect user back to previoud url is not working

I am working on local machine on a projet and i want to redirect user back to their previous after they have logged in.I tried myself based on research over internet, but no success. If somebody could help; will appreciate..Here are my code.
sell.php
if (!isset($_SESSION["user_id"])) {
header("Location: login.inc.php?location=". urlencode($_SERVER["REQUEST_URI"]));
exit();
}
include_once("./includes/partheader.html");
login.inc.php
<form action='' method='post'>
<p>
<label for='email'>Email : </label>
<input type='text' name='email' value='<?php if(isset($_POST['email'])){ echo $_POST['email'];} ?>' /><?php if(isset($errEmail) ){echo $errEmail;} ?>
</p>
<p>
<label>Mot de passe : </label>
<input type='password' name='userpwd' value='' /><?php if(isset($pwdErr)){ echo $pwdErr;} ?>
</p>
<p>
<input type="hidden" name="location" value="<?php if (isset($_GET["location"])) {
echo htmlspecialchars($_GET["location"]);
} ?>">
</p>
<p>
<input type='submit' name='login' value='Connexion' />
</p>
</form>
login_form.inc.php
if(array_key_exists('login', $_POST)){
$redirect = NULL;
if($_POST['location'] != '') {
$redirect = $_POST['location'];
}
if (empty($_POST["email"])) {
$errEmail = "Enter your email";
} else {
$email = trim($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errEmail = "Invalid email ";
}
}
if (empty($_POST['userpwd'])) {
$pwdErr = "Entrer votre mot de passe";
}
else{
$userpwd = sha1($_POST['userpwd']).$_POST['userpwd'];
}
if(empty($errEmail) && empty($pwdErr) ){
include_once(BASE_URI."pdoconnect.inc.php");
if(isset($pdo) ){
try{
$sql = 'SELECT userid, gender,nameuser FROM users WHERE users.email = :email AND users.userpwd = :userpwd';
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':email', $email);
$stmt->bindValue(':userpwd', $userpwd);
$stmt->execute();
$rowscount = $stmt->rowCount();
if(isset($rowscount) && $rowscount < 1 ){
$err = 'Mot de passe ou nom d\' utilisateur incorrect';
}
else{
foreach($result = $stmt->fetchAll() as $row){
$_SESSION['user_id'] = $row['userid'];
$_SESSION['gender'] = $row['gender'];
$_SESSION['nameuser'] = $row['nameuser'];
} //end foreach
if (isset($redirect)) {
header("Location:". $redirect);
}
//end of redirect header
}
}catch (PDOException $e) {
$errors[] = "Eror in script".$e->getMessage();
}
}
}//end of check error
}//end of post
My issue is when i fill the login form with the right details...the page should redirect to sell.php instead it stays on the login page with this url in browser :http://localhost/projet-fembuleuse/html/login.inc.php?location=%2Fprojet-fembuleuse%2Fhtml%2Fvendre.php
I think a script like that is quite prone to errors and problems. What if someone messes with the request headers? Instead, you should just save the url inside a session variable and use that when needed:
Sell.php
<?php
session_start();
if (!empty($_SESSION["user_id"])) {
$_SESSION['cur_url'] = $_SERVER["REQUEST_URI"];
header("Location: login.inc.php");
exit();
}
include_once("./includes/partheader.html");
login.inc.php
<?php session_start(); ?>
<form action='' method='post' accept-charset='utf-8'>
<p>
<label for='email'>Email : </label>
<input type='text' name='email' value='<?php if(isset($_POST['email'])){ echo $_POST['email'];} ?>' /><?php if(isset($errEmail) ){echo $errEmail;} ?>
</p>
<p>
<label>Mot de passe : </label>
<input type='password' name='userpwd' value='' /><?php if(isset($pwdErr)){ echo $pwdErr;} ?>
</p>
<p>
<input type='submit' name='login' value='Connexion' />
</p>
</form>
login_form.inc.php
<?php
session_start();
if(array_key_exists('login', $_POST)){
if (empty($_POST["email"])) {
$errEmail = "Enter your email";
} else {
$email = trim($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errEmail = "Invalid email ";
}
}
if (empty($_POST['userpwd'])) {
$pwdErr = "Entrer votre mot de passe";
} else {
$userpwd = sha1($_POST['userpwd']).$_POST['userpwd'];
}
if(empty($errEmail) && empty($pwdErr) ){
include_once(BASE_URI."pdoconnect.inc.php");
if(isset($pdo) ){
try{
$sql = 'SELECT userid, gender,nameuser FROM users WHERE users.email = :email AND users.userpwd = :userpwd';
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':email', $email);
$stmt->bindValue(':userpwd', $userpwd);
$stmt->execute();
$rowscount = $stmt->rowCount();
if(isset($rowscount) && $rowscount < 1 ){
$err = 'Mot de passe ou nom d\' utilisateur incorrect';
} else {
foreach($result = $stmt->fetchAll() as $row){
$_SESSION['user_id'] = $row['userid'];
$_SESSION['gender'] = $row['gender'];
$_SESSION['nameuser'] = $row['nameuser'];
} //end foreach
if (!empty($_SESSION['cur_url'])) {
header("Location:". $_SESSION['cur_url']);
}
//end of redirect header
}
} catch (PDOException $e) {
$errors[] = "Eror in script".$e->getMessage();
}
}
}//end of check error
}//end of post
PS: I didn't check your code for any other existing problems. If the rest of the code is working as expected, this should solve the problem.

Can't insert to the database

My problem is, I can't insert the variables $skyr,$eftir,$notandi,$pass and $mel in the code below into my Mysql database when I submit the form. The Insert statement is correct and mysqli_connect() in the $conn variable is correct, I tested it with other variables in other file. So, what is the problem in my code? What I'am doing wrong?
Here is my code:
<!DOCTYPE>
<html>
<head>
<title>Skráðu þig!</title>
<link rel="stylesheet" type "text/css" href="stylesheet.css">
<link rel='stylesheet' type "text/css" href="style_val.css"/>
</head>
<body>
<div class="container">
<banner><div class="bordi"><img src="./myndir/Banner.jpg"/></div></banner>
<div class="front-box"></div>
<div class="skraning">
<?php
//RECAPTCHA - SERVER SIDE
require_once('recaptchalib.php');
$privatekey = "privatekey";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
$invalid = "Vinsamlegast ritaðu aftur inn stafina fyrir ofan.";
}
else{
$invalid = "";
}
//Tekið af:https://developers.google.com/recaptcha/docs/php
error_reporting(1); error_reporting(E_ALL); ini_set('display_errors', 1);//Við viljum ekki sjá villurnar, heldur viljum við hafa hlutina á mannamáli. Við búum síðan til aðgerðir(functions) til að höndla þær villur sem kunna að koma upp.
?>
<?php
$mysql_host = "some host";
$mysql_database = "some database";
$mysql_user = "some user";
$mysql_password = "some password";
$dbname = 'some database name';
$conn = mysqli_connect($mysql_host,$mysql_user,$mysql_password,$dbname);
if(!$conn){
echo "Get ekki tengst gagnagrunni. Vefstjóra gert viðvart";
villupost();
}
function villupost(){
$to = 'arnarfreyr#hive.is';
$subject = 'MYSQL VILLA!';
$message = mysqli_error();
$headers = 'sjálfvirkur tölvupóstur';
mail($to,$subject,$message,$headers);
}
function sanityCheck($string, $type, $length){
// assign the type
$type = 'is_'.$type;
if(!$type($string))
{
return FALSE;
}
// now we see if there is anything in the string
elseif(empty($string))
{
return FALSE;
}
// then we check how long the string is
elseif(strlen($string) > $length)
{
return FALSE;
}
else
{
// if all is well, we return TRUE
return TRUE;
}
}
//Tekið og breytt af: http://www.phpro.org/tutorials/Validating-User-Input.html
// define variables and initialize with empty values
$skyrErr = $eftirErr = $notandiErr = $passErr = $melErr = $c_passErr = $melErr_s ="";
$skyr = $eftir = $notandi = $pass = $mel = $c_pass = $mel_s = "";
$fylla_ut = "Þennan reit verður að fylla út.";
$fylla_rett = "Vinsamlegast fylltu út rétt netfang.";
if (isset($_POST['sub'])) {
if (empty($_POST["skyr"])==FALSE && sanityCheck($_POST["skyr"],'string',60)!=FALSE) {
$skyr = mysqli_real_escape_string($conn,$_POST["skyr"]);
}
else {
$skyrErr = '<span class="red">'.$fylla_ut.'</span>';
$pass = "";
$c_pass = "";
}
if (empty($_POST["eftir"])==FALSE && sanityCheck($_POST["eftir"],'string',60)!=FALSE) {
$eftir = mysqli_real_escape_string($conn,$_POST["eftir"]);
}
else {
$eftirErr = '<span class="red">'.$fylla_ut.'</span>';
$pass = "";
$c_pass = "";
}
if (empty($_POST["notandi"])==FALSE && sanityCheck($_POST["notandi"],'string',15)!=FALSE){
$notandi = mysqli_real_escape_string($conn,$_POST["notandi"]);
}
else {
$notandiErr = '<span class="red">'.$fylla_ut.'</span>';
$pass = "";
$c_pass = "";
}
if (empty($_POST["pass"])==FALSE) {
if (!preg_match('/^(?=.*\d)(?=.*\W)(?=.*[a-z])(?=.*[A-Z]).{6,15}$/', $_POST["pass"])){
$passErr = "Lykilorðið verður að innihalda lágstafi, hástafi, tölustafi og sérstafi t.d. !\"#$%&/";
$pass = "";
$c_pass = "";
}
else{
$pass = $_POST["pass"];
$salted = mcrypt_create_iv(64);
$pass = mysqli_real_escape_string($conn,hash('sha512',$_POST["pass"].$salted));
}
}
else{
$passErr = '<span class="red">'.$fylla_ut.'</span>';
}
if (empty($_POST["mel"])==FALSE && sanityCheck($_POST["mel"],'string',60)!=FALSE){
if (!filter_var($_POST["mel"], FILTER_VALIDATE_EMAIL)){
$melErr = '<span class="red">'.$fylla_rett.'</span>';
$pass = "";
$c_pass = "";
}
else{
$mel = mysqli_real_escape_string($conn,$_POST["mel"]);
}}
else{
$melErr = '<span class="red">'.$fylla_ut.'</span>';
$pass = "";
$c_pass = "";
}
if (empty($_POST["mel_s"])==FALSE && sanityCheck($_POST["mel_s"],'string',60)!=FALSE){
if (!filter_var($_POST["mel_s"], FILTER_VALIDATE_EMAIL)){
$melErr_s = '<span class="red">'.$fylla_rett.'</span>';
$pass = "";
$c_pass = "";
}
if ($_POST["mel"]!=$_POST["mel_s"]){
$melErr_s = '<span class="red">Netföng stemma ekki.</span>';
$pass = "";
$c_pass = "";}
else{
$mel_s = $_POST["mel_s"];
}
}
else {
$melErr_s = '<span class="red">'.$fylla_ut.'</span>';
$pass = "";
$c_pass = "";
}
if (empty($_POST["c_pass"])==FALSE){
if($_POST["pass"]!=$_POST["c_pass"]){
$c_passErr = '<span class="red">Lykilorð stemma ekki. Reyndu aftur.</span>';
$pass = "";
$c_pass = "";
}
else{
$c_pass = $_POST["c_pass"];
}
}
else{
$c_passErr = '<span class="red">'.$fylla_ut.'</span>';
$pass = "";
$c_pass = "";
}
if ($skyr!=null&&$eftir!=null&&$notandi!=null&&$pass!=null&&$mel!=null/*&&$_POST["recaptcha_challenge_field"]!=null&&$_POST["recaptcha_response_field"]!=null*/){
$data = "INSERT INTO Login(Skírnarnafn,Eftirnafn,Notandanafn,Lykilorð,Tölvupóstur)
VALUES ('$skyr', '$eftir', '$notandi', '$pass', '$mel')";
mysqli_query($conn,$data);
mysqli_close($conn);
}
}
?>
<div class="formtext"></br>Hér getur þú skráð þig. Fylltu út formið hér að neðan.
Athugaðu að lykilorðið má ekki vera minna en 6 stafir
og ekki meira en 15 stafir.
Reit með stjörnu verður að fylla út.</div>
<script>
var RecaptchaOptions = {
theme : 'custom',
custom_theme_widget: 'recaptcha_widget'
};
</script>
<form class="formpos" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label>Skírnarnafn:<span class="red"> *</span></label>
<input class="skrainnp" type="text" name="skyr" value="<?php echo htmlspecialchars($skyr);?>" maxlength="60"/>
<span class="form_err"><?php echo $skyrErr;?></span>
</br>
</br>
<label>Eftirnafn:<span class="red"> *</span></label>
<input class="skrainnp" type="text" name="eftir" class="eftirnafn" value="<?php echo htmlspecialchars($eftir);?>" maxlength="60"/>
<span class="form_err"><?php echo $eftirErr;?></span></label>
</br>
</br>
<label>Notandanafn:<span class="red"> *</span></label>
<input class="skrainnp" type="text" name="notandi" class="notandanafn" value="<?php echo htmlspecialchars($notandi);?>" maxlength="15"/>
<span class="form_err"><?php echo $notandiErr;?></span>
<br/>
<br/>
<label>Lykilorð:<span class="red"> *</span><input class="skrainnp" type="password" name="pass" class="lykilorð" value="<?php echo htmlspecialchars($pass);?>" maxlength="15"/>
<span class="form_err"><?php echo $passErr;?></span>
</br>
</br>
<label>Staðfesta lykilorð:<span class="red"> *</span></label><input class="skrainnp" type="password" name="c_pass" class="s_lykilorð" value="<?php echo htmlspecialchars($c_pass);?>" maxlength="15"/>
<span class="form_err"><?php echo $c_passErr;?></span>
</br>
</br>
<label>Netfang:<span class= "red"> *<span></label>
<input class="skrainnp" type="text" name="mel" class="postur" value="<?php echo htmlspecialchars($mel)?>" maxlength="60"></input>
<span class="form_err"><?php echo $melErr;?></span>
</br>
</br>
<label>Netfang aftur:<span class= "red"> *<span></label>
<input class="skrainnp" type="text" name="mel_s" class="postur_s" value="<?php echo htmlspecialchars($mel_s)?>" maxlength="60"/>
<span class="form_err"><?php echo $melErr_s;?></span>
</br>
</br>
<!--RECAPTCHA-HTML BYRJAR-->
<div>
<div id="recaptcha_widget" style="display:none">
<div id="recaptcha_image"></div>
<div class="recaptcha_only_if_incorrect_sol" style="color:red"></div>
<span class="recaptcha_only_if_image">Ritaðu stafina fyrir ofan:</span>
<span class="recaptcha_only_if_audio">Ritaðu tölustafina sem þú heyrir:</span>
<input type="text" id="recaptcha_response_field" name="recaptcha_response_field" />
<div class="recaptcha_nytt">Fá nýtt</div>
<div class="recaptcha_lesa">Lesa upp</div>
<div class="recaptcha_mynd">Fá mynd</div>
<div class="recaptcha_hjalp">Hjálp</div>
<script type="text/javascript"
src="http://www.google.com/recaptcha/api/challenge?k=6LeHcvcSAAAAABMGhQ7ZqaWpJs0L0b93VKguMQwN">
</script>
<noscript>
<iframe src="http://www.google.com/recaptcha/api/noscript?k=6LeHcvcSAAAAABMGhQ7ZqaWpJs0L0b93VKguMQwN"
height="300" width="500" frameborder="0"></iframe><br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40">
</textarea>
<input type="hidden" name="recaptcha_response_field"
value="manual_challenge">
</noscript>-->
<!--RECAPTCHA-HTML ENDAR-->
<?php //RECAPTCHA
require_once('recaptchalib.php');
$publickey = "6LeHcvcSAAAAABMGhQ7ZqaWpJs0L0b93VKguMQwN"; // you got this from the signup page
echo recaptcha_get_html($publickey);
echo "<span class='recaptcha_err'>".$invalid."</span>";
?>
</br>
</br>
<input type="submit" name="sub" class="senda" value="Áfram"/>
</form>
</div>
</div>
</body>
</html>
UPTADE:
I found out that the insert statement is not working.
I know for sure that the connection is working, it's used in other file and was used when this worked correctly. Then something went wrong. I don't know why.
So, what's wrong with this code below?
$skyr = "Arnar";
$eftir = "Kristinsson";
$notandi = "afk0901";
$pass = "afk0901";
$mel = "arnarfreyr#hive.is";
$data = "INSERT INTO Login(Skírnarnafn,Eftirnafn,Notandanafn,Lykilorð,Tölvupóstur)
VALUES ('$skyr', '$eftir', '$notandi', '$pass', '$mel')";
mysqli_query($conn,$data);
mysqli_close($conn);
It looks like I've found what was wrong...it was not my code. It was the database. I used wrong Indexes. I changed Index types from unique to Index. Problem solved. Thank you who tried to answer :) I really found this out after 5 days...I don't know why I did not fell this in mind before.

Categories