MySQL connection works on Localhost but not on webserver - php

Good day Everyone..
I have an issue that is puzzling me and I can not seem to find a way to solve it. Even the tech support in my hosting service can not solve it.
I have created a small script to do a simple task. I require the employees to log in to perform any said task.
I have tested the application on a development server and the login script works perfectly, but when I place it on the webserver the connection is never established.
I use the same username and passowrd in the dbcon.php file to log in using phpMyAdmin and it works, and I run the queries and they also work.
Here are the files:
1: dbcon.php
<?php
$connect = "mysql:host=localhost;dbname=mdchaara_draiwil_dms;charset=utf8";
$db_user = "dbusername";
$db_pass = "dbpassword";
$db = new PDO($connect,$db_user,$db_pass);
?>
2: login.php:
<?php
session_start();
require "../../_dbcon/_dbcon.php";
//Timezone settings:
$timezone = "Asia/Kuwait";
if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);
// check the username has only alpha numeric characters
if (ctype_alnum($_POST['username']) != true)
{
//if there is no match
$message = "Username must be alpha numeric";
}
//check the password has only alpha numeric characters ***/
if (ctype_alnum($_POST['password']) != true)
{
//if there is no match ***/
$message = "Password must be alpha numeric";
}
else
{
// if we are here the data is valid and we can insert it into database
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);
//SQL Injection Precaution:/
$username = stripslashes($username);
$password = stripslashes($password);
try
{
//Select Statement:
$stmt = $db->query("SELECT *
FROM dms_gt_users
WHERE username = '$username' AND password = '$password'");
$result = $stmt->rowCount();
}
catch(PDOException $ex) {
echo "An Error occured!"; //user friendly message
some_logging_function($ex->getMessage());
}
// If result matched $username and $password, there will be one row
if($result==1){
// check if the account is active:
$stmt = $db->query("SELECT id_status
FROM dms_gt_users
WHERE username = '$username' AND password = '$password'");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id_status= $row['id_status'];
}
$stmt = $db->query("SELECT employee_id
FROM dms_gt_users
WHERE username = '$username' AND password = '$password'");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$employee_id= $row['employee_id'];
}
//Check if account is active:
if($id_status == "A"){
// Create Session ID:
$session_id = "";
$_SESSION['sid'] = "";
$session_id = mt_rand(100000, 999999);
$sid_update = $db->query("UPDATE dms_gt_users
SET `session_id`='$session_id'
WHERE username='$username' and password ='$password'");
$_SESSION['sid'] = $session_id;
//Get last login details:
$current_login = date("Y-m-d H:i:s");
$stmt = $db->query('SELECT `last_log_in`
FROM dms_gt_users
WHERE `employee_id` = '.$employee_id);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$last_log_in = $row['last_log_in'];
}
$_SESSION['last_log_in'] = $last_log_in;
//get IP address:
$ip = getenv('REMOTE_ADDR');
//Add login details to Activity Log:
$stmt = $db->query("INSERT INTO dms_activity_log
(`employee_id`, `activity_date_time`, `activity`, `ip_address`)
VALUES ('$employee_id', '$current_login', 'Logged in', '$ip')");
//Add login details to users table:
$stmt = $db->query("UPDATE dms_gt_users
SET `last_log_in`='$current_login'
WHERE username='$username' and password ='$password'");
//update session login
$_SESSION['login']= 1;
//save employee id to session
$_SESSION['employee_id'] = $employee_id;
// redirect to portal home:
header ("Location:../../../home.php");
}
//Account is not Active:
else{
header ("Location:../../../index.php");
}
}
//Username or password are incorrect
else {
header ("Location:../../../index.php");
}
}
?>
What am I doing wrong? and if my code is ok, what should I tell the hosting Tech Support to look for?
Thanks!!
EDIT
#noc2spam: I have updated the connection string as you have advised, I get no errors logged. I var_dump the $db, and I get object(PDO)#1 (0)

It is pretty hard to tell why this is happening without looking into the server itself. I suggest that you enable the Exception mode so that you can see what the problem is. For example:
try {
$connect = "mysql:host=localhost;dbname=mdchaara_draiwil_dms;charset=utf8";
$db_user = "dbusername";
$db_pass = "dbpassword";
$db = new PDO($connect,$db_user,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo 'PDO Exception: '.$e->getMessage();
die();
}
It would be much easier to troubleshoot now. Check if you are getting any error and update the original question with the message if possible. I will edit this answer after that.

IF Roger Ng's answer doesn't solve it, then you may have a firewall blocking your connection. Check your mysql server port... typically 3306.

Check your database's url. Generally, in shared/dedicated hosting environment, DB server and App Server are on different machines. Also, many service providers do not provide mysql cluster services on port 3306. So, please get the correct URL and port of the database from your hosts CPanel or tech support team.
Also, add the App server's IP address to the permitted IP addresses list in Remote MySQL Cpanel interface.

Related

Error 500 with Login Process (SQL, PHP, Heroku)

I'm trying to turn my final project into my teacher via pushing it from Cloud9 to Heroku. Unfortunately, the code managing the project's login process has a mistake that's preventing it from displaying most of my site to my teacher.
Here is the code
//login
<?php
session_start();
include 'dbConnection.php';
$conn = getDatabaseConnection();
$username = $_POST['username'];
$password = sha1($_POST['password']);
//echo $password;
//Watch out! Sql injection risk
/*$sql = "SELECT *
FROM q_admin
WHERE username = '$username'
AND password = '$password'";*/
$sql = "SELECT *
FROM f_admin
WHERE username = :username
AND password = :password";
$namedParameters = array();
$namedParameters[':username'] = $username;
$namedParameters[':password'] = $password;
$stmt = $conn->prepare($sql);
$stmt->execute($namedParameters);
$record = $stmt->fetch(PDO::FETCH_ASSOC);
if (empty($record)) {
echo "Wrong username or password";
header("Location: login.php?login=false");
exit;
} else {
$_SESSION['username'] = $record['username'];
$_SESSION['userId'] = $record['userId'];
header('Location: admin.php'); //redirects users to admin page
}
?>
The code above should be looking into my SQL database for usernames and passwords before deciding whether or not to let the user into the site's admin page.
Instead, the user is taken to a mostly blank page displaying an error 500, regardless of their credentials.
According to the Heroku logs, the error is somewhere around line 24, but I still can't identify it.
Thank you for giving this your time.

Issue with Sign in form in PHP

I am trying to use the below code to create a login form. The problem being after registration when I am trying to login, getting an error message "Username or Password don't match" even though email & password are correct. I tried "$num <=1" and allows me to log in but obviously it is not authenticating the login details in that case. Any help will be appreciated.Most importantly this code is working fine on a local server like XAMPP but problem starts when using a host server like hostgator (no issue to connect with the server).
<?php
session_start(); // Starting Session
#Database connection
include('../config/connection.php');
$error=''; // Variable To Store Error Message
if (isset($_POST['submit']))
{
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = '<p class="alert alert-danger">One or either field is missing</p>';
}
else
{
// Define $username and $password
$email=$_POST['email'];
$password = $_POST['password'];
// To protect MySQL injection for Security purpose
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
// SQL query to fetch information of registerd users and finds user match.
$q = "SELECT * FROM users WHERE email = '$email' AND password = md5(SHA1('$password'))";
$r = mysqli_query($dbc, $q)or die(mysqli_error());
$num = mysqli_num_rows($r);
if($num ==1){
$_SESSION['username'] = $email;
header('Location:Index.php');
} else {
$error = '<p class="alert alert-danger">Username or Password don\'t match</p>';
}
mysqli_close($dbc); // Closing Connection
}
}
?>
in your query the $password should not be between the quotes, cause then it will seek for the string instead of the value of the variable.
$q = "SELECT * FROM users WHERE email = '$email' AND password = 'md5(SHA1($password))'";
make sure your password is hashed in your database

PHP Authentication works only local

I have a PHP login page that works perfectly locally, but when in server always come out with "Invalid Username or Password". I tried it in two different servers and the result was the same.
login.php
session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password']))
{
$error = "Username or Password is invalid";
}
else
{
// Define $username1 and $password1
$username1 = $_POST['username'];
$password1 = $_POST['password'];
include_once ('lib/db.php');
$connection = new mysqli($servername, $username, $password, $dbname);
$username1 = stripslashes($username1);
$password1 = stripslashes($password1);
$username1 = mysql_real_escape_string($username1);
$password1 = mysql_real_escape_string($password1);
// SQL query to fetch information of registerd users and finds user match.
$query = "select * from login where PASSWORD='$password1' AND USERNAME='$username1'";
$result = $connection->query($query);
$rows = mysqli_num_rows($result);
if ($rows == 1)
{
$_SESSION['user']=$username1; // Initializing Session
$_SESSION['pppv'] = 10;
header("Location: logged-in.php"); // Redirecting To Other Page
}
else
{
$error = "Username or Password is invalid";
}
}
}
EDIT
Try printing the query after submission gives me this:
Local:
select * from login where PASSWORD='test' AND USERNAME='test'
Server:
select * from login where PASSWORD='' AND USERNAME=''
Use isset($_POST['username']) ||isset($_POST['password'])instead of empty($_POST['username']) || empty($_POST['password']).
Read this to know the difference between isset and empty.
There's no context, but check these things:
Does your database contain the same credentials as local?
Does your requested page return http status such as 200? If it's 404, there's something wrong with your path's. If it's 500, there's an internal error (right permissions set?)
Did you check your log files?
Did you clear your browser cookies and history?
Did you print the full query (including filled parameters) to the window and did you execute this query in your database management tool? And did you get result?

login page with multiple databases

I have a website that I need users to be able to login to. It is currently on a different server from the company's actual website. I would like to have a single login form that checks for a username and password in multiple databases on the same server.
Heres the setup.
1 Database has 2 different tables that I need to check for username and password.
the other database has 1 table that I need to check.
I will have a checkbox for 1 of the tables in the first database. So the form will have 3 field. (Username, Password, and "I am a reporter" checkbox)
I believe that it has something to do with the UNION sql command.
I don't know a LOT about sql but I am trying to learn as I go...
Here is the code so far.. also, I hope someone will tell me whether the information will be passed securely or not.
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['uname']) || empty($_POST['pswd'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$uname=$_POST['uname'];
$pswd=$_POST['pswd'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$con = mysql_connect("10.0.0.3", "webaccess", "ccrweb");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("company", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from dbo.contacts where WebPwd='$password' AND WebAcctName='$username'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
header("location: "); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>
It is not all complete yet and I am still researching but I am also trying to do this as quick as possible.
any help will be greatly appreciated!
It appears you make a connection declaring one name and then a different connection object name later.
$con = mysql_connect("10.0.0.3", "webaccess", "ccrweb");
$db = mysql_select_db("company", $connection);
I believe the later should use the same name $con and also at the end mysql_close($con);
First, you should use the mysqli_ or PDO API instead of mysql statements
If you need to use mysql, here is what to do:
$QueryReporter = mysql_query("SELECT * FROM $ReporterTable WHERE Username = '$Username' AND Password = '$Password'");
$QueryOthers = mysql_query("SELECT * FROM $UserTable WHERE Username ='$Username' AND Password = '$Password'");
if(mysql_num_rows($QueryReporter)==1){
//Its a reporter
}
else if(mysql_num_rows($QueryOthers)==1){
//Its not a reporter, but a user
}
else{
//Its no user or reporter, show error :)
}
EDIT:
If you are thinking about two different DB servers, you can use a function, then close the connection after the full query and return the result:
function CheckIfReporter($Username, $Password){
//DATABASE CONNECTION TO REPORTER DB
$Query = mysql_query("SELECT * FROM MyTable WHERE Username = '$Username' AND Password = '$Password'");
if(mysql_num_rows($Query)==1){
return TRUE;
}
//Else, no result:
else{
return FALSE;
}
//Close mysqlconnection:
mysql_close();
}
Now, make a similar function for user check,
if(CheckIfReporter($UsernameInput, $PasswordInput)==TRUE){
//Its a reporter
}
else if(CheckIfUser($UsernameInput, $PasswordInput)==TRUE){
//Its a user
}
else{
//Its none
}

Registration script.php does not work

I have a registration script that doesn't work. It used to work but then suddenly it stopped working. I dont know what I've done or what happend. I have tried for like an hour now to find out where the problem is, but I can't seem to find it.
What happens? When I click register I don't get any errors but it doesn't upload to the database:
When I type: $res = mysql_query($query) or die ("ERROR"); it displays ERROR so I think it's related to that code:
//=============Configuring Server and Database=======
$host = 'localhost';
$user = 'root';
$password = '';
//=============Data Base Information=================
$database = 'login';
$conn = mysql_connect($host,$user,$password) or die('Server Information is not Correct'); //Establish Connection with Server
mysql_select_db($database,$conn) or die('Database Information is not correct');
//===============End Server Configuration============
//=============Starting Registration Script==========
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['pass1']);
$email = mysql_real_escape_string($_POST['email']);
$country = mysql_real_escape_string($_POST['country']);
$rights = '0';
$IP = $_SERVER['REMOTE_ADDR'];
//=============To Encrypt Password===================
//============New Variable of Password is Now with an Encrypted Value========
$query = mysql_query("SELECT username FROM users WHERE username = '".$username."'");
if (mysql_num_rows($query) > 0)
{
echo 'Username or email already in use.';
}
else{
if(isset($_POST['btnRegister'])) //===When I will Set the Button to 1 or Press Button to register
{
$query = "insert into users(username,password,email,country,rights,IP,registrated)values('$username','$password','$email','$country',$rights,$IP,NOW())" ;
$res = mysql_query($query);
header("location:load.php");
}
}
I think you are getting the error because you are missing some quotes in your query for two columns wich really looks like not integers
'$email','$country',$rights,$IP,NOW())" //$rights and $ip doesn't have quotes
so your query would look like
"insert into users(username,password,email,country,rights,IP,registrated)values('$username','$password','$email','$country','$rights','$IP',NOW())"
Use mysql_error() in order to see what the error message is. If you haven't changed anything in the script then it's either your database structure has changed or your rights have.
Update:
You don't have quotes around your IP value, which is surprising because you said that query worked until now. Anyway you should also consider saving IPs the RIGHT way. Good luck!

Categories