I have just uploaded my local project to server but PDO queries are not working in LIVE server. It's working fine on local. I thought PDO might not be installed on server so i ran the below script
PHP version in server is PHP Version 5.3.3, Linux server
<?php
if (!defined('PDO::ATTR_DRIVER_NAME')) {
echo 'PDO unavailable';
}else{
echo 'pdo is installed';
}
?>
Connection.php:
<?php
try{
$pdo = new PDO('mysql: host=localhost; dbname12', 'myusername', 'password');
}catch(PDOException $e){
exit('Database Error');
}
?>
Login:
<?php
session_start();
include_once('../includes/connection.php');
if(isset($_POST['user_name'], $_POST['user_password'])){
$username = $_POST['user_name'];
$password = md5($_POST['user_password']);
if(empty($username) or empty($password)){
$error = 'All fields are required!';
}else {
$query = $pdo->prepare("SELECT * FROM users WHERE user_name = ? AND user_password = ?");
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
//var_dump($query);exit;
$num = $query->rowCount();
if ($num == 1) {
// User correct details let's log him in
$_SESSION['logged_in'] = true;
header('Location: dashboard.php');
exit();
} else {
$error = 'Incorrect Details';
}
}
}
?>
By entering correct credentials the login is showing incorrect details always + For debugging i bypassed the login and entered dashboard where we are fetching articles from DB but nothing was there. And in database we have many entries.
Well I don't know if this is a bug or not, but adding dbname=dbname12 to below line everything starts working!
$pdo = new PDO('mysql: host=localhost; dbname=dbname12', 'myusername', 'password');
Locally it was working fine with the below code but on server when I added dbname then queries started working.
$pdo = new PDO('mysql: host=localhost; dbname12', 'myusername', 'password');
Related
Using xampp for local development, I was able to build a very simple authentication for accessing a webpage. Everything worked fine on my local machine but I ran into some issues while testing it on my live server.
Instead of creating the database in phpMyAdmin, I had to use the MySQL Databases tool in my cPanel. No big deal, I guess, just create the myLogin database, then go into phpMyAdmin to add the myUsers table with ID, username, and password, and finally insert the user 'admin' with a hashed password.
Issue 1: I guess it only makes sense, but the following resulted in an error:
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'myLogin';
Failed to connect to MySQL: Access denied for user 'root'#'localhost' (using password: NO)
So, I opened mySQL Database again and added a user with a password and attached it to the myLogin database. I edited the code in the auth.php file to reflect the changes and... no error! However, no nothing.
Issue 2: After I enter the password and hit enter the browser just goes to the auth.php file and does nothing. No echoes, no redirect upon success, nothing. Below is the entire auth.php file:
<?php
session_start();
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'myUser';
$DATABASE_PASS = 'myPass';
$DATABASE_NAME = 'myLogin';
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
if ( !isset($_POST['uName'], $_POST['pWord']) ) {
die ('Please fill both the username and password field!');
}
if ($stmt = $con->prepare('SELECT id, password FROM myUsers WHERE username = ?')) {
$stmt->bind_param('s', $_POST['uName']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password);
$stmt->fetch();
if (password_verify($_POST['pWord'], $password)) {
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['uName'];
$_SESSION['id'] = $id;
header('Location: ../wica.php');
} else {
echo 'Incorrect password!';
}
} else {
echo 'Incorrect username!';
}
$stmt->close();
}
?>
As I mentioned, I am a complete PHP newbie, this has all been cobbled together thanks to various tutorials.
I don't know why it won't even echo "Incorrect password!" when I type the wrong password. It just sits on auth.php and does nothing and I'm clueless. This is my first time using mySQL on the remote server. Could there be critical settings that aren't the same as my xampp setup? Did I miss an important step somewhere?
Also, it seems a little insecure to have the DATABASE_USER and DATABASE_PASS just sitting in the auth.php file for anyone to see. Was I not supposed to do this? What are the secure alternatives, or are there any?
In case you got caught in the wheels of the comment-train, here's the answer:
My local dev. server (xampp) is running PHP 7+ while my remote server's PHP version was 5.4x, preventing password_verify from working. I was able to update the remote server's PHP version and everything worked. (Thank you fyrye!)
As was pointed out, the php code itself was a mess, so I found a better tutorial, I hope, and re-wrote the auth file:
<?php
if ( isset($_POST['pWord'])) {
require '../../../dbh.inc.php';
$username = $_POST['uName'];
$userpass = $_POST['pWord'];
if(empty($username) || empty($userpass)) {
header("Location: ../index.html?error=emptyFields");
exit();
}
else {
$sql = "SELECT * FROM users WHERE username=?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../index.html?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if($row = mysqli_fetch_assoc($result)) {
$pwdCheck = password_verify($userpass, $row['password']);
if($pwdCheck == false) {
header("Location: ../index.html?error=wrongPass");
exit();
}
else if($pwdCheck == true) {
session_start();
$_SESSION['loggedin'] = TRUE;
header("Location: ../wica.php");
exit();
}
else {
header("Location: ../index.html?error=wrongPass");
exit();
}
}
else {
header("Location: ../index.html?error=noUser");
exit();
}
}
}
}
else {
header("Location: ../index.html?error=justWrong");
exit();
}
?>
You might notice that I also moved the database credentials to an include that now resides above the public root.
Is it the best solution? Probably not, but learning how to implement something like DotEnv is beyond me atm. I don't actually know PHP, I just use it sometimes like a pleb. Plus, I just spent a month translating 3000+ lines of Actionscript into javascript and creating html/css equivalents for all the .swf library elements. My brain is currently oatmeal. Hope my follies can at least help someone else.
I am new to developing a website. I have question about user connection to server and database. For example, a server 'server1' have 2 database and website, 'webdata1' and 'webdata2'. (I am not using any framework for both website development because i still not familiar in framework.)
User A log in and create session to 'webdata1' and user B log in and create session to 'webdata2'. The problem is, when user A connect and create session to 'webdata1', for 'webdata2' also was connected with user A session instead of user B.
How can i split the user session and connection? It is by using framework (MVC Framework) solve this? Or is there another method for this?
session_start();
include "connectdatabase.php";
try
{
$connect = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["login"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$message = '<label>All fields are required</label>';
}
else
{
$query = "SELECT * FROM User WHERE username = :username AND password = :password";
$statement = $connect->prepare($query);
$statement->execute(
array(
'username' => $_POST["username"],
'password' => $_POST["password"]
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
header("location:index.php");
}
else
{
$message = '<label>Wrong Data</label>';
}
}
}
}
catch(PDOException $error)
{
$message = $error->getMessage();
}
I use this code in login.php for both website. "connectdatabase.php" contain code to connect to server and database.
On my website i log users in perfectly but i noticed that when a user is logged out, they can simply hit backspace and be re-logged in or even just put the file name in the URL. I found a lot questions on this matter but some are very vague with little steps and others are very outdated. I basically want to give the user a token for the session, that i have generated and set to the database already, and that token will be seen in the URL as GET request for security but i do not know how to go about this. Here is my code for the login page and upload page
PHP Login Page
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] =="POST"){
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if(!empty($username) && !empty($password)){
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
$stmt = $handler->prepare("SELECT * FROM generalusersdata WHERE username = :username");
$stmt->execute(array(':username'=>$username));
if($result = $stmt->fetch()){
if(password_verify($password, $result['password'])){
$token = md5(uniqid(mt_rand(), true));
$stmtToken = $handler->prepare("SELECT * FROM token_table WHERE token = :token");
$stmtToken->execute(array(':token'=>$token));
if($rowToken = $stmtToken->fetch()){
die("Error, Please try again");
}
$userid = $result['user_id'];
$email = $result['email'];
$time = time();
$stmtSendToken = $handler->prepare("INSERT INTO token_table set timestamp=?, user_id=?, token=?");
$stmtSendToken->execute(array($time, $userid, $token));
$stmtUpdate = $handler->prepare("UPDATE generalusersdata SET isDev = true WHERE user_id =?");
$stmtUpdate->execute(array($userid));
$_SESSION['id'] = $userid;
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['timestamp'] = $time;
header("Location: developerUpload.php");
}
}else{
die("Username OR Password is incorrect! Please try again");
}
}else{
die("Values Missing!");
}
}
?>
PHP upload page after logging in
<?php
session_start();
if(array_key_exists("id", $_COOKIE)){
//set the session id equal to the cookie
$_SESSION['id']= $_COOKIE['id'];
}
if(array_key_exists("id", $_SESSION)){
$username = $_SESSION['username'];
echo "Welcome To the Developer Side ".$username."!";
echo "<br><br><button><a href='developerLogin.php?logout=1'>Log Out</a></button></br></br>";
if(isset($_FILES['file']) && $_FILES['file']['size'] > 0){
$target = "devFiles/";
$target_file = addslashes(trim($target . basename($_FILES["file"]["name"])));
// Check file size not > 500Mb
if($_FILES["file"]["size"] > 500000000){
echo "Files Cannot be bigger than 500MB";
exit;
}
if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)){
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
$dev_file = addslashes(trim($_FILES['file']['tmp_name']));
$file_name = addslashes(trim($_FILES['file']['name']));
$username = $_SESSION['username'];
$email = $_SESSION['email'];
$userid = $_SESSION['id'];
$time = $_SESSION['timestamp'];
$stmt = $handler->prepare("INSERT INTO developerfiles set user_id=?, username=?, email=?, dev_file=?, file_name=?, timestamp=?");
if(!$stmt->execute(array($userid, $username, $email, $dev_file, $file_name, $time))){
die("Error");
}else{
echo "Thank you for Submiting!";
}
}
}
}else {
header("Location: developerLogin.php");
}
?>
In your upload file you did not check the session again.
So every one could login into your upload file, only create an $_SESSSION['id']='1' and a $_COOKIE['id']='1' and your logged in (also if the id did not exists).
And one tipp: Set an Hash (md5, uniqueid,...) or somthing like that in your _SESSION (from your database, insted of an id) or every one could login as every user, only changing the _SESSION id.
The other thing is, you did not set an _COOKIE in your hole script, but in your upload file you check if the _COOKIE is set, or remove the _COOKIE check in your upload file
So add an setcookie() to your login page too, to work with your current file.
And add a second SQL request to your upload file, like:
$id=$_SESSION['id'];
if(!is_numeric($id) or $id<1) $id = 0; // a little bit of "security".
"SELECT * WHERE `id`='$id'";
if($sql_request => true){
// write the script
} else {
// you are not logged in
}
To destroy the _SESSION (logout) set the _SESSION like this $_SESSION['id']='empty'; unset($_SESSION['id']); so no one could use the back button to login back.
So there is no need to do it unsave with an token in your URL.
I have created a website lately with a group of students, but were having some troubles.
We created the website in php 5.4 on a localhost and it worked perfectly.
But now we wanted to get the site online and the webhosting is using a different version of php(5.6).
So now the session does not start.
It redirects us to the homepage, but we are not logged in.
We were thinking that it was because of the version of php, since it did work at first.
<?php
include_once 'connect.php';
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['gebruiker'];
// SQL Query To Fetch Complete Information Of User
$ses_sql="select email_adres from gebruiker where email_adres='".$user_check".'";
$row = mysqli_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
header('Location: login.php'); // Redirecting To Home Page
}
else{
header('Location: acountgegevens.php');
}
?>
<?php
include_once 'connect.php';
function logincheck(){
if(isset($_POST['submit'])){
$error = 0;
// declare variables
$email = null;
$password = null;
// check if email address has been set
if (isset($_POST['email_adres']) &&
!empty($_POST['email_adres'])) {
$email = addslashes($_POST['email_adres']);
}
// check if password has been set
if (isset($_POST['password']) && !empty($_POST['password'])) {
$password = md5($_POST['password']);
}
if ($email == null || $password == null) {
$error = 1;
}
// query database for user credentials
$db = new PDO('**');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $db->prepare("SELECT *
FROM gebruiker
WHERE email_adres = :email
AND wachtwoord = :password
LIMIT 1");
$statement->execute(array(':email' => $email, ':password' => $password));
$result = $statement->fetch(PDO::FETCH_OBJ);
if (!$result) {
$error = 1;
} else {
session_start();
$_SESSION['gebruiker'] = $email;
var_dump($_SESSION);
?>
<script>location.href='index.php'</script>
<?php
}
return $error;
}
}
?>
These two files are included, but we cant figure it out.
Could someone help?
I would hazzard a guess that your connect.php has not been changed to match the hosting companies host/user/password and therefore is outputting an error message.
This of course means that session_start() , which was placed after the connect.php and therefore after your script has attempted to send something to the browser, will not work.
You are only seeing the result of the failed session_start() but I would check the connect.php is configured correctly for its new hosting location
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.