PHP SESSION will not be set by value from DB - php

Problem: I have built an login system and it works fine on my localhost.
Localhost: Here it works.
FTP-server: Here it's not working.
I've tried to fix this for 7 hours now.
$_POST is getting the value, if I set a $_SESSION it also shows the value.
DB info is correct.
I think the problem is when connecting to DB to get values. Where I did wrong I do not know, as above tried to fix this for a long time now.
Login file:
<?php
ini_set("default_charset","iso-8859-1");
session_start();
require_once("db_config.php");
echo $_SESSION['USER_ID']." - ";
if(!empty($_POST['username']) AND !empty($_POST['password'])) {
$username_db = $_POST['username'];
$password_db = $_POST['password'];
if(isset($username_db) AND isset($password_db)) {
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$qry="SELECT * FROM user_table WHERE email='".$username_db."' OR alias='".$username_db."' AND password='".$password_db."' ";
$result=mysql_query($qry);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while($rows=mysql_fetch_row($result)) {
$_SESSION['USER_ID'] = $rows['id'];
header("Location: index.php");
}
}
}
if(!empty($_SESSION['USER_ID'])) {
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$qry="SELECT * FROM user_table WHERE id='".$_SESSION['USER_ID']."'";
$result=mysql_query($qry);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while($rows=mysql_fetch_array($result)) {
header("Location: index.php");
}
}
?>
check if login SESSION is set: I think there is some messed up code here.
<?php
ini_set("default_charset","iso-8859-1");
session_start();
require_once("db_config.php");
if(!empty($_SESSION['USER_ID'])) {
$user_id = $_SESSION['USER_ID'];
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$qry="SELECT * FROM user_table WHERE id='".$user_id."'";
$result=mysql_query($qry);
if (!$result) {
header("Location: login.php");
die('Invalid query: ' . mysql_error());
}
while($rows=mysql_fetch_array($result)) {
$_SESSION['ALIAS'] = $rows['alias'];
$_SESSION['FIRST_NAME'] = $rows['first_name'];
$_SESSION['LAST_NAME'] = $rows['last_name'];
$_SESSION['EMAIL'] = $rows['email'];
$_SESSION['USER_LEVEL'] = $rows['user_level'];
}
} else { header("Location: login.php"); }
?>

Related

PHP and SQL -- Select from database

I have a problem with this code. It has syntax error and I don't know what is it.
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'id1381007_accounts';
$conn = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
if (!$conn) {
die('Could not connect: ' . mysql_error());
$sql = 'SELECT id FROM users WHERE email=\"donat12#icloud.com\"';
echo $sql;
?>
There are some issue with the code. First you forgot to close the if condition over here
if (!$conn) {
And then you forgot to execute the sql query
the complete code would be like
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'id1381007_accounts';
$conn = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id FROM users WHERE email=\"donat12#icloud.com\"';
if ($result = $conn->query($sql)) {
while ( $row = $result->fetch_assoc()) {
$data[] = $row;
}
echo "<pre>";
print_r($data);
echo "</pre>";
}
$conn->close();
?>
There are two errors
You are missing } closing bracket after die
Mysql query is wrong.
So the code should be
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id FROM users WHERE email="donat12#icloud.com"';
echo $sql;

Checking if username is available

I am trying to check if the username is available before i insert into the table.
But it seems to insert into the table no matter if the username already exists.
Here is my php code:
<?php
session_start();
define('DB_NAME', 'madsanker_dk_db');
define('DB_USER', 'madsanker_dk');
define('DB_PASSWORD', 'myPassword');
define('DB_HOST', 'mysql43.unoeuro.com');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' .mysqli_error());
}
$db_selected = mysqli_select_db( $link, DB_NAME);
if (!$db_selected) {
die('Could not connect: ' .mysqli_connect_error());
}
$username = $_POST['username'];
$password = $_POST['password'];
$name = $_POST['name'];
$email = $_POST['email'];
$username = mysqli_real_escape_string($link,$username);
$password = mysqli_real_escape_string($link,$password);
$name = mysqli_real_escape_string($link,$name);
$email = mysqli_real_escape_string($link,$email);
$password = md5($password);
$sql = "SELECT * FROM mainLogin WHERE username = '$username'";
$result = mysqli_query($link, $sql);
$count = mysqli_num_rows($result);
if($count > 0) {
$sql = "INSERT INTO mainLogin (username, password, name, email) VALUES ('$username', '$password', '$name','$email' )";
$result = mysqli_query($link, $sql);
if (!$result) {
die('Error: ' . mysqli_error($link));
}else {
$_SESSION['login'] = $username;
echo "<script>window.location = 'http://madsanker.dk.linux101.unoeuro-server.com'</script>";
}
}else {
echo "username taken";
}
mysqli_close($link);
?>
What am I doing wrong?
just change the greater sign in your if statement from ">" to ==0
if($count==0){
}
If username already in db than change this condition:
if($count > 0) { 
//your stuff
}
With:
if($count <= 0) { // if not found
//your stuff
}

PHP Login and connecting to MySql

I am new to PHP. I am creating a login.php page. i have created a table into MySQL database.
Database name: school
Table name: users
I have saved a username = admin and pass= 123
I am now trying to connect the database and trying to verifying the input information from database before accessing to the page "admin.php"
<?php
error_reporting(E_ERROR);
global $link;
$servername='localhost';
$dbname='school';
$dbusername='root';
$dbpassword='';
$table_Name="users";
$link = mysql_connect($servername,$dbusername,$dbpassword);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
else
{
mysql_select_db($dbname,$link) or die ("could not open db".mysql_error());
}
?>
Getting input data from this code
<?php
$my_user = $_POST['user'];
$my_password = $_POST['password'];
?>
trying this
$signin = mysql_query( "SELECT FROM users where username = &my_user" )
or die("SELECT Error: ".mysql_error()); $num_rows = mysql_num_rows($signin);
Now kindly explain with code how can I connect the database and verify the information and if its correct the page should redirect to admin.php page
This will insert the form info into database:
$insert="INSERT INTO `users`(`user`,`password`) VALUES ('$my_user','$my_password') ";
$query=mysql_query($insert,$link);
This will select the info from database:
$result=mysql_query('SELECT * FROM users WHERE username='$my_user' AND password='$my_password'");
$sql1=mysql_query($result,$link);
<?php
if (isset($_POST)) {
$my_user = $_POST['user'];
$my_password = $_POST['password'];
$con=mysql_connect("localhost","root","");
if(!$con)
{
die("Database is not connected");
}
mysql_select_db("school",$con);
$query="select * from users where username=$my_user and pass=$my_password";
$res=mysql_query($query);
if(mysql_num_rows($res) > 0)
header('Location:admin.php'); // redirect to home page
else
echo 'Not found'; // can show some validation err
}
<?php
include('conn.php');
if (isset($_POST['submit'])){
$UserName=$_POST['user'];
$PassWord=$_POST['pass'];
$sql = "SELECT username,pass from login WHERE username='$UserName'and password='$PassWord'";
$retval = mysql_query($sql);
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
if (($row['username']==$Username)and($row['pass']==$Password)){
header("location:admin.php");
}
}
}
echo "Invalid User Name and Password\n";
?>
Start to use PDO for database connections. I have not tested this, but should give you insight into what to do.
config.php
<?php
define('DB_TYPE', 'mysql');
define('DB_HOST', 'localhost');
define('DB_NAME', 'school');
define('DB_USER', 'root');
define('DB_PASS', '');
?>
functions.php
<?php
function validate_user_creds() {
try
{
$pdo = new PDO(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME.', '.DB_USER.', '.DB_PASS);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
header('Location: admin.php');
exit();
}
catch (PDOException $e)
{
$error = 'Unable to connect to the database server.';
include 'error.html.php';
exit();
}
}
?>
login.php
<?php
require 'config.php';
require 'functions.php';
if ($_POST['user'] === DB_NAME && $_POST['password'] === DB_PASS) {
validate_user_creds();
}
?>
Normally with mysql (deprecated!)
<?php
error_reporting(E_ERROR);
$error = false;
if(isset($_POST['login']))
{
$servername = 'localhost';
$dbname = 'school';
$dbusername = 'root';
$dbpassword = '';
$table_Name = 'users';
$link = mysql_connect($servername, $dbusername, $dbpassword) or die('Could not connect: ' . mysql_error());
mysql_select_db($dbname, $link) or die ('could not open db' . mysql_error());
$my_user = $_POST['user'];
$my_password = $_POST['password'];
$signin = mysql_query("SELECT * FROM `users` WHERE `username` = '" . mysql_real_escape_string($my_user) . "' AND `password` = '" . mysql_real_escape_string($my_password) . "' LIMIT 1;")
or die('SELECT Error: '.mysql_error());
$num_rows = mysql_num_rows($signin);
mysql_close($link);
if($num_rows)
{
header('Location: admin.php');
}
else
{
$error = 'Unknown login!';
}
}
?><html><head><title>Login</title></head><body>
<form action="#" method="post">
<?php if($error !== false) { echo '<p>' . $error . '</p>'; } ?>
<input name="user" type="text" size="255" />
<input name="password" type="text" size="255" />
<button type="submit" name="login">Login</button>
</form>
</body></html>
PDO / MySQLi
<?php
error_reporting(E_ERROR);
$error = false;
if(isset($_POST['login']))
{
$servername = 'localhost';
$dbname = 'school';
$dbusername = 'root';
$dbpassword = '';
$table_Name = 'users';
$link = new mysqli($servername, $dbusername, $dbpassword, $dbname);
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$my_user = $_POST['user'];
$my_password = $_POST['password'];
if(!($signin = $link->prepare('SELECT * FROM `users` WHERE `username` = ? AND `password` = ? LIMIT 1;')))
{
printf("Select Error: %s\n", $link->error);
exit();
}
$signin->bind_param('ss', $my_user, $my_password);
if($signin->execute())
{
$signin->store_result();
$num_rows = $signin->num_rows;
if($num_rows)
{
header('Location: admin.php');
}
else
{
$error = 'Unknown login!';
}
}
$link->close();
}
?><html><head><title>Login</title></head><body>
<form action="#" method="post">
<?php if($error !== false) { echo '<p>' . $error . '</p>'; } ?>
<input name="user" type="text" size="255" />
<input name="password" type="text" size="255" />
<button type="submit" name="login">Login</button>
</form>
</body></html>
Use PDO with prepared statements when you access databases in PHP, since it helps against SQL injection. Have a look at http://php.net/manual/en/intro.pdo.php.
Edit:
Wayne's answer is just confusing. In login.php he is validating the administrator by comparing the user's name to the database name and the user's password to the database's password. I don't recommend it, and it doesn't really have much to do with what you posted.
I'd go with PatrickB's answer.
if(mysql_num_rows(mysql_query("select * from users where username='$my_user' and pass='$my_password'"))>0) {
header('Location:admin.php');
} else {
echo " < b > Incorrect username or password<\b>";
}

Deleting row from a MySQL Table using checkboxes and a button

I want to make a table with the members of a website and in this table when you check the checkboxes and you press the "Delete" button to delete this member from the members table and also to delete his applications from the applications table. With my code when I click the delete button it prints me "Query failed"
This is my code:
<?php
require_once('config.php');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$data = mysql_query("SELECT * FROM members ") or die(mysql_error());
echo ' <form action="members-exec.php">
<table width="760" border=1>
<tr>';
if(isset($_SESSION['SESS_RANK'])) {
echo '
<th></th>';
}
echo '
<th>Служител:</th>
<th>Отпуск отпреди 2009год.</th>
<th>Отпуск от мин. год.</th>
<th>Отпуск от тек. год.</th>
</tr>';
while($info = mysql_fetch_array( $data ))
{
echo '
<tr>';
if(isset($_SESSION['SESS_RANK'])) {
echo '
<td>
<input type="checkbox" name="'.$info['firstname'] .' '.$info['lastname'] .'" value="'.$info['firstname'] .' '.$info['lastname'] .'" />
</td>';
}
echo '
<td>'.$info['firstname'] .' '.$info['lastname'] .'</td>
<td>'.$info['predi'] .'</td>
<td>'.$info['minali'] .'</td>
<td>'.$info['tekushti'] .'</td>';
}
echo' </tr> ';
echo '</table>';
if(isset($_SESSION['SESS_RANK'])) {
echo '
<br> <input type="submit" name="remove" value="Delete" /></form>';
}
?>
This is my php part:
<?php
session_start();
require_once('config.php');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$qry = "DELETE FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'" && "DELETE FROM applications WHERE userfname = '$userfname'";
$result = mysql_query($qry);
if($result) {
header("location: members.php");
exit();
}else {
die("Query failed");
}
?>
EDIT:
<?php
session_start();
require_once('config.php');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$qry = "DELETE FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'" ;
$result = mysql_query($qry);
$qry = "DELETE FROM applications WHERE userfname = '$userfname'";
$result = mysql_query($qry);
if($result) {
header("location: members.php");
exit();
}else {
die("Query failed");
}
?>
$qry = "DELETE FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'"
&& "DELETE FROM applications WHERE userfname = '$userfname'";
There's your problem - you're trying to do two SQL statements with one call, and mysql_query won't let you do that. It should work if you do two separate queries.
HOWEVER
You should look at moving to mysqli_* or PDO - mysql_* is being deprecated. You can do multiple queries in one call directly using mysqli, too; and they both make use of bound parameters, which helps you write more secure code.
You are trying to execute two delete statements in one query. This is a no-no.
You will need to split the statements into two executes:
$qry = "DELETE FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'";
$result = mysql_query($qry);
$qry="DELETE FROM applications WHERE userfname = '$userfname'";
$result = mysql_query($qry);
You can always try and use mysqli_multi_query()

Simple php/mysql not working

I have the following in a php script.All I get is a blank page, no errors or nothing.
error_reporting(E_ALL);
ini_set("display_errors", 1);
$database = "mydatabase";
$con = mysql_connect("localhost", "admin", "password") or die(mysql_error());
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db = mysql_select_db($database);
if(!$db){
die('Could not connect: ' . mysql_error());
}
if(isset($_POST['id'])){
$userid = mysql_real_escape_string($_POST['id']);
echo($userid);
}
if(isset($_POST['name')){
$username = mysql_real_escape_string(htmlentities($_POST['name']));
echo($username);
}
$query = mysql_query("SELECT * FROM userinfo
WHERE userid ='$userid'")or die(mysql_error());
if(mysql_num_rows($query) > 0){
echo "yeah";
}else{
$query = mysql_query("INSERT INTO userinfo (username,userid)
VALUES ($username,$userid)")or die(mysql_error());
if(mysql_affected_rows($query)== 1){
echo "UPDATED";
}else{
echo "NOPE";
}
}
You should format your code better. Also you where missing a close ] bracket on this line, if (isset($_POST['Name')) {
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$database = "mydatabase";
$con = mysql_connect("localhost", "admin", "password") or die(mysql_error());
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db = mysql_select_db($database);
if(!$db)
{
die('Could not connect: ' . mysql_error());
}
if(isset($_POST['id']))
{
$userid = mysql_real_escape_string($_POST['id']);
echo($userid);
}
if(isset($_POST['name']))
{
$username = mysql_real_escape_string(htmlentities($_POST['name']));
echo($username);
}
$query = mysql_query("SELECT * FROM userinfo WHERE userid ='$userid'")or die(mysql_error());
if(mysql_num_rows($query) > 0)
{
echo "yeah";
}
else
{
$query = mysql_query("INSERT INTO userinfo (username,userid) VALUES ($username,$userid)")or die(mysql_error());
if(mysql_affected_rows($query)== 1)
{
echo "UPDATED";
}
else
{
echo "NOPE";
}
}
?>
You also have an error in your SQL:
INSERT INTO userinfo (username,userid)
VALUES ($username,$userid)
The values here should be quoted:
INSERT INTO userinfo (username,userid)
VALUES ('$username', '$userid')

Categories