I want to add Google captcha to my php form. The form adds data to my mysql database. How can I add the two parts of code together so the form checks first the captcha and after it's checked, then send it.
$servername = "";
$username = "";
$password = "";
$database = "";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$email = $_SESSION['userName'];
$contact = $_POST['naar'];
$address = $_POST['bericht'];
$sql = "INSERT INTO messages (to_user, from_user, message)
VALUES ('".$contact."', '".$email."', '".$address."')";
$conn->close();
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//form submitted
//check if other form details are correct
//verify captcha
$recaptcha_secret = "xxxxxxxxxxxxxx";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
$response = json_decode($response, true);
if($response["success"] === true)
{
echo "Logged In Successfully";
}
else
{
echo "You are a robot";
}
}
As #Dagon and #Marc B have suggested in the comments above, try this:
$servername = "";
$username = "";
$password = "";
$database = "";
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//form submitted
//check if other form details are correct
//verify captcha
$recaptcha_secret = "xxxxxxxxxxxxxx";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
$response = json_decode($response, true);
if($response["success"] === true)
{
//$conn = new mysqli($servername, $username, $password, $database);
try{
$db = new PDO('mysql:host='.$servername.';dbname='.$database,$username,$password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo "Error connecting to DB";
echo $e->getMessage();
exit();
}
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$email = $_SESSION['userName'];
$contact = $_POST['naar'];
$address = $_POST['bericht'];
$sql_pdo = "INSERT INTO messages (to_user, from_user, message)
VALUES (:contact, :email, :address)";
$stmt = $conn->prepare($sql_pdo);
try {
$result = $stmt->execute( array(
':contact' => $contact,
':email' => $email,
':address' => $address
));
if ( count($result) > 0 ) {
// Insert has gone well. Do your things here.
echo "Logged In Successfully";
}
else {
// Insert error. Report, check, ...
}
}
catch(PDOException $e){
echo 'could not insert in DB';
echo 'Error: ' . $e->getMessage();
return false;
}
$conn->close();
}
else
{
echo "You are a robot";
}
}
Related
I need to do the following to finish off my project and as im just learning but need bit of guidance to do the following:
it seems im not populating the department select with the current value in the 'edit employee form', ive been told if i use the getPersonnel.php file it returns the JSON to populate the department select, then all i need to do is set the value of the select to the departmentID value of the employee.
I also know and im going to change my php code to prepared statements to avoid sql injection.
this is my code below:
function updateEditEmployeeModal(employee) {
$.ajax({
url: './php/getPersonnel.php',
type: 'POST',
datatype: 'json',
data: {employeeId: employee.id},
success:function(result){
// console.log(result);
$('#editEmployeeId').html(result.data.personnel[0].id);
$('#editEmployeeFirstNameInput').val(`${result.data.personnel[0].firstName}`);
$('#editEmployeeLastNameInput').val(`${result.data.personnel[0].lastName}`);
$('#editEmployeePositionInput').val(result.data.personnel[0].jobTitle);
$('#editEmployeeEmailInput').val(result.data.personnel[0].email);
$("#editEmployeeDepartmentSelect").val(result.data.personnel[0].departmentId).change();
},
error: function(err){
console.log(err);
}
});
and getPersonnel.php file ::
<?php
// example use from browser
// http://localhost/companydirectory/libs/php/getPersonnel.php?id=1
// remove next two lines for production
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$executionStartTime = microtime(true);
include("config.php");
header('Content-Type: application/json; charset=UTF-8');
$conn = new mysqli($cd_host, $cd_user, $cd_password, $cd_dbname, $cd_port, $cd_socket);
if (mysqli_connect_errno()) {
$output['status']['code'] = "300";
$output['status']['name'] = "failure";
$output['status']['description'] = "database unavailable";
$output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
$output['data'] = [];
mysqli_close($conn);
echo json_encode($output);
exit;
}
// first query
$employeeId = $_REQUEST['employeeId'];
$query = $query = "SELECT p.id, p.lastName, p.firstName, p.jobTitle, p.email, p.departmentID as departmentId, d.name as department, l.name as location FROM personnel p LEFT JOIN department d ON (d.id = p.departmentID) LEFT JOIN location l ON (l.id = d.locationID) WHERE p.id = '$employeeId';";
$result = $conn->query($query);
if (!$result) {
$output['status']['code'] = "400";
$output['status']['name'] = "executed";
$output['status']['description'] = "query failed";
$output['data'] = [];
mysqli_close($conn);
echo json_encode($output);
exit;
}
$personnel = [];
while ($row = mysqli_fetch_assoc($result)) {
array_push($personnel, $row);
}
$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "success";
$output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
$output['data']['personnel'] = $personnel;
mysqli_close($conn);
echo json_encode($output);
?>
In have an array that looks like this
$content = [["4","1",1,9],["1","3",3,1],["3","4",4,7]]
I would like to insert those values into the database, this is what i've had tried
if(is_array($content)) {
foreach ($content as $c) {
list($job_id, $job_bay_id, $row, $col) = explode(',', $c);
try {
update_calendar($job_id, $job_bay_id, $row, $col);
} catch (Exception $ex) {
$_SESSION["errorMsg"] = $ex->getMessage();
$_SESSION["errorType"] = "danger";
}
}
}
function update_calendar($job_id, $job_bay_id, $row, $col){
global $DB;
$sql1 = "UPDATE " . TBL_CALENDAR . " SET `job_bay_id` = :job_bay_id, `tbl_row` = :row, `tbl_col` = :col WHERE `job_id` = :job_id ";
try {
$stmt = $DB->prepare($sql1);
$stmt->bindValue(":job_bay_id", $job_bay_id);
$stmt->bindValue(":row", $row);
$stmt->bindValue(":col", $col);
$stmt->bindValue(":job_id", $job_id);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
}
Here is the code:
include_once('class.database.php');
class ManageUsers{
public $link;
function __construct(){
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
return $this->link;
}
function registerUsers($password, $ip_address, $date, $time, $username, $email, $uname){
$query = $this->link->prepare("INSERT INTO users (password,ip_address,date,time,username, email, uname) VALUES(?,?,?,?,?,?,?)");
$values = array ($password, $ip_address, $date, $time, $username, $email, $uname);
$query->execute($values);
$count = $query->rowCount();
return $count;
}
function LoginUsers($username, $password){
$query = $this->link->query("SELECT * FROM users WHERE username='$username' AND password='$password'");
$rowCount = $query->rowCount();
return $rowCount;
}
function GetUserInfo($username){
$query = $this->link->query("SELECT * FROM users WHERE username = '$username'");
$rowCount = $query->rowCount();
if($rowCount ==1)
{
$result = $query->fetchAll();
return $result;
}
else
{
return $rowCount;
}
}
}
and it is showing me this error
Fatal error: Call to a member function query() on a non-object in
C:\wamp\www\timetable\class.ManageUsers.php on line 22
I have a xamp based webserver and I installed attendance system , I have 10 users registered to enter their attendance by login individually... issue is in login page accept any password and not giving error that password is wrong. Like you enter user id john#abcd.com & password gfjhgh its accept and entered to index page , the original password is 123456 but its accept every thing you type. Please tell me how to solve. It should says that you entered wrong password and can not login.
Code is below:- Complete sign-in.php
<?php
// Check if install.php is present
if(is_dir('install')) {
header("Location: install/install.php");
} else {
if(!isset($_SESSION)) session_start();
// Access DB Info
include('config.php');
// Get Settings Data
include ('includes/settings.php');
$set = mysqli_fetch_assoc($setRes);
// Include Functions
include('includes/functions.php');
// Include Sessions & Localizations
include('includes/sessions.php');
// Check if the User is all ready signed in
if ((isset($_SESSION['tz']['userId'])) && ($_SESSION['tz']['userId'] != '')) {
header('Location: index.php');
}
$msgBox = '';
$installUrl = $set['installUrl'];
$siteName = $set['siteName'];
$siteEmail = $set['siteEmail'];
// Account Log In
if (isset($_POST['submit']) && $_POST['submit'] == 'signIn') {
if($_POST['emailAddy'] == '') {
$msgBox = alertBox($accEmailReq, "<i class='fa fa-times-circle'></i>", "danger");
} else if($_POST['password'] == '') {
$msgBox = alertBox($accPassReq, "<i class='fa fa-times-circle'></i>", "danger");
} else {
$usrEmail = htmlspecialchars($_POST['emailAddy']);
$check = "SELECT userId, userFirst, userLast, isActive FROM users WHERE userEmail = '".$usrEmail."'";
$res = mysqli_query($mysqli, $check) or die('-1' . mysqli_error());
$row = mysqli_fetch_assoc($res);
$count = mysqli_num_rows($res);
if ($count > 0) {
// If the account is Active - Allow the login
if ($row['isActive'] == '1') {
$userEmail = htmlspecialchars($_POST['emailAddy']);
$password = encodeIt($_POST['password']);
if($stmt = $mysqli -> prepare("
SELECT
userId,
userEmail,
userFirst,
userLast,
location,
superUser,
isAdmin
FROM
users
WHERE
userEmail = ?
AND password = ?
")) {
$stmt -> bind_param("ss",
$userEmail,
$password
);
$stmt -> execute();
$stmt -> bind_result(
$userId,
$userEmail,
$userFirst,
$userLast,
$location,
$superUser,
$isAdmin
);
$stmt -> fetch();
$stmt -> close();
if (!empty($userId)) {
if(!isset($_SESSION))session_start();
$_SESSION['tz']['userId'] = $userId;
$_SESSION['tz']['userEmail'] = $userEmail;
$_SESSION['tz']['userFirst'] = $userFirst;
$_SESSION['tz']['userLast'] = $userLast;
$_SESSION['tz']['location'] = $location;
$_SESSION['tz']['superUser'] = $superUser;
$_SESSION['tz']['isAdmin'] = $isAdmin;
// Add Recent Activity
$activityType = '1';
$tz_uid = $userId;
$activityTitle = $userFirst.' '.$userLast.' '.$accSignInAct;
updateActivity($tz_uid,$activityType,$activityTitle);
// Update the Last Login Date for User
$sqlStmt = $mysqli->prepare("UPDATE users SET lastVisited = NOW() WHERE userId = ?");
$sqlStmt->bind_param('s', $userId);
$sqlStmt->execute();
$sqlStmt->close();
header('Location: index.php');
} else {
// Add Recent Activity
$activityType = '0';
$tz_uid = '0';
$activityTitle = $accSignInErrAct;
updateActivity($tz_uid,$activityType,$activityTitle);
$msgBox = alertBox($accSignInErrMsg, "<i class='fa fa-warning'></i>", "warning");
}
}
} else {
// Add Recent Activity
$activityType = '0';
$tz_uid = $row['userId'];
$activityTitle = $row['userFirst'].' '.$row['userLast'].' '.$signInUsrErrAct;
updateActivity($tz_uid,$activityType,$activityTitle);
// If the account is not active, show a message
$msgBox = alertBox($inactAccMsg, "<i class='fa fa-warning'></i>", "warning");
}
} else {
// Add Recent Activity
$activityType = '0';
$tz_uid = '0';
$activityTitle = $noAccSignInErrAct;
updateActivity($tz_uid,$activityType,$activityTitle);
// No account found
$msgBox = alertBox($noAccSignInErrMsg, "<i class='fa fa-times-circle'></i>", "danger");
}
}
}
// Reset Account Password
if (isset($_POST['submit']) && $_POST['submit'] == 'resetPass') {
// Validation
if ($_POST['accountEmail'] == "") {
$msgBox = alertBox($accEmailReq, "<i class='fa fa-times-circle'></i>", "danger");
} else {
$usrEmail = htmlspecialchars($_POST['accountEmail']);
$query = "SELECT userEmail FROM users WHERE userEmail = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s",$usrEmail);
$stmt->execute();
$stmt->bind_result($emailUser);
$stmt->store_result();
$numrows = $stmt->num_rows();
if ($numrows == 1) {
// Generate a RANDOM Hash for a password
$randomPassword = uniqid(rand());
// Take the first 8 digits and use them as the password we intend to email the Employee
$emailPassword = substr($randomPassword, 0, 8);
// Encrypt $emailPassword for the database
$newpassword = encodeIt($emailPassword);
//update password in db
$updatesql = "UPDATE users SET password = ? WHERE userEmail = ?";
$update = $mysqli->prepare($updatesql);
$update->bind_param("ss",
$newpassword,
$usrEmail
);
$update->execute();
$qry = "SELECT userId, userFirst, userLast, isAdmin FROM users WHERE userEmail = '".$usrEmail."'";
$results = mysqli_query($mysqli, $qry) or die('-2' . mysqli_error());
$row = mysqli_fetch_assoc($results);
$theUser = $row['userId'];
$isAdmin = $row['isAdmin'];
$userName = $row['userFirst'].' '.$row['userLast'];
if ($isAdmin == '1') {
// Add Recent Activity
$activityType = '3';
$activityTitle = $userName.' '.$admPassResetAct;
updateActivity($theUser,$activityType,$activityTitle);
} else {
// Add Recent Activity
$activityType = '3';
$activityTitle = $userName.' '.$usrPassResetAct;
updateActivity($theUser,$activityType,$activityTitle);
}
$subject = $siteName.' '.$resetPassEmailSub;
$message = '<html><body>';
$message .= '<h3>'.$subject.'</h3>';
$message .= '<p>'.$resetPassEmail1.'</p>';
$message .= '<hr>';
$message .= '<p>'.$emailPassword.'</p>';
$message .= '<hr>';
$message .= '<p>'.$resetPassEmail2.'</p>';
$message .= '<p>'.$resetPassEmail3.' '.$installUrl.'sign-in.php</p>';
$message .= '<p>'.$emailTankYouTxt.'<br>'.$siteName.'</p>';
$message .= '</body></html>';
$headers = "From: ".$siteName." <".$siteEmail.">\r\n";
$headers .= "Reply-To: ".$siteEmail."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
mail($usrEmail, $subject, $message, $headers);
$msgBox = alertBox($resetPassMsg1, "<i class='fa fa-check-square'></i>", "success");
$stmt->close();
} else {
// Add Recent Activity
$activityType = '1';
$tz_uid = '0';
$activityTitle = $resetPassMsgAct;
updateActivity($tz_uid,$activityType,$activityTitle);
// No account found
$msgBox = alertBox($resetPassMsg2, "<i class='fa fa-times-circle'></i>", "danger");
}
}
}
Place
$stmt->store_result();
after $stmt -> execute(); and before $stmt->bind_result(....);
Make sure to place $stmt -> close() at the end of the your all conditions.
and Check whats the result of your $userId is returning Before if (!empty($userId)) { .... }
i added $stmt->store_result(); after $stmt -> execute(); and before $stmt->bind_result(....); and sure to place $stmt -> close() at the end of the your all conditions. but still all users can logins with every password like klklfjnbjfhg but original password is 123456
So i'm trying to execute a Insert Statement using PHP, but when i call the part of the code that should do it, nothing happends...
Already checked it up to see what's going wrong, but could't find out.
Here's the JavaScript function that calls the PHP code.
function comparaSenhas(){
var pass = document.getElementById("pwd1").value;
var pass2 = document.getElementById("pwd2").value;
if(pass !== pass2){
return false;
}else{
return true;
}
}
function postData(){
var hr = new XMLHttpRequest();
var url = "../mysql.php";
var fstnm = document.getElementById("fn").value;
var lstnm = document.getElementById("ln").value;
var dtnasc = document.getElementById("dn").value;
var email = document.getElementById("em").value;
var senha = document.getElementById("pwd1").value;
var vars = "fname="+fstnm+"&lname="+lstnm+"&dt_nasc="+dtnasc+"&email="+email+"&senha="+senha;
if(comparaSenhas()){
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
alert(return_data);
}
}
hr.send(vars);
}
}
And here's the PHP code that i'm using.
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "godienski";
$dbname = "web";
//create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("insert into usuarios(first_name, last_name, data_nascimento, email, senha) values (?,?,?,?,?);");
$stmt->bind_param("sssss",$firstname,$lastname,$dtnascimento,$mail,$password);
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$dtnascimento = $_POST['dt_nasc'];
$mail = $_POST['email'];
$password = $_POST['senha'];
$stmt->execute();
$stmt->close();
$conn->close();
?>
</body>
</html>
Can anyone help?