Page source reveals part of my page isn't displaying - php

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

Related

Call to member function on a non-object (include database.php)

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!"

Please provide assistance with PHP login script

I'm new at creating login scripts with php and MySQL and was hoping for some help. I've already gotten the basics down for actually checking that the entered information is correct and I've gotten the sessions to work correctly. However, I'm having trouble getting the user's info to pull from his/her row and displaying on the membership page. Do I need to do another query and add a while loop within this page to collect the information? Here are the scripts:
login.php
$p_num = "";
$pwd = "";
$errors = "";
$num_rows = 0;
$user_id = "";
$user_name = "";
$password = "";
$image = "";
$user_email = "";
$program = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
include("database.php");
$p_num = $_POST["username"];
$pwd = $_POST["password"];
$query = "SELECT * FROM $user_table WHERE user_id = '$p_num' AND password = '$pwd'";
$result = mysqli_query($connect, $query);
$num_rows = mysqli_num_rows($result);
if($result){
echo "There is/are " .$num_rows ." set(s) in the database with this info.<br>";
if($num_rows > 0){
session_start();
$_SESSION["login"] = 1;
header("Location: ../pages/instructor.php");
}
else{
echo "Unable to login";
}
}
}
instructor.php
<!DOCTYPE html>
<?php
include("../php/login.php");
include("../php/database.php");
?>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<link href="../css/style.css" rel="stylesheet/less" type="text/css">
<script src="../js/jquery.2.0.3.js"></script>
<script src="../js/script.js"></script>
<script src="../js/less-1.7.4.min.js"></script>
</head>
<body>
<div id="page">
<header>
<div id="logo" class="logo_bg"></div>
<div id="fsi_logo" class="logo_bg"></div>
</header>
<div id="main">
<?php
session_start();
if(isset($_SESSION["login"])){
echo "Hello";
}
?>
<div id="bleg">
<h1>BUILD SCENARIO</h1>
<h1>SEARCH SCENARIOS</h1>
<h1>VIEW SCENARIOS</h1>
</div>
</div>
<footer>Copyright© 2014 FlightSafety International</footer>
</div>
</body>
</html>
database.php
$db = "spartan";
$host = "localhost";
$user = "root";
$password = "";
$connect = mysqli_connect($host, $user, $password) or die(mysqli_error($connect));
$user_table = "users";
$user_info = "user_info";
$create_db_spartan = "CREATE DATABASE IF NOT EXISTS $db";
$create_table_users = "CREATE TABLE IF NOT EXISTS $user_table(user_id VARCHAR(10) NOT NULL, user_name VARCHAR(100), password VARCHAR(16), PRIMARY KEY(user_id))";
$create_table_users_info = "CREATE TABLE IF NOT EXISTS $user_info(user_id VARCHAR(10) NOT NULL, user_name VARCHAR(100), email VARCHAR(50), program VARCHAR(4), PRIMARY KEY(user_name))";
mysqli_query($connect, $create_db_spartan) or die(mysqli_error($connect));
mysqli_select_db($connect, $db) or die(mysqli_error($connect));
mysqli_query($connect, $create_table_users) or die(mysqli_error($connect));
mysqli_query($connect, $create_table_users_info) or die(mysqli_error($connect));
Just as an FYI, I am not concerned with SQL Injection at this point in time, this isn't something that's been released and it's on an internal network. Thanks in advance.
In both of your scripts, session_start() is issued after data has been sent to the browser. This means that the opportunity for setting headers has passed, and so session cookies cannot be set. Thus, sessions will not work.
In both cases, put this command at the top of your script, or at least before the opening DOCTYPE. Your sessions should then start working.
Similarly, your header('Location: X') needs to be used prior to output being sent, otherwise the redirect will not work. However this appears just after an echo and the output of the DOCTYPE. Remove the echo and then edit the start of your instructor.php file thus:
<?php
include("../php/login.php");
include("../php/database.php");
?>
<!DOCTYPE html>
Here the output of the DOCTYPE should not happen until the loading of files and initialisation is complete. If there is any cookies/sessions/redirects to do, they can be done here.
All of these 'headers already sent' issues should raise a warning. If you are not seeing this in your development environment, you may have on-screen errors disabled - make sure they are turned on.

mysqli access denied (42000/1044) linux permissions?

I get the php error
mysqli::mysqli(): (42000/1044): Access denied for user
'sec_user01'#'localhost' to database 'secure_login'
I created the database with:
CREATE DATABASE `secure_login`;
I created the user with
CREATE USER 'sec_user'#'localhost' IDENTIFIED BY '**********************';
GRANT SELECT, INSERT, UPDATE ON `secure_login`.* TO 'sec_user'#'localhost';
I connect to the db using
include_once 'web_psl-config.php'; // As functions.php is not included
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
the config file is included successfully.
this worked up till a few hours ago.
The only thing I can think of that changed is that in my php script I made some folders with 755 access. Is it possible that the permissions from the files from which this script is executed are causing this error ?
I am really stumped.
edit: I tested this with an ADODB connection
require('../scripts/adodb5/adodb.inc.php');
$ADODB_CACHE_DIR = 'adodb5cache';
$Host = "localhost";
$Database = "secure_login";
$Databasetype ="mysql";
// lijst users en passwd
$DbAdminUser="sec_user01";
$DbAdminUserPassword="**************";
$debug = true; //debug on
//$debug = false; //debug off
//admin connection
$dbconn = ADONewConnection($Databasetype);
$dbconn->Connect($Host, $DbAdminUser, $DbAdminUserPassword, $Database);
$query="SELECT * FROM members;";
$ammount=$dbconn->GetAll($query);
print_r($ammount);
and this works. Is this some kind of bug in mysqli ?
I really hope I don't have to rewrite to use ADODB.
Login to your cpanel (www.example.com/cpanel)
Go to MySQL add database wizard
similar to "add database", "add_user" you will have a button
to add user" to the "database".
click on it,
added user should list under "priviledged user" for that "database".
Try to login into phpmyadmin with those credentials. If unsuccessful then your credentials might not matching.
The grant statement was wrongly formatted
GRANT SELECT, INSERT, UPDATE ON `secure_login`.* TO 'sec_user'#'localhost'; is wrong
GRANT SELECT, INSERT, UPDATE ON secure_login.* TO 'sec_user'#'localhost'; works.
Why did it work the first time I have no idea.
i have had this error a few times before, and to my understanding, which is limited on this error is that a many of things could be causing it, first and foremost try to reset your password, the way you do this is by going into a terminal and type.
$ mysqladmin -u root -p'oldpassword' password newpass
make notice to fill in your credentials where oldpassword, password, and newpass.
then try my php script i made, it will show you what fields you left blank and will use default parameters for them if they are still blank. the comments that pop up will also disappear within 10 seconds.
file 1
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" /><meta http-equiv="content-language" content="en-US" />
<title>MySQL Connection test</title>
<script type="text/javascript">
window.onload = function()
{
timedHide(document.getElementById('messages'), 10);
}
function timedHide(element, seconds)
{
if (element) {
setTimeout(function() {
element.style.display = 'none';
}, seconds*1000);
}
}
</script>
</head>
<body>
<span id="messages">
<?php include "constant.php"; ?>
</span>
</body>
</html>
file 2
constant.php
<?php
$database_ip = ""; //database ip adress goes inside quotes
$database_port = ""; //database port goes inside quotes
$database_name = ""; //database name goes inside quotes
$database_admin_user = ""; //admin username goes inside quotes
$database_admin_pass = ""; //admin password goes inside quotes
//do not modify anything past this point unless you know php well.
$database_link = null;
$database_defaults = array("127.0.0.","3306","MySQL","root","");
$error_defaults = array("error_no_101" => "required field *IP is empty, using default parameters!",
"error_no_102" => "required field *PORT is empty, using default parameters!",
"error_no_103" => "required field *NAME is empty, using default parameters!",
"error_no_104" => "required field *USER is empty, using default parameters!",
"error_no_105" => "required field *PASS is empty, using default parameters!");
if(empty($database_ip)){
$database_ip = $database_defaults[0];
echo $error_defaults["error_no_101"] . "<br/>";
}
if(empty($database_port)){
$database_port = $database_defaults[1];
echo $error_defaults["error_no_102"] . "<br/>";
}
if(empty($database_name)){
$database_name = $database_defaults[2];
echo $error_defaults["error_no_103"] . "<br/>";
}
if(empty($database_admin_user)){
$database_admin_user = $database_defaults[3];
echo $error_defaults["error_no_104"] . "<br/>";
}
if(empty($database_admin_pass)){
$database_admin_pass = $database_defaults[4];
echo $error_defaults["error_no_105"] . "<br/>";
}
$database_link = mysqli_connect($database_ip, $database_admin_user, $database_admin_pass, $database_admin_pass);
if (!$database_link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . mysqli_get_host_info($database_link) . "\n";
mysqli_close($database_link);
?>
i hoped this helped (=
THis error disappear when you add some privileges except the insert select update in user privileges!
So go add add all the privileges in cpanel with username and database name.

PHP Include another php that queries MySQL

In my site im trying to include on the top of each page a "banner" that is itself a separate php page that queries a MySQL database to return a number that displays.
When i goto the exact URL of the banner php url (www.sitename.com/banner.php) it works perfectly.
However, when i include the banner into another page include'banner.php' it returns the following error: Database access error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
I have 2 ways i need to include this, my main site pages are all php. My forum is phpbb and the file i need to include is HTML so i used (Note, i did ../ back out to the banners root, its not a matter of my file not being found.
Im assuming that when including the scope is different. How would i correctly accomplish this include?
Banner.php
<?php
require("../mysql.inc.php");
check_get($tp, "tp");
$tp = intval($tp);
$link = sql_connect();
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
if (!$result) {
echo "Database error.<br>\n";
exit;
}
list($total) = mysql_fetch_row($result);
mysql_free_result($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="menu_css.css" media="screen"/>
</head>
<body>
<div class="menucenter">
<div class="Online"> <? echo"$total" ?> Online</div>
</body>
</html>
mysql.inc.php
<?php
$SQLhost = "****.db.****.hostedresource.com";
$SQLport = "3306";
$SQLuser = "****";
$SQLpass = "****";
$SQLdb = "****";
function sql_connect()
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
if ($SQLport != "")
$link = #mysql_connect("$SQLhost:$SQLport","$SQLuser","$SQLpass");
else
$link = #mysql_connect("$SQLhost","$SQLuser","$SQLpass");
if (!$link) {
echo "Database access error ".mysql_errno().": ".mysql_error()."\n";
die();
}
$result = mysql_select_db("$SQLdb");
if (!$result) {
echo "Error ".mysql_errno($link)." selecting database '$SQLdb': ".mysql_error($link)."\n";
die();
}
return $link;
}
function sql_query($link, $query)
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
$result = mysql_query("$query", $link);
if (!$result) {
echo "Error ".mysql_errno($link).": ".mysql_error($link)."\n";
die();
}
return $result;
}
function check_get(&$store, $val)
{
$magic = get_magic_quotes_gpc();
if (isset($_POST["$val"])) {
if ($magic)
$store = stripslashes($_POST["$val"]);
else
$store = $_POST["$val"];
}
else if (isset($_GET["$val"])) {
if ($magic)
$store = stripslashes($_GET["$val"]);
else
$store = $_GET["$val"];
}
}
?>
#Craig, there is a possibility that the include file contains other includes which are not getting the right path. Can you paste some codes of the include file for us to validate the error ?
EDIT:
You have a missing quote at the end of the query.
$result = sql_query($link, "SELECT COUNT(*) FROM online_count);
It should be
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
EDIT:
You have a problem with the quotes. See you check_get function. $val is a variable and you dont need quotes around it. Check the below code.
if (isset($_POST[$val])) {
if ($magic)
$store = stripslashes($_POST[$val]);
else
$store = $_POST[$val];
}
else if (isset($_GET[$val])) {
if ($magic)
$store = stripslashes($_GET[$val]);
else
$store = $_GET[$val];
}
EDIT:
Also remove the quotes from $query:
$result = mysql_query($query, $link);
First things first:
Remove the # from your mysql statements and see if you are getting any other errors related to variables or so. You should not suppress errors while debugging.
Try printing the host, port, user and password variables inside the sql_connect() function and see if you are getting the correct values in your function.
If you have access to your server, check if /var/lib/mysql/mysql.sock exists, and has sufficient permissions.
srwxrwxrwx 1 mysql mysql 0 Sep 21 05:50 /var/lib/mysql/mysql.sock
If all is well till this point, you might want to troubleshoot your MySQL service further. A restart would help flush the connections, if that is the issue. Check a similar thread in SO too.

php header command isn't working

I'm having a problem getting this code to work on the website that I'd like to launch soon. In particular when I sign in the header won't redirect after a successful login. I have used this code before many times and I've never had a problem with it. The only difference now is that I'm using a different server and a different database. Here's the code that is giving me trouble:
<?php
/*set all the variables*/
$email = $_POST['email'];
$password = sha1($_POST['password']); /* hash the password*/
$conn = mysqli_connect ('servername', 'username', 'password', 'databasename') or die('Error connecting to MySQL server');
/*select the id from the users table that match the conditions*/
$sql = "SELECT id FROM users WHERE email = '$email' AND password = '$password'";
$result = mysqli_query($conn, $sql) or die('Error querying database.');
$count = mysqli_num_rows($result);
if ($count == 1) {
echo 'Logged in Successfully.';
$row = mysqli_fetch_array($result);
session_start();
$_SESSION['user_id'] = $row['id'];
/*If true head over to the users table*/
header('location: users_table.php');
}
/*If invalid prompt them to adjust the previous entry*/
else {
echo '<h2>Invalid Login</h2><br />';
echo '<h2>Click HERE to go back and adjust your entry.</h2>';
}
mysqli_close($conn);
?>
It's not a matter of it connecting properly because I get the message 'successful Login' but it won't redirect at all.
Thanks for all the answers, I tried removing the echo but all I get now is a blank page, I thought maybe it was the browser I was using so I switched to another and I still just get a blank page, any other suggestions?
You cannot echo anything before your header statement.
echo 'Logged in Successfully.';
This is causing the header call to not work.
if ($count == 1) {
echo 'Logged in Successfully.';
//this statement is creating problem
$row = mysqli_fetch_array($result);
session_start();
$_SESSION['user_id'] = $row['id'];
/*If true head over to the users table*/
header('location: users_table.php');
}
This is because you are echoing something berfore header
You should use ob_start() at start and ob_end_flush() at the end of the document..
or do not echo before header().As we found you haven't turned on the error.So turn it ON.
You can't be posting the header after the echo... if this actually worked you'd never see the text (it would simply redirect). (To fix remove/comment out the echo line)
Also the location header requires an absolute/full URL (although many browsers seem to cope with relative URLs).
If you want to do it this way (show some sort of status before hand), use an HTML or Javascript redirect that triggers after a couple of seconds.
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Logged in Successfully.</title>
<meta http-equiv="REFRESH"
content="5;url=http://www.example.com/users_table.php"></HEAD>
<BODY>
Logged in Successfully.
</BODY>
</HTML>
Javascript
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>Logged in Successfully.</title>
</HEAD>
<BODY onLoad="setTimeout(function() {
window.location='http://www.example.com/users_table.php'},5000)">
Logged in Successfully.
</BODY>
</HTML>
Better yet, allow the users_table.php page to display a successful login message and use the header-location redirect.

Categories