PHP doesn't work properly when hosted - php

I have made a Log in and Sign up system and on my localhost it worked properly but when i hosted it and created account it says Incorrect credentials. I will send a code if it is needed. And i have crated a MySql db.
Site link: http://metallicafanpage.esy.es
I am using Hostinger
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
// it will never let you open index(login) page if session is set
if ( isset($_SESSION['user'])!="" ) {
header("Location: home.php");
exit;
}
$error = false;
if( isset($_POST['btn-login']) ) {
// prevent sql injections/ clear user invalid inputs
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if(empty($email)){
$error = true;
$emailError = "Please enter your email address.";
} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
}
if(empty($pass)){
$error = true;
$passError = "Please enter your password.";
}
// if there's no error, continue to login
if (!$error) {
$password = hash('sha256', $pass); // password hashing using SHA256
$res=mysql_query("SELECT userId, userName, userPass FROM users WHERE userEmail='$email'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row
if( $count == 1 && $row['userPass']==$password ) {
$_SESSION['user'] = $row['userId'];
header("Location: home.php");
} else {
$errMSG = "Incorrect Credentials, Try again...";
}
}
}
?>
Here is Register.php
<?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 if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
$error = true;
$nameError = "Name must contain alphabets and space.";
}
//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 userEmail FROM users WHERE userEmail='$email'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count!=0){
$error = true;
$emailError = "Provided Email is already in use.";
}
}
// 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 = hash('sha256', $pass);
// if there's no error, continue to signup
if( !$error ) {
$query = "INSERT INTO users(userName,userEmail,userPass) VALUES('$name','$email','$password')";
$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...";
}
}
}
?>

This Is Because Of Your Php Mysql version Your Hosting Server Is Just Using An Old Php Or Mysql Version

Related

PHP code with oci

For email validation, the condition for checking email exist or not is failed to function and I still able to register using same email. This is code for email validation
if ( !filter_var($bemail,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
} else {
**// check email exist or not**
$result = oci_parse($connection,"SELECT BUSER_EMAIL FROM
POHSENG.BRONTE_USER WHERE BUSER_EMAIL= $bemail");
$count = oci_num_rows($result);
if($count!=0){
$error = true;
$emailError = "Provided Email is already in use.";
}
This is overall php code. I tried a lot of way to modify but it is not work at all, while in mysqli it is working.
<?php
require 'oci_connect_hugo.php';
$error = false;
$count="";
$bname="";
$bemail="";
$baddress="";
$bpass="";
$nameError = "";
$emailError ="";
$addError ="";
$passError = "";
if ( isset($_POST['signup']) ) {
// clean user inputs to prevent sql injections
$bname = trim($_POST['bname']);
$bname = strip_tags($bname);
$bname = htmlspecialchars($bname);
$bemail = trim($_POST['bemail']);
$bemail = strip_tags($bemail);
$bemail = htmlspecialchars($bemail);
$baddress =trim($_POST['baddress']);
$baddress = strip_tags($baddress);
$baddress = htmlspecialchars($baddress);
$bpass = trim($_POST['bpass']);
$bpass = strip_tags($bpass);
$bpass = htmlspecialchars($bpass);
// basic name validation
if (empty($bname)) {
$error = true;
$nameError = "Please enter your full name.";
} else if (strlen($bname) < 3) {
$error = true;
$nameError = "Name must have at least 3 characters.";
} else if (!preg_match("/^[a-zA-Z ]+$/",$bname)) {
$error = true;
$nameError = "Name must contain alphabets and space.";
}
//basic email validation
if ( !filter_var($bemail,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
} else {
**// check email exist or not**
$result = oci_parse($connection,"SELECT BUSER_EMAIL FROM
POHSENG.BRONTE_USER WHERE BUSER_EMAIL= $bemail");
$count = oci_num_rows($result);
if($count!=0){
$error = true;
$emailError = "Provided Email is already in use.";
}
if (empty($baddress)) {
$error = true;
$addError = "Please enter your address.";
}
// password validation
if (empty($bpass)){
$error = true;
$passError = "Please enter password.";
} else if(strlen($bpass) < 6) {
$error = true;
$passError = "Password must have at least 6 characters.";
}
// password encrypt using SHA256();
$bpass = hash('sha256', $bpass);
// if there's no error, continue to signup
if( !$error ) {
$res = oci_parse($connection,"insert into
POHSENG.BRONTE_USER(BUSER_NAME, BUSER_EMAIL, BUSER_ADDRESS,
BUSER_PASSWORD) VALUES('$bname','$bemail','$baddress','$bpass')");
oci_execute($res);
if ($res) {
$errTyp = "success";
$errMSG = "Successfully registered, you may login now";
unset($bname);
unset($bemail);
unset($bpass);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}
}
}
?>

How to auto login after registration

Like title says I want to log a user in once they successfully registered and don't want them to put username and password again to log in.
Here is registration code
<?php
$name = ((isset($_POST['name']))?sanitize($_POST['name']):'');
$email = ((isset($_POST['email']))?sanitize($_POST['email']):'');
$password = ((isset($_POST['password']))?sanitize($_POST['password']):'');
$confirm = ((isset($_POST['confirm']))?sanitize($_POST['confirm']):'');
$errors = array();
if($_POST){
$emailQuery =$db->query("SELECT * FROM users1 WHERE email = '$email'");
$emailCount = mysqli_num_rows($emailQuery);
if($emailCount != 0){
$errors[] = 'That email already exists in our database.';
}
$required = array('name', 'email', 'password', 'confirm');
foreach($required as $f){
if(empty($_POST[$f])){
$errors[] = 'You must fill out all fields';
break;
}
}
if(strlen($password) < 6){
$errors[] = 'Your password must be atleast 6 characterss';
}
if($password != $confirm){
$errors[] = 'Your password do not match';
}
if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
$errors[] = 'You must enter a valid email';
}
if(!empty($errors)){
echo display_errors($errors);
}else{
//add user to database
$hashed = password_hash($password,PASSWORD_DEFAULT);
$db->query("INSERT INTO users1 (full_name,email,password) values('$name', '$email','$hashed')");
}
?>
And here is how my login structure looks like
<?php
if ($_POST) {
//form validation
if (empty($_POST['email']) || empty($_POST['password'])) {
$errors[] = 'You must provide email and password.';
}
//Validate email
if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
$errors[] = 'You must enter a valid email';
}
//Password is more than 6 characters
if(strlen($password) < 6) {
$errors[] = 'Password must be at least 6 characters';
}
// check if email exits in the database
$query = $db->query("SELECT * FROM users WHERE email = '$email'");
$user = mysqli_fetch_assoc($query);
$usercount = mysqli_num_rows($query);
if($usercount < 1){
$errors[] = 'That email does not exist in our database';
}
if (!password_verify($password, $user['password'])) {
$errors[] = 'The password does not match our records. Please try again.';
}
//check for errors
if(!empty($errors)) {
echo display_errors($errors);
}else {
$user_id = $user['id'];
login($user_id);
}
}
?>
And here is login function
function login($user_id){
$_SESSION['SBUser'] = $user_id;
global $db;
$date = date("y-m-d h:i:s");
$db->query("UPDATE users SET last_login = '$date' WHERE id = '$user_id'");
$_SESSION['success_flash'] = 'You are now logged in!';
header('location: index.php');
}
The only thing that you do to indicate that a user is logged in is set $_SESSION['SBUser'] = $user_id;
So in your registration script just do that as well.
<?php
// new code
session_start();
$name = ((isset($_POST['name']))?sanitize($_POST['name']):'');
$email = ((isset($_POST['email']))?sanitize($_POST['email']):'');
$password = ((isset($_POST['password']))?sanitize($_POST['password']):'');
$confirm = ((isset($_POST['confirm']))?sanitize($_POST['confirm']):'');
$errors = array();
if($_POST){
$emailQuery =$db->query("SELECT * FROM users1 WHERE email = '$email'");
$emailCount = mysqli_num_rows($emailQuery);
if($emailCount != 0){
$errors[] = 'That email already exists in our database.';
}
$required = array('name', 'email', 'password', 'confirm');
foreach($required as $f){
if(empty($_POST[$f])){
$errors[] = 'You must fill out all fields';
break;
}
}
if(strlen($password) < 6){
$errors[] = 'Your password must be atleast 6 characterss';
}
if($password != $confirm){
$errors[] = 'Your password do not match';
}
if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
$errors[] = 'You must enter a valid email';
}
if(!empty($errors)){
echo display_errors($errors);
}else{
//add user to database
$hashed = password_hash($password,PASSWORD_DEFAULT);
$db->query("INSERT INTO users1
(full_name,email,password)
values('$name', '$email','$hashed')");
// new code
$_SESSION['SBUser'] = $db->insert_id;
}
?>

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 do I redirect a user to the same URL if the password/email validation fails?

I have a password reset script that has email and password validation. How can I make the script redirect the user to the same URL (ie. "https://www.domain.com/resetpassword.php?token=...") if they fail to meet the validation? Currently, if the validation test fails, the user is redirected to the URL: https://www.domain.com/resetpassword.php. The token is now gone and the password reset page becomes useless.
Here is my PHP code:
<?php
ob_start();
session_start();
include 'connect.php';
// Was the form submitted?
if (isset($_POST['btn-reset']))
{
// Gather the post data
$email = trim($_POST['email']);
$email = strip_tags($email);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$cpass = trim($_POST['cpass']);
$cpass = strip_tags($cpass);
//basic email validation
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
}
// password validation
if (empty($pass)){
$error = true;
$passError = "Please enter password.";
} else if(strlen($pass) < 6) {
$error = true;
$passError = "Password must have at least 6 characters.";
} else if($pass != $cpass) {
$error = true;
$passError = "Passwords do not match.";
}
// if there's no error, continue to process
if( !$error ) {
$token = $_POST ['token'];
// Retrieve token from database
$stmt = $conn->prepare('SELECT token FROM token WHERE userEmail=? and NOW() < expire_date');
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$resetKey = $row['token'];
}
// Does the new reset key match the old one?
if ($resetKey == $token && isset($token))
{
if ($pass == $cpass)
{
//hash and secure the password
$password = password_hash($pass, PASSWORD_DEFAULT);
// Update the user's password
$stmt = $conn->prepare('UPDATE user SET userPass = ? WHERE userEmail = ?');
$stmt->bind_param('ss', $password, $email);
$stmt->execute();
$conn = null;
$sucMSG = "Your password has been successfully reset.";
unset($email);
unset($pass);
unset($cpass);
unset($token);
unset($resetKey);
}
else
$matchError = "Your password's do not match.";
}
else
$keyError = "Your password reset key is invalid.";
}
}
?>
And then I have the errors appear in my form using PHP if the values of the errors are set.

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