unable to connect to mysql through php on new page - php

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 = '';

Related

creating a copy of my app to create a "test server" does not work using php and mysql

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;
}

PHP cannot show tables from MySqli Query

I am trying to figure out why I can connect to a database, but cannot access the data in it.
Here's my configuration:
//config.php
<?php
define("HOST", "MYSERVERNAMEISHERE");
define("DATABASE", "users");
?>
My user logs in, and their information is passed to be checked:
//login.php
<?php
if ($_POST) {
if ($_POST["user"] && $_POST["password"]) {
include_once "config.php";
define("USER", $_POST["user"]);
define("PASSWORD", $_POST["password"]);
$link = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($link) {
$link->close();
if ($_SESSION) {
session_destroy();
}
session_start();
$_SESSION["user"] = $_POST["user"];
$_SESSION["password"] = $_POST["password"];
}
}
}
if ($_SESSION) {
header('Location: profile.php');
}
else {
header('Location: login.html');
}
?>
When they pass, they get to see their profile page.
//profile.php
<?php
session_start();
if (!$_SESSION["user"] || !$_SESSION["password"]) {
session_destroy();
header("Location: login.html");
}
else {
include_once "config.php";
}
$link = new mysqli(HOST, USER, PASSWORD, DATABASE) or die("Unable to connect to database");
$result = $link->query("SHOW TABLES") or die("Unable to show tables");
...
ADDITIONAL PHP AND HTML CODE AFTER THIS POINT
The problem is that the process dies when I try to query the mysqli link. (I get Unable to show tables) Right now, the SHOW TABLES is just filler for debugging; I will actually have useful mysqli queries when I figure out the issue.
Please help me determine where my bug is. If you find a typo or a reference link for me, sorry for wasting your time. I've been researching and debugging for hours now.
Thanks very much in advance.
PS: If you have some good advice for changes I should make, I appreciate those too. It's my first time making a user login.
Your query in profile.php is failing because USER and PASSWORD are not defined. When the person logs in, they are defined in login.php. When redirected to profile.php, USER AND PASSWORD do not have values since they are not in config.php.
In profile.php, change
$link = new mysqli(HOST, USER, PASSWORD, DATABASE) or die("Unable to connect to database");
to
$link = new mysqli(HOST, $_SESSION["user"], $_SESSION["password"], DATABASE) or die("Unable to connect to database");

Can't Link To MySQL database

I am learning MySQL/PHP and I cannot figure out how to connect to MySQL on my localhost. I have written a short bit of code and I included root as my user name and root as my password because I have not set these elements yet (as far as I know). I feel that perhaps I am missing something in regards to the username/password combination. However, I feel that this should not be an issue because I have not tampered with the default conditions.
I need some help.
My code is below:
<?php
try {
$db = new PDO("mysql:host=localhost;dbname=shirts4max;port=3306", "root", "root");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf-8'");
} catch (Exception $e) {
echo "Could not connect to the database.";var_dump($e);
exit;
}
I am only seeing the error message on my page:
"Could not connect to the database."
Thank for reading. Please help me Obiwan.
Show the real error. Avoid using root except for maintenance.
From the PDO Manual page here, modified for you
<?php
$dsn = 'mysql:dbname=shirts4max;host=localhost';
$user = 'root';
$password = 'root';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Have you tried connecting via command line using: mysql -uroot -proot -hlocalhost -p3306? If you can't connect that way, the PDO connection won't go through either. Playing with the connection info via command line gives you a nice easy way to find what works, then include it in your code. Also, if you've not set the user/pw, it's possible there isn't one currently, so you wouldn't need those parameters at all.

How can I prevent this script from being freely accessed?

I am trying to create a simple PHP/MySQL message system. The following code is a section of the page that displays the messages a user has received, messages.php. The user's messages have been fetched from MySQL and stored in the variable $messages.
foreach($messages as $message) {
// formatting, printing the text, etc.
echo 'Remove';
}
And here is the file msg_del.php:
<?php
$id = $_GET['id'];
// Connect to the database
require("../info/dbinfo.php");
$db_user = constant("DB_USER");
$db_pass = constant("DB_PASS");
$db_name = constant("DB_NAME");
$db_server = constant("DB_SERVER");
try {
$conn = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("DELETE FROM messages WHERE id = " . $conn->quote($id) . ";");
$stmt->execute();
}
catch(PDOException $e) {
echo "Error connecting to database!";
exit();
}
// Redirect to messages page
header("Location: messages.php");
exit();
?>
The code is fully functional, but the problem is that anyone can type msg_del.php?id=SOMEID into a browser and delete messages. How can I secure this to where messages can only be deleted from the links on messages.php?
You're going to need some sort of token in your request to validate that this is indeed a valid request from your system.
One method would be to append a nonce to your request. This ensures that the request came from a form you control, and someone isn't using an old form to spoof a new request.
There are many nonce libraries for PHP you can choose from.
The script needs to know if the current user has permission to do the action. One simple way to do that is with the $_SESSION variable.
Something like:
session_start();
if (!isset($_SESSION['user_id']) && /*permission logic here*/) {
//display an error message
die();
}
// database query here

PDO Exceptions in PHP

Okay I have a bit of a question dealing with $_POST. I'm attempting to send a few values from an Android App (Using HTTPclient) I'm developing but the PHP sends the message from the exception back. I'm trying to figure out why is that happening and how to fix it:
login
<?php
//load and connect to MySQL database stuff
require("configmob.php");
if (!empty($_POST)) {
//gets user's info based off of a username.
$query = "
SELECT
myusername,
mypassword
FROM Customer
WHERE
myusername = :myusername
mypassword = :mypassword";
$query_params = array(
':myusername' => $_POST['username'],
':mypassword' => $_POST['password']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$validated_info = false;
//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
//if we encrypted the password, we would unencrypt it here, but in our case we just
//compare the two passwords
if ($_POST['password'] === $row['password']) {
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if ($login_ok) {
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
} else {
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}
}
?>
config
<?php
// These variables define the connection information for your MySQL database
$host = "mysql17.000webhost.com";
$dbname = "a4335408_data1";
$username = "******";
$password = "******";
// UTF-8 is a character encoding scheme that allows you to conveniently store
// a wide varienty of special characters, like ¢ or €, in your database.
// By passing the following $options array to the database connection code we
// are telling the MySQL server that we want to communicate with it using UTF-8
// See Wikipedia for more information on UTF-8:
// http://en.wikipedia.org/wiki/UTF-8
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
// A try/catch statement is a common method of error handling in object oriented code.
// First, PHP executes the code within the try block. If at any time it encounters an
// error while executing that code, it stops immediately and jumps down to the
// catch block. For more detailed information on exceptions and try/catch blocks:
// http://us2.php.net/manual/en/language.exceptions.php
try
{
// This statement opens a connection to your database using the PDO library
// PDO is designed to provide a flexible interface between PHP and many
// different types of database servers. For more information on PDO:
// http://us2.php.net/manual/en/class.pdo.php
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
// If an error occurs while opening a connection to your database, it will
// be trapped here. The script will output an error and stop executing.
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code
// (like your database username and password).
die("Failed to connect to the database: " . $ex->getMessage());
}
// This statement configures PDO to throw an exception when it encounters
// an error. This allows us to use try/catch blocks to trap database errors.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// This statement configures PDO to return database rows from your database using an
associative
// array. This means the array will have string indexes, where the string value
// represents the name of the column in your database.
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// This block of code is used to undo magic quotes. Magic quotes are a terrible
// feature that was removed from PHP as of PHP 5.4. However, older installations
// of PHP may still have magic quotes enabled and this code is necessary to
// prevent them from causing problems. For more information on magic quotes:
// http://php.net/manual/en/security.magicquotes.php
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);
}
// This tells the web browser that your content is encoded using UTF-8
// and that it should submit content back to you using UTF-8
header('Content-Type: text/html; charset=utf-8');
// This initializes a session. Sessions are used to store information about
// a visitor from one web page visit to the next. Unlike a cookie, the information is
// stored on the server-side and cannot be modified by the visitor. However,
// note that in most cases sessions do still use cookies and require the visitor
// to have cookies enabled. For more information about sessions:
// http://us.php.net/manual/en/book.session.php
session_start();
// Note that it is a good practice to NOT end your PHP files with a closing PHP tag.
// This prevents trailing newlines on the file from being included in your output,
// which can cause problems with redirecting users.
?>
Thank you and I hope this question isn't too difficult or anyhting.
Try replacing the static error message with the exception message to see what's going wrong
Change:
$response["message"] = "Database Error1. Please Try Again!";
to:
$response["message"] = $ex->getMessage();
Conditions in a WHERE statement must be separated with AND keyword

Categories