Hello, I'm kind of new to php, so don't bash on me, but I just can't figure out what the problem is with this code. So basically I have several forms of output, but as soon as I do anything with mysql ( even just connect and disconnect! ), it won't allow me to do any kind of output. It also won't allow me to redirect.
I tried taking all the code out between the mysql connect and disconnect code and it didn't help to resolve anything, However, as soon as I comment out the mysql connection code, all my outputs and redirects work! I'm trying to build a simple login script that gets the email and password from a form elsewhere. I would love to get this resolved so I could figure out if the rest of it works. And I know that 'header' will not work after echo; the echo and the file writes will not be there as soon as I can make sure this is working. Any help would be appreciated! Thanks!
<?php
/*
Login.php searches for the email address given by loginPage.php in the data base.
If the email is found and the password given by loginPage.php matches that stored
in the data base, a session will begin and the client will be redirected to the
main page.
*** INCOMPLETE ***
*/
echo "HELLO!";
$email = $_POST["email"];
$password = $_POST["password"];
$errorLog = fopen("login.txt", "w");
fwrite($errorLog, "***Sesion started***");
$mysql_id = mysql_connect("localhost", "root", "12131");
if (!$mysql_id)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('informationStation', $mysql_id);
$results = mysql_query("SELECT password FROM Personals WHERE email = '" . $email . "';", $mysql_id);
if($results != null && $password == mysql_fetch_array($result))
{
$redirect = 'Location: http://127.0.1.1/main.php';
}
else
{
$redirect = 'Location: http://127.0.1.1/loginPage.php';
{
mysql_close($mysql_id);
fwrite($errorLog, "result: " . $results);
fwrite($errorLog, "redirect: " . $redirect);
fclose($errorLog);
header($redirect);
?>
Try this to get you started..
$results = mysql_query("SELECT password FROM Personals WHERE email = '" . $email . "'", $mysql_id) or die(mysql_error());
But you also need to read about sql injection.
And you should not store passwords in your database without salting and hashing them.
And you also need to use array syntax to access the data from your result...
$mysql = mysql_connect("localhost", "root", "12131") or die('Could not connect: ' . mysql_error());
mysql_select_db('informationStation', $mysql);
function loged($email, $password) {
$result = mysql_query("SELECT id FROM Personals WHERE email = '" . $email . "' AND password='" . $password . "'");
if(mysql_num_rows($result) != 1)
return false;
return true;
}
if(loged(mysql_real_escape_string($email), md5($password))) {
header('Location: http://127.0.1.1/mainPage.php');
exit;
}
header('Location: http://127.0.1.1/loginPage.php');
In this example you need to store users password using md5 encryption method (search for other more securely encryption methods).
Also we've escaped the email address against sql injection.
I've created a function which can be called every time you want to see if the user is loged in or not.
Note that this is not a complete login script. You will also need to make a login function where you'll have to start a new session for each user.
Related
Im new on php, so i need some sugests for following code:
<?php
// Start the session (pretty important!)
session_start();
// Establish a link to the database
$dbLink = mysql_connect('', '', '');
if (!$dbLink) die('Can\'t establish a connection to the database: ' . mysql_error());
$dbSelected = mysql_select_db('', $dbLink);
if (!$dbSelected) die ('We\'re connected, but can\'t use the table: ' . mysql_error());
$isUserLoggedIn = false;
$query = 'SELECT * FROM users WHERE session_id = "' . session_id() . '" LIMIT 1';
$userResult = mysql_query($query);
if(mysql_num_rows($userResult) == 1) {
$_SESSION['user'] = mysql_fetch_assoc($userResult);
$isUserLoggedIn = true;
} else {
if(basename($_SERVER['PHP_SELF']) != 'conectare.php') {
header('Location: conectare.php');
exit;
}
}
?>
Upper code verify if user it's logged in or not..
I need to create a profil link, like following:
http://site.com/profile.php?name=NAME-OF-USER
Can someone give me a ideea?
Im newbie on php, so pls understand me..
PS: Please dont tell me to use mysql, pdo and another, i allready know the beneficts, i need only answers for my code..
Thank you !
you simply need to use the get variable
create the link that will be clicked like this
the link that will be clicked on home page or any other page
<?php
$username='test';//the variable containing the username
echo'<a href="mysite.com/profile.php?user='.$username.'">
The link redirecting to profile page
</a>';
?>
the address bar will turn something like this www.mysite.com/profile.php?user=test
then on the profile page
<?php
$username_selector=$_GET['user']//in this case the value got from the link clicked is test
//then just select the necessary data using the variable storing the value got from th link clicked
?>
All you need to do is echo some html:
$username = "foo";
echo "profile link";
Note: I use \" to escape the "
More information about strings in php: http://php.net/manual/en/language.types.string.php
I've been told that this code is old way of connecting and is susceptible to sql injections. How can I make it secure?
This is the code I use to check a database for users and add a new user if they don't have an account. I tried mysqli but I don't think I got it right so I had to go back to this for now until I know how to make it secure.
<?php
// Connect to the database(host, username, password)
$con = mysql_connect('localhost','user1','pass1');
if (!$con)
{
echo "Failed to make connection.";
exit;
}
// Select the database. Enter the name of your database (not the same as the table name)
$db = mysql_select_db('db1');
if (!$db)
{
echo "Failed to select db.";
exit;
}
// $_POST['username'] and $_POST['password'] are the param names we sent in our click event in login.js
$username = $_POST['username'];
$password = $_POST['password'];
// Select eveything from the users table where username field == the username we posted and password field == the password we posted
$sql = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . $password . "'";
$query = mysql_query($sql);
// If we find a match, create an array of data, json_encode it and echo it out
if (mysql_num_rows($query) > 0)
{
$row = mysql_fetch_array($query);
$response = array(
'logged' => true,
'name' => $row['name'],
'email' => $row['email']
);
echo json_encode($response);
}
else
{
// Else the username and/or password was invalid! Create an array, json_encode it and echo it out
$response = array(
'logged' => false,
'message' => 'Invalid Username and/or Password'
);
echo json_encode($response);
}
?>
Any data coming from a user should be passed through mysql_real_escape_string(). See the URL below for more information on using that function. It's very important.
http://php.net/manual/en/function.mysql-real-escape-string.php
Here is a little more information on SQL Injections with PHP:
http://php.net/manual/en/security.database.sql-injection.php
MySQLi Information (another technique besides mysql_real_escape_string):
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
EDIT: OK, I'll admit, I'm kinda old-school. MySQLi definitely seems to be the way to go. I'm more familiar with PHP3 and PHP4 development. If you can, re-implement your data-access code using the last link.
I am looking for some kind of bug in my code which is causing this PHP page to not redirect. I'm looking to see if someone might know the cause of this problem (it may have something to do with the cookies).
inc_vars.php:
<?php
//some of the variables have been omitted.
$pid = 'gbb';
$dbtable ='';
$dbname = '';
$dbuser = '';
$dbpass = '';
$connect = mysql_connect('localhost', $dbuser, $dbpass);
if(!$connect){
header('Location: omitted');
die();
}
mysql_select_db ($dbname, $connect);
$webroot = 'omitted';
$share_page = $webroot . '/share-the-training';
$gift = $webroot . '/free-video?setuser=1199';
$bonus_content = $webroot . '/awesome-bonus';
$share_php = $webroot . '/share.php';
?>
refresh_id.php:
<?php
include_once('inc_vars.php');
$results = mysql_query("SELECT id FROM " . $dbtable . " WHERE email='" . $_GET['email'] . "'");
if(!$results || mysql_num_rows($results)==0){
header('Location: ' . $share_page . '?errorcode=1');
die();
}
$res_arr = mysql_fetch_assoc ($results);
setcookie($pid . "_viral", (string)$res_arr['id'], time() + 3600 * 365);
move_on();
function move_on(){
header ('Location: ' . $share_php);
die();
}
?>
When the person visits refresh_id.php?email=their_email they should redirect to the $share_php page. This is not working.
However, if this scenario happens: refresh_id.php?email=an-email-that-is-not-in-database then the script redirects to $share_page absolutely fine.
I have tried this with and without the gbb_viral cookie in place. I'm not sure why this isn't working. All pages are live and on the internet right now in case you want to look for yourself.
omitted
An email that exists in the database is as follows: acctrafficcop#gmail.com (for those that want to test this)
UPDATE
Stupid mistake with scopes. I simply added global $share_php in the move_on() function and everything is working fine now. Thank you everyone for the heads up on SQL injection, I am switching over to prepared statements right now.
In your move_on function, the variable $share_php does not exist because of variable scope. Therefore your redirect looks like this: Location:. There is no URL in the Location header.
You can pass the variable into the function, or use the global keyword to make it available. Try this:
move_on('/redirect_url');
function move_on($url){
header ('Location: ' . $url);
die();
}
In fact, in refresh_id.php I don't see a variable called $share_php anywhere, so you are redirecting to an empty URL.
You also need to set a status header for the browser to honor the location header. Try adding
header('HTTP/1.1 303 See Other');
Using curl will help you debug. Also, your are setting yourself up for SQL Injection with your SQL query.
Edit: After reading the second answer, it is correct that you aren't passing in a location to your redirection function. This should be fixed as well.
$results = mysql_query("SELECT id FROM " . $dbtable . " WHERE email='" . $_GET['email'] . "'");
Never trust input from users like this. Instead, use a SQL bind. Here's how you would do it with the mysqli library: http://php.net/manual/en/mysqli-stmt.bind-param.php
I'm ripping my noob hair out here. Can't understand why below code isn't working. The page loads alright, but when I try to log in with the username and password that is in my database the page is just reloaded to its original state with the login form, when I'd actually like to see a logout button instead. I've also tried comparing the password without salt and hash with an unhashed, unsalted equivalent in the database. Not working.
The only warnings I get are "It is not safe to rely on the system's timezone settings.", and I don't think those have anything to do with the password verification functionality.
The page starts out like this:
session_start();
error_reporting(-1); ini_set('display_errors', 'On');
Then follows some HTML. Then:
if (isset($_POST['log_out'])) {
session_unset();
session_destroy();
$_SESSION = array();
}
The logout button, when pressed, sets $_POST['log_out']. Then comes a function I got from a book, used to prevent SQL injection:
function mysql_fix_string($string) {
if (get_magic_quotes_gpc()) $string = stripslashes($string);
$string = htmlspecialchars($string, ENT_QUOTES);
$string = mysql_real_escape_string($string);
return $string;
}
Then comes the password verification part, which should only run if the user has submitted the login form (which posts back to the same page, thus setting $_POST['username'] and $_POST['password']):
if (isset($_POST['username']) && isset($_POST['password'])) {
$salt1 = 'how';
$salt2 = 'pony';
$password = md5($salt1 . $_POST['password'] . $salt2);
$db_hostname = 'xxxxxxxxx';
$db_username = 'xxxxxxxxx';
$db_password = 'xxxxxxxxx';
$db_database = 'xxxxxxxxx';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
$username = mysql_fix_string($_POST['username']);
$query = "SELECT password FROM users WHERE name = '" . $username . "'";
$result = mysql_fetch_assoc($query);
$passwordindatabase = $result['password'];
if ($password == $passwordindatabase) {
$_SESSION['logged_in'] = true;
$_SESSION['user'] = $username;
unset($_POST['username']);
unset($_POST['password']);
}
}
A bit further down comes the login form, only shown if ($_SESSION['logged_in'] != true). It posts the values of the input fields username and password to $_SERVER['REQUEST_URI'] (the same page).
Looks to me like you're missing the mysql_query() function which means you aren't actually executing the query.
mysql_query — Send a MySQL query
Do the following and see if it works:
$result = mysql_query($query);
$passwordindatabase = mysql_fetch_assoc($result);
Edit
On a completely different note, you should not use mysql functions since they are quite old fashioned and have mysql_injection vulnerability. I would advice you to start working with PDO as soon as possible, which (if done right) has got no mysql_injection vulerabilities.
The only bit that "smells" about the code you're showing is this:
if ($password == $passwordindatabase) {
I'd prefer to see something like this:
if (strcmp($password, $passwordindatabase) == 0) {
Also we need to see the code where you're actually inserting the values into the users table, because clearly $password and $passwordindatabase aren't matching.
To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
But, timezone warning is send before.
Set the timezone on php.ini file.
edited..
not only this problem. you must use mysql_query() function on sql request before mysql_fetch_assoc().
I have a site that I am storing the username and hashed password in a table. I am trying to compair this information (username and hashed password) to the login information passed from my login site. Unfortunately this keeps crashing. If someone could point me in the right direction as to what I am doing wrong I would appreciate it. Below is the code I am using to check the login. It may be something very simple as I am still pretty new to php.
<?php
$myServer = "server.domain.com";
$myUser = "readaccess";
$myPass = "password";
$myDB = "database";
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
$selected = mssql_select_db($myDB, $dbhandle)
or die("Couldn't open database $myDB");
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
//declare the SQL statement that will query the database
$query = "SELECT password, salt ";
$query. = "FROM dbo.members ";
$query. = "WHERE username = '$myusername' ";
$result = mssql_query($query)
or die('A error occured: ' . mssql_get_last_message());
// SQL_num_row is counting table row
$count=mssql_num_rows($result);
if($count) < 1) //no such user exists
{
header('Location: main_login.php');
}
$userData = mssql_fetch_array($result, MSSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $mypassword) );
if($hash != $userData['password']) //incorrect password
{
header('Location: main_login.php');
}
else {
header('Location: index.php');
}
?>
I think the problem is this line
$result = mssql_query($query)
or die('A error occured: ' . mssql_get_last_message());
The proper way to check failure is
$result = mssql_query($query, $dbhandle);
if(!$result)
die('A error occured: ' . mssql_get_last_message());
Note that this goes for the mssql_connect and mssql_select_db statements as well.
Note that you need to provide the database resource to the mssql_query function.
Also, most people find it more readable if you use .= without a space between them. I don't think it produces a parse error, but it make a lot of sense to keep the whitespace out of the operand. (You wouldn't do $counter+ +; even if it were legal.)
Note for asking future questions, always include whatever error message you're seeing and, if it is referencing a line number, point out that line in your code sample. In this case, I don't think your problem has anything to do with hashing or sql, as it's entirely a parse/syntax error.