I am working on a new website, and I rewrote some of my previously working code for the new one to recreate the login system. Unfortunately, the rewritten version does not work so let me explain what's going on.
I have "index.php", which holds the "titlemenu.php" that is used on every single page. I intend to run the login box in this title menu (top bar) so people can log in despite what page their own, and when they successfully log in, it refreshes the page they are currently on so they're logged in.
So far, bingo - It works. They're logged in and view members only pages. However, the title bar is a different story. It still shows "LOG IN" and "REGISTER", despite being logged in. Immediatelly, I though this was a problem with that specific php file, so I logged into that php only, bypassing index. When I try to sign in on that blank page only, I get:
Fatal Error: Call to a non-member function prepare() on line 18
I know this usually means your variable is not declared or not being ran, so I decided to troubleshoot it. I did a var_dump on every variable I used, which returned valid results. I checked index.php, which has no errors and runs fine, and shows users as logged in. "Welcome Back, RhapidFyre!" is what it says on the index, but the login box shows that I am not logged in yet.
loginheader.php
<?include "641a/database.php";?><div id="login"><?
$mydbid = $_SESSION['user'];
$myquery = "SELECT * FROM logins WHERE dbid = $mydbid";
$myrow = mysqli_fetch_assoc($myquery);
$myname = $myrow['nickname'];
if($_GET['do'] == "logout") {
unset($_SESSION['user']);
?><script type="text/javascript">
window.location.replace("index.php");
</script><?
}
if($_GET['do'] == 'login') {
$query = 'SELECT * FROM logins WHERE username = :username';
$query_params = array(':username' => $_POST['username']);
var_dump($query);
var_dump($query_params);
try
{
$stmt = $db->prepare($query); //LINE 18
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
?><script type="text/javascript">
window.location.replace("redirect.php?error=username");
</script><?
}(Further irrelevant code follows)
database.php
<? session_start();
$dbusername = "********";
$dbpassword = "********";
$dbhost = "localhost";
$dbname = "********";
$link = mysqli_connect($dbhost, $dbusername, $dbpassword, $dbname);
// PDO Initialization
try {
$db = new PDO("mysql:host={$dbhost};dbname={$dbname};charset=utf8", $dbusername, $dbpassword);
}
// If connection fails, die.
catch(PDOException $ex){
die("Failed to connect to the MySQL Server!" . $ex->getMessage());
}
Snippet of index.php
<html>
<head>
<title>My Website Template</title>
<link rel="stylesheet" type="text/css" href="base.css"/>
</head>
<body>
<div id="header">
<?include "pages/titles.php";?>
<?include "pages/loginheader.php";?>
</div>
The problem stemmed from using two connection types while trying to debug. Changed it all to MySQLi and it ran fine, but created new problems. As my programming instructor used to say, "Yay! New errors!"
Related
This is what I am trying to do: I want to download the code of my existing, and successfully running app (PHP and mySQL) and then upload it again to a different directory. I want to keep the database login the same. So basically I have a "live" code and a "test" code.
Now, when I go through this process I am getting a blank page when trying to log in as the newly uploaded "test" code. I am really puzzled why this is not working since I have not made any change to the code, I just duplicated it. I guess the blank page is telling me that the test code could not connect to the database. But why? Login details are the same!!
Any idea what I am missing here?
require_once("site_constant.php");
require_once("lib/mysql.php");
require_once("lib/function.php");
$DBObject = new db_sql();
$link = $DBObject->db_connect(DB_SERVER,DB_SERVER_USERNAME,DB_SERVER_PASSWORD, DB_DATABASE) or die('DB not connect');
The login details are in site_constant.php, which I have not changed:
define('DB_SERVER','xxxx');
define('DB_SERVER_USERNAME','xxxxx');
define('DB_SERVER_PASSWORD','xxxxx');
define('DB_DATABASE','xxxxxx');
define('SITE_URL', 'xxxxxxx');
The login function is in lib/mysql.php:
function db_connect($server = DB_SERVER, $username = DB_SERVER_USERNAME, $password = DB_SERVER_PASSWORD, $database = DB_DATABASE, $link = 'db_link')
{
global $$link;
$$link =mysql_connect($server, $username, $password);
if($$link)
{
$$link=mysql_select_db($database);
if(!$$link)
{
$msg="Can't connect from Database";
$this->db_error($msg,mysql_errno(),mysql_error());
}
}
else
{
$msg="Can't connect from MYSQL";
$this->db_error($msg,mysql_errno(),mysql_error());
}
return $$link;
}
I am new to PHP and can't find answers as to why the following code doesn't work. This should be easy, but I can't figure this out. This code produces no errors, and the SQL statement is correct in the phpAdmin SQL console. I've searched web & StackOverflow, but can't find a good answer. What's wrong?
ALL users (whether in the db or not) get ignored and stuck on login page.
<?php
session_start();
//create function to check login form for admin or other type of user.
//Redirect the admin user to the welcome page.
function login()
{
//strip login and password using in-build htmlspecialchars function
$value1 = htmlspecialchars($_POST['login']);
$value2 = htmlspecialchars($_POST['password']);
//set variables for the db connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$loggedin = '';
//Create new connection to db
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection and handle any error
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
header('Locatin: login.php');
}
else {
//check if super admin user exists in db
$sql = "SELECT count(*) FROM admins WHERE AdminLevel = 1";
$result = mysqli_query($conn,$sql);
//check to see if query returns any rows
if(mysql_num_rows(($result) > 0) {
include 'welcome.php';
}
//check if the password and username match
if(($username === $value1) && ($password === $value2)) {
$_SESSION['loggedin'] = TRUE;
echo "Hello ".$value1.", you are logged in!<br>";
}
//send user error message if login/username and password wrong
else {
echo "Incorrect username or password<br>";
include 'login.php';
}
//close the db connection
$conn->close();
}
?>
Login Form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Admin Login</title>
<script>
//function to check the form
function chkForm()
{
//determine the number of elements in the user login form
var intFormLen = document.forms[0].elements.length;
//loop through the form fields to see that a value has been input
for (var i = 0; i < intFormLen; i++) {
if (document.forms[0].elements[i].value == "") {
//send user an error message if login field empty
document.getElementById(document.forms[0].elements[i].name).innerHTML="Required Field";
document.forms[0].elements[i].focus();
return false;
}
}
//clear the form fields
function clearWarn(fieldName)
{
document.getElementById(fieldName).innerHTML = "";
return true;
}
return;
}
</script>
</head>
<body>
<h2>Admin Login</h2>
<div class="phpEcho">
<div class="formLayout">
<form action="#" method="post" onsubmit="return chkForm();">
<label for="login">Login:</label>
<input type="text"name="login" onchange="return clearWarn('fieldName')">
<div id="login" style="color:red"></div><br>
<label for="password">Password:</label>
<input type="password" name="password" onchange="return clearWarn('fieldName')">
<div id="password" style="color:red"></div><br><br>
<input type="submit" name="cmdSubmit" value="Log in">
</form>
</div>
</div>
</body>
</html>
You set your form action="#" and don't submit it in JavaScript.
As noted by Jason, chkForm() will never return true, which would also prevent the form from submitting.
This script has a lot of issues that should be addressed. I will go over a couple things that may help you:
1) I would suggest using some kind of config / bootstrap file to include in your documents that contains reusable elements and start session. Require/include only once.
/config.php
define("_DS_",DIRECTORY_SEPARATOR);
define("DBUSER",'root');
define("DBPASS",'');
define("DBHOST",'localhost');
define("DBDATABASE",'mydb');
// Start session
session_start();
2) You will want to separate out your functions, importantly your database connection, whether by class or by function. You want to keep tasks separate so it's easy to reuse.
Here is an example (I am going to use PDO because I am more familiar with it but principle is the same):
/functions/connection.php
function connection()
{
// This is just a really basic connection, one could expand on this
return new PDO('mysql:host='.DBHOST.';dbname='.DBDATABASE, DBUSER, DBPASS);
}
/functions/login.php
/*
** #param $username [string] by making this a param, you can manually log in users outside of POST
** #param $password [string] same as username
** #param $conn [resource] You will want to inject your connection into this
** in order to use it. Don't make the connection
** inside. May as well reuse resources already active
** #return [bool] If you return TRUE or FALSE, that will tell your script
** whether the login succeeded or failed for notification
*/
function login($username,$password,$conn)
{
// Don't worry about stripping down the username/pass, just bind
// the username and match the password
// You need to select from your user table (or whatever table
// you are storing your usernames for your site)
$query = $conn->prepare("select * from `users` where `username` = :0");
$query->execute(array(':0'=>$username));
$result = $query->fetch(PDO::FETCH_ASSOC);
if(empty($result))
return false;
// You will want to use password_hash to save passwords
if(!password_verify($password,$result['password']))
return false;
// I use htmlspecialchars here so I don't forget when echoing to page
// but you can do it at the time you echo to browser
$_SESSION['first_name'] = htmlspecialchars($result['first_name']);
//etc....
return true;
}
To use:
/index.php
// Include our soon-to-be-used files
require_once(__DIR__._DS_.'config.php');
require_once(__DIR__._DS_.'functions'. _DS_.'connection.php');
require_once(__DIR__._DS_.'functions'. _DS_.'login.php');
// Set connection
$con = connection();
// See if a post has been made
if(isset($_POST['login'])) {
$loggedin = login($_POST['login'],$_POST['password'],$con);
}
// If the login attempt made
if(isset($loggedin)) {
// If successful
if($loggedin) {
header('Location: welcome.php');
exit;
}
else
// If failed, you can note in a variable an echo in the html section
$error = 'Login failed';
}
For the client-side validation, I would suggest jQuery Validate, it's easy and works very well.
Super confused here. I've build a website that allows me to connect to mysql using php. I require common.php as you can see below, and have no issues connection, executing, etc.. to the database. What does not work is when I use this exact same code on a new page that I'm developing. I can login with a test user to the site, but the page will not run any SQL queries to pull information from my database. The error I get is:
"Access Denied for user 'ec2-user#localhost' (using password: NO)"
I do not understand why its trying to connect as ec2-user when thats obviously isn't what I'm asking the code to connect as.
Any help would be appreciated. I've been attempting to resolve this issue for a few days now and even with searching Father Google, I can't find a suitable answer.
Thanks!
Common.php Code
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to index.php");
}
Code for common.php is below
<?php
// These variables define the connection information for your MySQL database
$username = "username";
$password = "password";
$host = "myhostnotyours";
$dbname = "thedatabase";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
session_start();
Probably the bit "(using password: NO)" is the bit you should be looking into. Do the password thing!
Then again why not narrow down the problem a bit - instead of posting 100+ lines of code
set your password variable into null.
$password = '';
I'm working on a friend's project and I'm in charge of designing a simple website to interface with his databases. I have written the following code for one of his pages:
<!DOCTYPE html>
<html>
<head>
<title>Narcissus-OTS</title>
<meta charset="utf-8" />
<!--<meta http-equiv="refresh" content="3;url=./account.php" />-->
</head>
<body>
<?php include("./common/database.php"); ?>
<?php
//Grabs user-submitted credentials from previous page
$accountid = mysql_escape_string($_POST["acc"]);
$password = mysql_escape_string($_POST["pass"]);
$confirmation = mysql_escape_string($_POST["passtwo"]);
//Insures there is no duplicate database entry for accountid
$querycheck = $db->query("
SELECT *
FROM accounts a
WHERE a.name = $accountid
");
$checkifone = $querycheck->rowCount();
//If no duplicate entry...
if ($checkifone == 1) {
echo "There is already an account with that name; please choose a different account number.";
} else {
//Confirms if passwords match
if ($password == $confirmation) {
$passhash = sha1($password);
$database = $db->query("
INSERT INTO accounts
VALUES (NULL , '$accountid', '$passhash', '65535', '0', '', '1', '0', '0', '1');
");
echo "Your account has been successfully created.";
//If passwords do not match
} else {
echo "Your passwords did not match, please try again.";
}
}
?>
</body>
</html>
When I load the page and view page source, it doesn't seem to show terminating </body> or terminating </html> tags. I've traced my code and can't see any missing semi-colons or parentheses. For the life of me I can't figure this one out. It displays the terminating tags properly only when the passwords do not match (the bottom-most nested else statement).
edit; and before anyone says it, I know mysql_escape_string is deprecated.
edit2; database.php looks like...
<?php
$SERVER = "localhost";
$USERNAME = "redacted";
$PASSWORD = "redacted";
$DATABASE = "redacted";
$db = new PDO("mysql:dbname={$DATABASE}; host={$SERVER}", $USERNAME, $PASSWORD);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
?>
Your best bet to solve this problem and any other occurrences like this in the future is to tail your server log and determine what exactly the issue is.
For apache2:
tail -f /var/log/apache2/error.log
For nginx:
tail -f /var/log/nginx/error.log
Using PHP and MySQL to make a login/registration system. Registration is in and I'd say it works alright. However, I'm having some problems with the login page.
No matter what, it just kind of refreshes the page and I'm not sure what's wrong. Here's the loginaccount.php script I have running on the form:
**
EDIT:
**
Thanks for the help so far guys! But I'm still running into a pretty annyoing problem. Now, no matter what, it still doesn't log in, even though now I'm actually getting the error message I set up. Updated code below:
<?php
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
session_start();
$username = $_POST[‘username’];
$password = md5($_POST[‘password’]);
$query = "select * from registerusers where username='$username' and password='$password'";
$result = mysql_query($query);
if (mysql_num_rows($result) == 0) {
$error = "Incorrect login, please try again.";
include "login.php";
echo "<span class=error_message>".$error."</span>";
} else {
$_SESSION['username'] = "$username";
include "login.php";
echo "<span class=success_message>Welcome! You are now logged in.</span>";
}
?>
I can't post comments on questions yet, but I've got a possible reason for your problem.
Since you're only including (and not redirecting) the users to a page, the login page will just stay where it is and just keep including the files - doing the same things over and over. Try header('Location: memberspage.php') instead.