Check mysqli Insert Query excuted ok and display message and send email - php

I am creating a registration form for a project, nothing secure or advanced, i am still fairly new to php etc.
I insert the data needed to into a login table and a customer tbl, the data inserts fine. But i cant get the code to check that its worked and fire off a an email and display a message to the user.
I have tried using a value retrieved from the database which would only be there is the user registered successfuly.
if($userID != null)
{
$msg1 = "Thank You! you are now registered, please check your email for a verification link to verify your new account! ";
$col1 = "green";
//require_once "Mail.php";
require_once "inc/email.php";
}
I have also tried this
if($query)
{
$msg1 = "Thank You! you are now registered, please check your email for a verification link to verify your new account! ";
$col1 = "green";
//require_once "Mail.php";
require_once "inc/email.php";
}
Thanks,
Edit - Here is all the code,
<?php
include ("inc/mysql.php");
error_reporting(0);
$msg = "";
$col = 'green';
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$name = $email = $chkemail = $password = $chkpassword =$address = $towncity = $postcode = "";
//Required field validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$msg = "Name is required";
$col = 'red';
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$msg = "Email is required";
$col = 'red';
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["chkemail"])) {
$msg = "Please confirm your email address";
$col = 'red';
} else {
$chkemail = test_input($_POST["chkemail"]);
}
if (empty($_POST["password"])){
$msg = "Please enter a password";
$col = 'red';
}
if (empty($_POST["chkpassword"])){
$msg = "Please confirm your password ";
$col = 'red';
} else{
$chkpassword = test_input($_POST["chkpassword"]);
if(($_POST["password"]) != $chkpassword) {
$msg = "Please check your password is correct";
$col = 'red';
} else{
$password = test_input($_POST["password"]);
}
}
if (empty($_POST["address"])) {
$msg = "Please enter the first line of your address";
$col = 'red';
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["towncity"])) {
$msg = "Please enter the first line of your Town or City";
$col = 'red';
} else {
$towncity= test_input($_POST["towncity"]);
}
if (empty($_POST["postcode"])) {
$msg = "Please enter your postcode";
$col = 'red';
} else {
$postcode = test_input($_POST["postcode"]);
$customerVeri = "N";
if($customerVeri == "N"){
$name = mysqli_real_escape_string($db, $name);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password.substr($email,0,3));
$chkpassword = md5($password.substr($email,0,3));
$verifyLink = md5(substr($name,0,3).substr($email,0,3));
$sql="SELECT customerEmail FROM customer_tbl WHERE customerEmail='$email'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
$msg1 = "Sorry...This email already exists, please enter another or login...";
$col1 = "red";
}
else
{
$query = mysqli_query($db, "INSERT INTO login_tbl (customerEmail, customerPassword)VALUES ('$email', '$password')");
$sql="SELECT userID FROM login_tbl WHERE customerEmail='$email'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$userID = $row['userID'];
$query2 = mysqli_query($db, "INSERT INTO customer_tbl (customerName, userID, customerEmail, customerPassword, customerAddress, customerTowncity, customerPostcode, customerVerified, customerVerifiedlink)VALUES ('$name', '$userID', '$email', '$password','$address','$towncity','$postcode','$customerVeri','$verifyLink')");
echo("Error description: " . mysqli_error($db));
}
}
}
}
if($userID != null)
{
$msg1 = "Thank You! you are now registered, please check your email for a verification link to verify your new account! ";
$col1 = "green";
//require_once "Mail.php";
require_once "inc/email.php";
}
echo '<div style="color:'.$col.'">';
echo $msg;
echo '</div>';
echo '<div style="color:'.$col1.'">';
echo $msg1;
echo '</div>';
?>

Seems there was no issue, but instead an issue with the email.php that stopped the rest of the statement being executed. Now to pick that to bits. Sometimes a few hours away from the screen is all it needs!
Thanks all that answered..

You shouldn't check every statement for the success
The modern programming doesn't work this way. Any statement can report an error in case one occurs. While if there was no error, then everything went all right.
So, just get rid of all conditions and send your email.

Related

Cannot make register to work with reCAPTCHA2

I cannot make the register to work with recaptcha but it work normally without it
<?php
require_once("database.php");
$conn= pdo_con();
ini_set('SMTP','smtp.intnet.mu');
ini_set('smtp_port',25);
ini_set('sendmail_from','admin#example.co.uk');
if(!empty($_POST) || isset($_POST['regis_submit'])){
// Should the code be place here cause I already try it. //
$errors = array();
if (empty($_POST['firstname']) || empty($_POST['regis_username']) || empty($_POST['lastname']) || empty($_POST['inputEmail'])
|| empty($_POST['phone_num']) || empty($_POST["gender"]) || empty($_POST['regis_pass']) || empty($_POST["postal_address"])
|| empty($_POST["DateField"]) ){
$errors[] = 'Value(s) in the form missing, please fill them all out!';
exit();
} else if(!preg_match ('%^[A-Za-zÀàÂâÇçÉéÈèÊêËëÔôÙùÎîÏïÛûÜü\.\' \-]{2,15}$%', $_POST['firstname'])){
$errors['firstname'] = '<p><font color="red">Please enter your first name!</font></p>';
exit();
} else if ( etc...
}
else if (count($errors) > 0) {
foreach($errors as $error) {
echo $error;
}
} else {
$firstname = escape_data($_POST['firstname']);
$username = escape_data($_POST['regis_username']);
$lastname = escape_data($_POST['lastname']);
$email = escape_data($_POST['inputEmail']);
$telephone = escape_data($_POST['phone_num']);
$password = escape_data($_POST['regis_pass']);
$address = escape_data($_POST['postal_address']);
$gender = escape_data($_POST['gender']);
$date = escape_data($_POST['DateField']);
//check if user already exist
$exist = "";
$query = $heidisql->prepare("SELECT user_id as 'exist' FROM users WHERE user_username='$username' OR email_address='$email' ");
$query->execute();
while($userRow = $query->fetch(PDO::FETCH_ASSOC)) {
$exist = $userRow['exist'];
}
if(strlen($exist) > 0){
echo 'Account already exist!';
exit();
} else {
$sql = "";
$stmt = $heidisql->prepare($sql);
$token = bin2hex(random_bytes(20));
$hash = password_hash($password, PASSWORD_BCRYPT);
$stmt->execute(array ( ... ));
my email here
if (mail($to, $subject, $message, $headers)) { // Sending email // email_to, subject, body,email_from
echo 'Thank you for your registration. Check your email, and click on the link to activate your account ';
exit();
} else {
echo'Server failed to sent message, please try again later.';
exit();
}
}
} // END of else statement
exit();
}
debug($errors);
}
WHere exactly should I put the captcha code below into my code... I already try to put it on top but I get an error. Undefined $responseKey or something like that.
$secretKey = "xxxx";
$responseKey = $_POST['g-recaptcha-response'];
$userIP = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify";
$response = file_get_contents($url."?secret=".$secretKey."&response=".$responseKey."&remoteIP=".$userIP);
$data_response = json_decode($response);
if(isset($data_response->success) AND $data_response==true){
} else {
}
The and div are properly place into my form. I just cant pinpoint where the code should be placed exactly.

Insert from php into mysql database

I've created an mail server with dovecot postfix and mysql.
The user should be able to create a new mail adress via a php webpage which will insert the data into the mysql database.
It also does insert it into the DB, but the connection to the mail server wont work with that credentials.
When I insert the same things myself sirectly into the DB it works, can you please give that code a look and tell me what might be wrong?
I think it has something todo with the password hash generation with doveadm.
<?php
ob_start();
session_start();
if( isset($_SESSION['user'])!="" ){
header("Location: home.php");
}
include_once 'dbconnect.php';
$error = false;
if ( isset($_POST['btn-signup']) ) {
// clean user inputs to prevent sql injections
$name = trim($_POST['name']);
$name = strip_tags($name);
$name = htmlspecialchars($name);
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// basic name validation
if (empty($name)) {
$error = true;
$nameError = "Please enter your full name.";
} else if (strlen($name) < 3) {
$error = true;
$nameError = "Name must have atleat 3 characters.";
} else {
// check email exist or not
$query = "SELECT username FROM accounts WHERE username='$name'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count!=0){
$error = true;
$nameError = "Benutzeraccount existiert schon.";
}
}
//basic email validation
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
} else {
// check email exist or not
$query = "SELECT resetmail FROM accounts WHERE resetmail='$email'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count!=0){
$error = true;
$emailError = "Kontakt E-Mail Adresse bereits in Verwendung.";
}
}
// password validation
if (empty($pass)){
$error = true;
$passError = "Please enter password.";
} else if(strlen($pass) < 6) {
$error = true;
$passError = "Password must have atleast 6 characters.";
}
// password encrypt using SHA256();
$password = shell_exec('/usr/bin/doveadm pw -s SHA512-CRYPT -p '. $pass);
// if there's no error, continue to signup
if( !$error ) {
$query = "INSERT INTO accounts(username,domain,at,complete,resetmail,password,quota,enabled,sendonly) VALUES('$name','chillihorse.de','#','test','$email','$password','2048','1','0')";
$res = mysql_query($query);
if ($res) {
$errTyp = "success";
$errMSG = "Successfully registered, you may login now";
unset($name);
unset($email);
unset($pass);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}
}
}
?>

How to echo Empty Entry Prohibited Message generated from a query in php?

I have a form which when submitted, checks this query ->
if(isset($_POST['update']) && !empty($_POST['name']) && !empty($_POST['reg_name']))
I want to echo a message "Please fill up all the required fields." if the required fields are not filled up.
In short, it should highlight the field name which is not filled up.
The Full Code:
include ('database/abcd.php');
if ($con->connect_error)
{
die("Connection failed: " . $con->connect_error);
}
if(isset($_POST['update']))
{
$error = array();
if(empty($_POST['name']))
$error[] = 'Please fill name field';
if(empty($_POST['reg_name']))
$error[] = 'Pleae fill reg_name field';
if(count($error) < 1)
{
$name = $_POST['name'];
$reg_name = $_POST['reg_name'];
$established = $_POST['established'];
$industry = $_POST['industry'];
$about = $_POST['about'];
$website = $_POST['website'];
$mail = $_POST['mail'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$city = $_POST['city'];
$facebook = $_POST['facebook'];
$wiki = $_POST['wiki'];
$twitter = $_POST['twitter'];
$google = $_POST['google'];
$member_username = $_SESSION['username'];
$process="INSERT INTO notifications (member_username, process, icon, class) VALUES ('$_POST[member_username]','$_POST[process]','$_POST[icon]','$_POST[class]')";
if (!mysqli_query($con,$process))
{
die('Error: ' . mysqli_error($con));
}
$sql = "UPDATE `company_meta` SET `name` = '$name', reg_name = '$reg_name', wiki = '$wiki', established = '$established', industry = '$industry', about = '$about', website = '$website', mail = '$mail', phone = '$phone', address = '$address', city = '$city', facebook = '$facebook', twitter = '$twitter', google = '$google' WHERE `member_username` = '$member_username'";
if ($con->query($sql))
{
header('Location: edit.php');
}
}
else
{
$errors = implode(',' $error);
echo $errors;
}
$con->close();
}
I think what you are pass in name or reg_name is check first .may be name or reg_name can content white space so that it not showing message otherwise above code is working correctly..
if(isset($_POST['update'])) // This first check whether it is an update call
{
$error = array(); // Here we initialize an array so that we can put the messages in it.
if(empty($_POST['name'])) // If the name field is empty, push a message in $error array.
$error[] = 'Please fill name field';
if(empty($_POST['reg_name'])) // Same as above field
$error[] = 'Pleae fill reg_name field';
if(count($error) < 1) // Now this checks if the $error array has no value. If it has value it means that either or both of the above fields are empty and the else block will be executed.
{
// Submit your form
}
else
{
$errors = implode(',' $error);
echo $errors;
}
}
else
{
// Update not triggered.
}

Registration and Log in form

I have created registration form which sends a link via e-mail and you have to click it in order to be successfully registered, which makes you have to log in. The problem is that I can't log in, while everything else is working fine. Below you will find my register.php, activation.php and login.php. Any help would be great.
action = register.php
if ($_GET['action'] == 'register') {
if(isset($_POST['formsubmitted'])){
$error = array();
if(empty($_POST['username'])){
$error[] = 'Please enter a username';
}else{
$username = $_POST['username'];
}
if(empty($_POST['email'])){
$error[] = 'Please enter a mail';
}else{
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/",$_POST['email'])) {
$email = $_POST['email'];
}else{
$error[] = 'Your mail is invalid';
}
}
if (empty($_POST['password'])){
$error[] = 'Please enter a password';
}else{
$password = $_POST['password'];
$password = md5(uniqid(rand(),true));
}
if (empty($error)){
$verify_email = "SELECT * FROM members WHERE email = '$email'";
$result_verify_email = mysql_query($verify_email,$lnk);
if (!$result_verify_email){
echo 'Database error';
}
if (mysql_fetch_assoc($result_verify_email) == 0){
$activationCode = md5(uniqid(rand(),true));
$insert_users = "INSERT INTO members VALUES ('','".$username."','".$email."','".$password."','".$activationCode."',0)";
$result_insert_users = mysql_query($insert_users,$lnk);
if(!$result_insert_users){
echo 'Database error';
}
if(mysql_affected_rows($lnk) == 1){
$message = 'To activate your account, please click on this link:\n\n";';
$message .= WEBSITE_URL . '/index.php? page=activation&action=activation&key='.$activationCode;
mail(
$email,
'Registration Confirmation',
$message,
'FROM:' . EMAIL
);
echo 'A confirmation email has been sent to ' . $Email . ' Please click on the Activation Link';
}else {
echo 'You could not be registered';
}
}else {
echo 'That email address has already been registered.</div>';
}
action = activation
if ($_GET['action'] == 'invitation') {
if (!empty($_GET['key'])){
//thelw na eleksw an afto to key uparxei sto tabale members
$sql = "SELECT * FROM members WHERE activationCode = '".$_GET['key']."'";
$result=mysql_query($sql,$lnk);
$user= mysql_fetch_assoc($result);
if(!empty($user)){
//edw tha energopoiisw ton xristi
$sql = "UPDATE members SET flag=1 WHERE username = '".$user['username']."'";
mysql_query($sql,$lnk);
}else{
echo "this is WRONG";
}
}else{
echo 'No key';
}
}
action = login
if ($_GET['action'] == 'login') {
$error = array();
if (empty($_POST['username'])) {
$error[] = 'You forgot to enter your username ';
} else{
$username = $_POST['username'];
}
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = $_POST['password'];
$password = md5(uniqid(rand(),true));
}
$check_credentials = "SELECT * FROM members WHERE username = '".$username."' AND password = '".$password."' AND flag = '1' ";
$result_check_credentials = mysql_query($check_credentials,$lnk);
$user_check_credentials = mysql_fetch_assoc($result_check_credentials);
if(!empty($user_check_credentials)){
$_SESSION['Auth'] = $user_check_credentials['username'];
header('location:index.php?page=home');
}else{
$message = '<img src="css/photos/zzzdoop.png"> ';
$_SESSION['Auth'] = false;
}
} elseif ($_GET['action'] == 'logout') {
$_SESSION['Auth'] = false;
}
you are doing wrong with password.
use below code
if ($_GET['action'] == 'register') {
if(isset($_POST['formsubmitted'])){
$error = array();
if(empty($_POST['username'])){
$error[] = 'Please enter a username';
}else{
$username = $_POST['username'];
}
if(empty($_POST['email'])){
$error[] = 'Please enter a mail';
}else{
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/",$_POST['email'])) {
$email = $_POST['email'];
}else{
$error[] = 'Your mail is invalid';
}
}
if (empty($_POST['password'])){
$error[] = 'Please enter a password';
}else{
$password = md5($_POST['password']);
}
if (empty($error)){
$verify_email = "SELECT * FROM members WHERE email = '$email'";
$result_verify_email = mysql_query($verify_email,$lnk);
if (!$result_verify_email){
echo 'Database error';
}
if (mysql_fetch_assoc($result_verify_email) == 0){
$activationCode = md5(uniqid(rand(),true));
$insert_users = "INSERT INTO members VALUES ('','".$username."','".$email."','".$password."','".$activationCode."',0)";
$result_insert_users = mysql_query($insert_users,$lnk);
if(!$result_insert_users){
echo 'Database error';
}
if(mysql_affected_rows($lnk) == 1){
$message = 'To activate your account, please click on this link:\n\n";';
$message .= WEBSITE_URL . '/index.php? page=activation&action=activation&key='.$activationCode;
mail(
$email,
'Registration Confirmation',
$message,
'FROM:' . EMAIL
);
echo 'A confirmation email has been sent to ' . $Email . ' Please click on the Activation Link';
}else {
echo 'You could not be registered';
}
}else {
echo 'That email address has already been registered.</div>';
}
and for login
if ($_GET['action'] == 'login') {
$error = array();
if (empty($_POST['username'])) {
$error[] = 'You forgot to enter your username ';
} else{
$username = $_POST['username'];
}
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = md5($_POST['password']);
}
$check_credentials = "SELECT * FROM members WHERE username = '".$username."' AND password = '".$password."' AND flag = '1' ";
$result_check_credentials = mysql_query($check_credentials,$lnk);
$user_check_credentials = mysql_fetch_assoc($result_check_credentials);
if(!empty($user_check_credentials)){
$_SESSION['Auth'] = $user_check_credentials['username'];
header('location:index.php?page=home');
}else{
$message = '<img src="css/photos/zzzdoop.png"> ';
$_SESSION['Auth'] = false;
}
} elseif ($_GET['action'] == 'logout') {
$_SESSION['Auth'] = false;
}
I'm guessing the error is here:
action = login
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = $_POST['password'];
$password = md5(uniqid(rand(),true)); // HERE
}
You've just changed your password into something completely random, then you are trying to look for it in the database...
The key to programming is understanding what you are doing and knowing methods to determine what is wrong. It is ALL about problem solving. As you can see in your code: (action = login)
else {
$password = $_POST['password'];
$password = md5(uniqid(rand(),true));
}
You generate a random password each time rather than hashing the password that was provided. You then go on to check if it exists with the user. You need to make it like your registration method:
$password = md5($_POST['password']);
Another problem you have is in your query to check for valid user. Your flag field is an int but you're treating it like a string.
AND flag = '1' ";
needs to be
AND flag = 1 ";
NOTICE: DO NOT USE MySQL_* for it has been deprecated as of PHP 5.5. Use MySQLi_* or PDO. You are also wide open for SQL injections, be careful.

trying insert a checkbox in a form of terms and condition

I am trying to input a check-box for terms and conditions in a form, but when I registered the form without ticking the box the registration went through , (which was not suppose to be). Please help have a look.
<?php
echo "<h2>Register</h2>";
$submit = $_POST['register'];
//form data
$fullname = mysql_real_escape_string(htmlentities(strip_tags($_POST['fullname'])));
$username = strtolower(mysql_real_escape_string(htmlentities(strip_tags($_POST['username']))));
$password = mysql_real_escape_string(htmlentities(strip_tags($_POST['password'])));
$repeatpassword = mysql_real_escape_string(htmlentities(strip_tags($_POST['repeatpassword'])));
$email = mysql_real_escape_string(htmlentities(strip_tags($_POST['email'])));
$houseno = mysql_real_escape_string(htmlentities(strip_tags($_POST['houseno'])));
$addressa = mysql_real_escape_string(htmlentities(strip_tags($_POST['addressa'])));
$addressb = mysql_real_escape_string(htmlentities(strip_tags($_POST['addressb'])));
$addressc = mysql_real_escape_string(htmlentities(strip_tags($_POST['addressc'])));
$county = mysql_real_escape_string(htmlentities(strip_tags($_POST['county'])));
$state = mysql_real_escape_string(htmlentities(strip_tags($_POST['state'])));
$country = mysql_real_escape_string(htmlentities(strip_tags($_POST['country'])));
$accept = mysql_real_escape_string(htmlentities(strip_tags($_POST['accept'])));
if ($submit)
{
$namecheck = mysql_query("SELECT username FROM reusers WHERE username='$username'");
$count = mysql_num_rows($namecheck);
if($count!=0)
{
die("Username already taken!");
}
//check for registration form details
if ($fullname&&$username&&$password&&$repeatpassword&&$email&&$houseno&&$addressa&&$county&&$state&&$country)
{
if($accept!= 1)
{
if ($password==$repeatpassword)
{
//check char lenght of username and fullname
if (strlen($username)>25||strlen($fullname)>25)
{
echo "Lenght of username or fullname is too long";
}
else
{
//check password length
if(strlen($password)>25||strlen($password)<6)
{
echo"Password must be between 6 and 25 characters";
}
else
{
//check password length
$emailcheck = mysql_query("SELECT email FROM reusers WHERE email='$email'");
$ecount = mysql_num_rows($emailcheck);
if($ecount!=0)
{
echo"email already registered Please sign in into your account to continue";
}
else
{
//generate random code
$code = rand(11111111,99999999);
//send activation email
$to = $email;
$subject = "Activate your account";
$headers = "From: donotreply#reacheasy.co.uk";
$body = " Hello $fullname,\n\nUsername $username,\n\n Password $password ,\n\nYou registered `and need to activate your account. Click the link below or paste it into the URL bar of your browser\n\nhttp://reach.co.uk/activate.php?code=$code\n\nThanks!";
if (!mail($to,$subject,$body,$headers))
echo "We couldn't sign you up at this time. Please try again later.";
else
{
//register the user!
//encript password
$password = md5($password);
$repeatpassword = md5($repeatpassword);
$queryreg = mysql_query("
INSERT INTO reusers VALUES ('','$fullname','$username','$password','$email','$code','0','houseno','addressa','addressb','addressc','county','state','country')
");
die("You have been registered successfully! Please check your email ($email) to activate your account<a href='index.php'>Return to login page</a>");
}
}
}
}
}
else
echo"Your passwords do not match!";
}
else
echo"Please read and accept Terms and Conditions before registering!";
}
else
echo "Please fill in <b>all</> fields!";
}
?>
$accept = ($_POST['accept'] ? 1:0);
You must use
if($accept == 1)
because $_POST['accept'] = 1 when you check the checkbox.
Now return Please read and accept Terms and Conditions before registering! when checkbox is checked and register the user when checkbox is not checked.

Categories