Cannot make register to work with reCAPTCHA2 - php

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.

Related

Register new user - Problem with SQLSTATE

Implementing a simple register system and after implementing try to test it I get this error message:
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
My code for register user is:
<?php
session_start();
require_once('config.php');
if(isset($_POST['submit']))
{ if(isset($_POST['name'],$_POST['lastname'],$_POST['email'],$_POST['pass']) && !empty($_POST['name']) && !empty($_POST['lastname']) && !empty($_POST['email']) && !empty($_POST['pass']))
{
$name= trim($_POST['name']);
$lastname = trim($_POST['lastname']);
$email= trim($_POST['email']);
$pass= trim($_POST['pass']);
$options = array("cost"=>4);
$hashPassword = password_hash($pass,PASSWORD_BCRYPT,$options);
$date = date('Y-m-d H:i:s');
if(filter_var($email, FILTER_VALIDATE_EMAIL))
{
$sql = 'SELECT * FROM members WHERE email = :email';
$stmt = $pdo->prepare($sql);
$p = ['email'=>$email];
$stmt->execute($p);
if($stmt->rowCount() == 0)
{
$sql = "insert into members (name, lastname, email, `pass`, created_date,updated) values(:name,:lastname,:email,:pass,:created_date,:updated)";
try{
$handle = $pdo->prepare($sql);
$params = [
':name'=>$name,
':lastname'=>$lastname,
':email'=>$email,
':pass'=>$hashPassword,
':created_date'=>$date,
':updated'=>$date
];
$handle->execute($params);
$success = 'Successfull registration!';
}
catch(PDOException $e){
$errors[] = $e->getMessage();
}
}
else
{
$valName= $name;
$valLastname= $lastname;
$valEmail= '';
$valPass= $pass;
$errors[] = 'Email address already registered';
}
}
else
{
$errors[] = "Email address is not valid";
}
}
else
{
if(!isset($_POST['name']) || empty($_POST['name']))
{
$errors[] = 'Error 1!';
}
else
{
$valIme= $_POST['name'];
}
if(!isset($_POST['lastname']) || empty($_POST['lastname']))
{
$errors[] = 'Error 2!';
}
else
{
$valLastname= $_POST['lastname'];
}
if(!isset($_POST['email']) || empty($_POST['email']))
{
$errors[] = 'Error 4!';
}
else
{
$valEmail= $_POST['email'];
}
if(!isset($_POST['pass']) || empty($_POST['pass']))
{
$errors[] = 'Error 5!';
}
else
{
$valPass= $_POST['pass'];
}
}
}
?>
I don't get where the problem could be. I think is that I need to change the date value inserted to the database, and that could be a problem. Can someone test this code and tell me where is the problem?

localhost: data not going into database

i am trying to make a registration system but when i register the data isn't there.
i tried to search same questions but i couldn't find the issue, and the worst is that the script detect the database but wont get the data in.
The PHP script :
<?php
$bdd = new PDO('mysql:host=127.0.0.1;dbname=fireblock', 'root', '');
if(isset($_POST['submitform'])) {
$username = htmlspecialchars($_POST['username']);
$email = htmlspecialchars($_POST['email']);
$email2 = htmlspecialchars($_POST['email2']);
$pass = sha1($_POST['pass']);
$pass2 = sha1($_POST['pass2']);
if(!empty($_POST['username']) AND !empty($_POST['email']) AND !empty($_POST['email2']) AND !empty($_POST['pass']) AND !empty($_POST['pass2'])) {
$usernamelength = strlen($username);
if($usernamelength <= 255) {
if($email == $email2) {
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
$reqemail = $bdd->prepare("SELECT * FROM members WHERE email = ?");
$reqemail->execute(array($email));
$emailexist = $reqemail->rowCount();
if($emailexist == 0) {
if($pass == $pass) {
$insertmbr = $bdd->prepare("INSERT INTO members(username, email, pass) VALUES(?, ?, ?)");
$insertmbr->execute(array($username, $email, $pass));
$error = "Your account has been created! Connect";
} else {
$error = "Your passs are not the same!";
}
} else {
$error = "Email already used!";
}
} else {
$error = "Your email is invalid!";
}
} else {
$error = "Your emails are not the same!";
}
} else {
$error = "Your username can't get upper than 255 characters!";
}
} else {
$error = "Every fields should be filled!";
}
}
?>

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...";
}
}
}
?>

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

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.

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.

Categories