I am creating a user management system. During the registration process the user enters their personal information, including the address attribute.
<?php
include("database.php");
$error = "";
if(isset($_POST['submit']))
{
$username = mysql_real_escape_string($_POST['username']);
$name = mysql_real_escape_string($_POST['name']);
$address = mysql_real_escape_string($_POST['address']);
$passwordConfirm = $_POST['passwordConfirm'];
$privacy = $_POST['privacy'];
//validare i valori inseriti dall'utente
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error = "Inserisci una email valida ";
}
else if (strlen($password < 8)) {
$error = "La password deve contenere almeni 8 caratteri";
}
else if ($password != $passwordConfirm)
{
$error = "Le password devono coincidere!";
}
else {
$error = "Ti sei appena registrato";
}
$sql = "INSERT INTO users(username, name, surname, affiliation, department,address,position,email,web,telephone,mobile,password,privacy) VALUES('$username','$name','$surname','$affiliation','$department','$address','$position','$email','$web','$telephone','$mobile','$password','$privacy')";
mysqli_query($database,$sql) or die(mysqli_error($database));
header("location:index.php");
}
echo "$error";
?>
Thanks to 'geocode.php' I get the geographical coordinates of the address. I managed to implement a version in which the geolocation occurs after user registration. In this way (geocode.php)
<?php
session_start();
include("database.php");
if(isset($_SESSION['username'])){
$current_user = $_SESSION['username'];
$sql = "SELECT address FROM users WHERE username='$current_user'";
$result = mysqli_query($database,$sql);
$row = mysqli_fetch_array($result);
}
$address = urlencode($row['address']);
$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$address."&sensor=true";
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->status;
if ($status=="OK"){
$lat = $xml->result->geometry->location->lat;
$lng = $xml->result->geometry->location->lng;
$latlng = "$lat,$lng";
}
if(isset($_SESSION['username'])){
$temp=$_SESSION['username'];
$sql1 = "UPDATE users SET lat='$lat',lng='$lng' WHERE username='$temp'";
mysqli_query($database,$sql1);
}
?>
I wish I had some advice to make sure that the API call to google maps occurs during user registration.
I am not 100% sure what you are looking for.
According my understanding you want to add geo location code during registration process.
what you can do is you add following code after sanitizing address.
if($address !='')
{
$address_code = urlencode($row['address']);
$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$address_code."&sensor=true";
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->status;
if ($status=="OK"){
$lat = $xml->result->geometry->location->lat;
$lng = $xml->result->geometry->location->lng;
$latlng = "$lat,$lng";
}
// Now you have latitude and Longitude saved in $lat and $lang respectively. You can add this in your insert query.
}
I hope this make sense.
Related
I don't know exactly how to explain ...
When I log in, on a browser page, enter the correct user, but if I open another page, still in the browser in use, and I refresh it automatically chooses one of the two users, deleting the other
I don't know if I have explained myself well, I don't know how to explain myself well. excuse me
This is a private page code (page after log in)
session_start();
function authenticate()
{
return array_key_exists('email', $_SESSION);
};
if (authenticate() !== true) {
header("location: /private/login/log-in.php");
}
$user_id = $_SESSION['id'];
$email = $_SESSION['email'];
$password = $_SESSION['password'];
$check_id = "SELECT * FROM usertable WHERE email = '$email'";
$result = mysqli_query($conn, $check_id);
if (mysqli_num_rows($result) > 0) {
$fetch_info = mysqli_fetch_assoc($result);
$user_id = $fetch_info['id'];
};
This is a login code
session_start();
$user_id = $_SESSION['id'];
$email = $_SESSION['email'];
$password = $_SESSION['password'];
$check_id = "SELECT * FROM usertable WHERE email = '$email'";
$result = mysqli_query($conn, $check_id);
if (mysqli_num_rows($result) > 0) {
$fetch_info = mysqli_fetch_assoc($result);
};
if (isset($_POST['login'])) {
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$password = md5($_POST['password'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
date_default_timezone_set("Europe/Rome");
$date = date('Y-m-d H:i:s');
$sql_insert_date = mysqli_query($conn, "UPDATE usertable SET activeLogInDate = '$date'");
$check_email = "SELECT * FROM usertable WHERE email = '$email' ";
$res = mysqli_query($conn, $check_email);
if (mysqli_num_rows($res) > 0) {
$fetch = mysqli_fetch_assoc($res);
$_SESSION['id'] = $fetch['id'];
$uniqueID = $fetch['uniqueID'];
$username = $fetch['username'];
$name = $fetch['name'];
$fetch_pass = $fetch['password'];
if (password_verify($password, $fetch_pass)) {
$activeStatus = "Online";
$sql2 = mysqli_query($conn, "UPDATE usertable SET activeStatus = '$activeStatus'");
$_SESSION['email'] = $email;
$status = $fetch['status'];
if ($status == 'verified') {
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
header("location: /private/private_page/private.php?us=$uniqueID?nm=$username");
} else {
$info = "Non è stata verificata la tua identità,controlla il messaggio inviato all' email $email";
$_SESSION['info'] = $info;
header('location: /private/otp/otp-code.php');
}
} else {
$errors['email'] = "Inserimento password o email non corretto!";
}
} else {
$errors['email'] = "Sembra che tu non sia ancora un membro! Clicca sul pulsante registrati per iscriverti.";
}
};
The line -
$password = md5($_POST['password'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
is incorrect. md5()'s second parameter is meant to be a bool; you've got a likely copy/paste/edit error from the previous line, filter_var();
Take out the second parameter.
BTW you shouldn't really rely on md5 these days. There's a password_hash() function that's what you should be using now.
Here I have code where user is going to be created, they have to enter one accesscode given by admin. That accesscode is limited by some users like 10 or 20. After that it shows error like your accesscode is limited. So until now, it's working fine.
Now if user tries to enter accesscode that is not given by admin it has to show error message like your accesscode is wrong.
Here is my code:
<?php
require('../config.php');
require_once($CFG->dirroot . '/user/editlib.php');
$errorMessage = '';
$successMessage = '';
if(isset($_SESSION['successMessage'])) {
$successMessage = $_SESSION['successMessage'];
unset($_SESSION['successMessage']);
}
if (isset($_POST['register'])) {
$errors = array();
$data = array();
$chk_sql = "SELECT * FROM {user} u where username = ?";
if (!empty($chk_sql) ) {
$errorMessage = 'Username already taken';
}
if(!$chk_username = $DB->get_record_sql($chk_sql, array($_POST['username']))) {
$secret = $_POST['secret'];
$access_code_sql = "SELECT * FROM {accesscode} WHERE random_no= ? and `number` > `used` and status=1";
if($chk_secret = $DB->get_record_sql($access_code_sql, array($secret))) {
$cadminid = $chk_secret->cadmin_id;
$clientid = $chk_secret->clientid;
$DB->execute("UPDATE {accesscode} SET used = used+1 WHERE random_no = '$secret'");
$insert_record = new stdClass();
$insert_record->firstname = $_POST['firstname'];
$insert_record->lastname = $_POST['lastname'];
$insert_record->username = $_POST['username'];
$insert_record->secret = $secret;
$insert_record->password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$insert_record->timecreated = time();
$insert_record->maildigest = $cadminid;
$insert_record->maildisplay = $clientid;
$insert_record->idnumber = 1;
$insert_record->mnethostid = 1;
$insert_record->confirmed = 1;
$insert_record->email = $_POST['email'];
if ($result = $DB->insert_record('user', $insert_record)) {
$_SESSION['successMessage'] = "record created successfully";
header('Location: register.php');
} else
$errorMessage = "error! can you please try again";
} else
$errorMessage = "your access code limit completed";
}
}
?>
Can you give us more information about your problem? What doesn't work?Try some "var_dump()" in your loop to know if you pass through or not so you can tell us where is the problem !
But first thing I see is here :
if(! $chk_username = $DB->get_record_sql($chk_sql, array($_POST['username'])) )
and here :
if($result = $DB->insert_record('user', $insert_record))
You should use "==" or "===" because using "=" means you assign a value to "$chk_username" and "result".
Then here is some librairie you can use if you want to display flash message, this is just for your information :
https://github.com/plasticbrain/PhpFlashMessages
And if you want to do it in JS you can use : https://github.com/CodeSeven/toastr
Hope it helps !
i changed the condition like this
<?php
require('../config.php');
require_once($CFG->dirroot . '/user/editlib.php');
$errorMessage = '';
$successMessage = '';
if(isset($_SESSION['successMessage']))
{
$successMessage = $_SESSION['successMessage'];
unset($_SESSION['successMessage']);
}
if (isset($_POST['register'])) {
$errors = array();
$data = array();
$chk_sql = "SELECT * FROM {user} u where username = ?";
if (!empty($chk_sql) ) {
$errorMessage='Username already taken';
}
if(!$chk_username = $DB->get_record_sql($chk_sql, array($_POST['username']))
)
{
$secret = $_POST['secret'];
$access_code_sql = "SELECT * FROM {accesscode} WHERE random_no= ? and
status=1";
if($chk_secret = $DB->get_record_sql($access_code_sql, array($secret)) )
{
if ( $chk_secret->used >= $chk_secret->number ) {
$errorMessage = "your access code limit completed..";
}else
{
$cadminid = $chk_secret->cadmin_id;
$clientid = $chk_secret->clientid;
$DB->execute("UPDATE {accesscode} SET used = used+1 WHERE random_no = '$secret'");
$insert_record = new stdClass();
$insert_record->firstname = $_POST['firstname'];
$insert_record->lastname = $_POST['lastname'];
$insert_record->username = $_POST['username'];
$insert_record->secret = $secret;
$insert_record->password = password_hash($_POST['password'],
PASSWORD_DEFAULT);
$insert_record->timecreated = time();
$insert_record->maildigest = $cadminid;
$insert_record->maildisplay = $clientid;
$insert_record->idnumber = 1;
$insert_record->mnethostid = 1;
$insert_record->confirmed = 1;
$insert_record->email = $_POST['email'];
if($result = $DB->insert_record('user', $insert_record))
{
$_SESSION['successMessage'] = "record created successfully";
header('Location: register.php');
}
else
$errorMessage = "error! can you please try again";
}
}
else
$errorMessage = "your access code is wrong..";
}
}
?>
it's working..
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.
i would like to a fix a problem with my code, that regard an user profile system. During registration user set their personal information, including address. Address value is used by API google maps.UPDATE query doesnt work.Why?
N.B: data type lat, lng are 'decimal(10,8)decimal(11,8)'
<?php
include("database.php");
session_start();
$error = "";
if(isset($_POST['submit']))
{
$username = mysql_real_escape_string($_POST['username']);
$name = mysql_real_escape_string($_POST['name']);
$surname = mysql_real_escape_string($_POST['surname']);
$affiliation = mysql_real_escape_string($_POST['affiliation']);
$department = mysql_real_escape_string($_POST['department']);
$address = mysql_real_escape_string($_POST['address']);
$position = mysql_real_escape_string($_POST['position']);
$email = mysql_real_escape_string($_POST['email']);
$web = mysql_real_escape_string($_POST['web']);
$telephone = mysql_real_escape_string($_POST['telephone']);
$mobile = mysql_real_escape_string($_POST['mobile']);
$password = $_POST['password'];
$passwordConfirm = $_POST['passwordConfirm'];
$privacy = $_POST['privacy'];
//validare i valori inseriti dall'utente
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error = "Inserisci una email valida ";
}
else if (strlen($password < 8)) {
$error = "La password deve contenere almeni 8 caratteri";
}
else if ($password != $passwordConfirm)
{
$error = "Le password devono coincidere!";
}
else {
$error = "Ti sei appena registrato su B";
}
$sql = "INSERT INTO users(username, name, surname, affiliation, department,address,position,email,web,telephone,mobile,password,privacy) VALUES('$username','$name','$surname','$affiliation','$department','$address','$position','$email','$web','$telephone','$mobile','$password','$privacy')";
mysqli_query($database,$sql) or die(mysqli_error($database));
if($address !=''){
$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$address."&sensor=true";
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->status;
if ($status=="OK"){
$lat = $xml->result->geometry->location->lat;
$lng = $xml->result->geometry->location->lng;
}
$sql1 = "UPDATE users SET lng='$lng', lat='$lat' WHERE username='$username'";
mysqli_query($database,$sql1) or die(mysqli_error($database));
}
}
?>
instead of using AND, you need to separate with a comma ,
$sql1 = "UPDATE users SET lng='$lng', lat='$lat' WHERE username='$username'";
Do not use And and don't forget to add backticks :) and good to see that newbies are completely avoiding mysql_* :D
$sql1 = "UPDATE `users` SET `lng`='$lng', `lat`='$lat' WHERE `username`='$username'";
Replace AND with comma in update statement
I am new here, and I am continuing previous developer website for the client.
This web will sent an verification email for user after the user sign up for member in the web.
The email is send to the user but my problem now is that the verification doesn't work. When the user click on the verification link, it's does link to the verification.php but show a blank page.
I don't know where is the problem.
This is the account_verification.php file:
session_start();
require_once 'cms/configuration.php';
$username = $_GET['e_username'];
$key = $_GET['key'];
$sql = "SELECT * FROM member WHERE username = '$username'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$memberID = $row['id'];
if ($key == md5($username.$row['id']))
{
$sql = "UPDATE member SET verified = '1' WHERE id = '{$row['id']}'";
$result = mysql_query($sql);
echo ' <script type="text/javascript">
alert("Your account is activated.");
window.location = "homepage.php";
</script>';
}
?>
And this is the membersignup.php file:
<?php
session_start();
require_once 'cms/configuration.php';
include "includes/phpmailer.php";
foreach ($_POST as $key => $value)
{
$_POST[$key] = $value;
}
$e_username = trim($_POST['username']);
$password = $_POST['password'];
$ic_no = $_POST['ic_no'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$contact = $_POST['contact'];
$address = $_POST['address'];
$comp_name = $_POST['comp_name'];
$comp_address = $_POST['comp_address'];
$comp_contact = $_POST['comp_contact'];
$comp_fax = $_POST['comp_fax'];
$comp_email = $_POST['comp_email'];
$about_us = $_POST['about_us'];
$datetime = $_POST['datetime'];
;
$result = mysql_query("SELECT username FROM member WHERE username='$e_username'");
$num_records = mysql_num_rows($result);
if ($num_records !=0){
echo "Please use different username.";
exit();
}
$sql = sprintf("INSERT INTO member (username, password, ic_no,email, birthday, contact, address, company_name, company_address, company_contact, company_fax, company_email, about_us, register_date)
VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',NOW())",
mysql_real_escape_string($e_username),
md5($password),
mysql_real_escape_string($ic_no),
mysql_real_escape_string($email),
mysql_real_escape_string($dob),
mysql_real_escape_string($contact),
mysql_real_escape_string($address),
mysql_real_escape_string($comp_name),
mysql_real_escape_string($comp_address),
mysql_real_escape_string($comp_contact),
mysql_real_escape_string($comp_fax),
mysql_real_escape_string($comp_email),
mysql_real_escape_string($about_us),
mysql_real_escape_string($datetime)
);
$result = mysql_query($sql) or die(mysql_error());
$insertID = mysql_insert_id();
$key = md5($_POST['username'].$insertID);
$link = "http://___/account_verification.php?username={$_POST['username']}&key=$key";
$body = "<div>
<p style='padding:10px;'>
Hello {$_POST['username']}!
</p>
<p style='padding:10px;'>
Thank you for creating an account at ___.
</p>
<p style='padding:10px;'>
Please keep this e-mail for your records. Your account information is as follows:<br/>
Username : $e_username <br/>
Password : {$_POST['password']}
</p>
<p style='padding:10px;'>
Verify your account to complete your registration by clicking the link:<br/>
<a href='$link' target='_blank'>$link</a>
</p>
<p style='padding:10px;'> </p>
<p style='padding:10px;'>
Thanks,<br/>Admin
</p>
</div>";
$subject = "Member Registration and Verification";
if ($result)
{
$sendMailResult = sendPHPMail('noreply#___.com', '___', $_POST['email'], $subject, $body);
if($sendMailResult == TRUE)
echo 1;
else
echo "There's problem sending validation mail to your email. Please try again later.";
}
else
{
echo "There's problem saving your registration details to our database. Please try again later.";
}
?>
Can anyone help me to find what is the problem here?
You are searching for a user that matches $username = $_GET['e_username']; when you are actually only sending in the url username
So, your account_verification.php should be
session_start();
require_once 'cms/configuration.php';
$username = $_GET['username'];
$key = $_GET['key'];
$sql = "SELECT * FROM member WHERE username = '$username'";
etc ...
And your link to this script should be as follows: (note: your username variable is changed to $_POST['e_username']
$link = "http://___/account_verification.php?username={$_POST['e_username']}&key=$key";