Students Portal

Show query from sql with session (PHP)

I’m using login feature with session and SQL, in my sql there is a column called first name, I’m trying to find out how can I show after the login Hello $firstname which is not working and not Hello $username which is working and show the username. Thanks for your help.

 else < $fmsg = "Invalid Login Credentials."; >> if (isset($_SESSION['username']))< $username = $_SESSION['username']; echo "Hello " . $username . " "; echo "This is the Members Area "; echo "Logout"; >else header('location: login.php'); ?> 

Your code is vulnerable to SQL injection attacks. You should use prepared statements with bound parameters, via either the mysqli or PDO drivers. This post has some good examples.

Never store plain text passwords. Instead use password_hash() and password_verify() . If you’re using a version of PHP prior to 5.5, do not use MD5 or SHA1 to hash passwords. Instead you can use this compatibility pack.

chill guys, I’m still a rookie, thats why i’m here, to improve myself 🙂 I will check everything you guys said

3 Answers 3

 else < $fmsg = "Invalid Login Credentials."; >> if(isset($_SESSION['username'])) < echo "Hello " . $_SESSION['firstname']." . You are just logged in.
"; echo "This is the Members Area"; echo "Logout"; > else header('location: login.php'); ?>

Note : use some password encryption to encrypt n decrypt password to maintain user privacy (E.g md5)

Thanks first of all, thats the error I get Notice: Undefined index: firstname in index2.php on line 22 and i’m still practice on this, i’m sure md5 and encryption in general will come after.

Читайте также:  Event listeners in php

Learn from mistakes. Do not repeat them. Never hesitate to ask anything because no one is perfect. Always try to improve your coding standards.

 else < $fmsg = "Invalid Login Credentials."; >> if (isset($_SESSION['username']))< $username = $_SESSION['username']; $firstname = $_SESSION['firstname']; // you ofcourse can assign $firstname again here echo "Hello " . $username ; // you don't need the appending ." "; echo "Hello " . $firstname ; // can echo $firstname succesfully here echo "This is the Members Area "; echo "Logout"; >else header('location: login.php'); ?> 

Now, you can take advice from other answers and comments and see the vulnerability in your code.

Your question is hard to be answered because it has too many problems that will cost you. The code is poorly written, vulnerable and more.

Please accept my advice and follow a simple tutorial how to create a better login system.

Update because the OP really wants an answer to his question:

First of all check if you are actually posting «firstname»:

If you are, then you need to store the «firstname»:

$firstname = $_POST['firstname']; 

Inside your result of the query:

NOTE: I only give you a solution because you really wanted it. Your code is very vulnerable and poorly written. Also, you edited the question while I was answering. 🙂

Источник

How to perform a mysql query after reading session values

I am using this script to read a value in a session, then I want to query the database about this value :

  while ($row = mysql_fetch_assoc($result)) < $email = $row['email'] . "\n"; echo "Your e-mail adress is : $email \n" ; >?> 

I get this when I test the page with my browser: Your user_id is: 1430 Invalid query: Access denied for user ‘nobody’@’localhost’ (using password: NO) Whole query: SELECT * FROM customers WHERE Thanks a lot!

5 Answers 5

Connect to your database server first and select a database using mysql_connect and mysql_select_db . The mysql_query function will try to open a connection with default parameters, or as the manual puts it:

If no such link is found, it will try to create one as if mysql_connect() was called with no arguments.

Hence, PHP is trying to connect to localhost with username «nobody» and no password.

mysql_connect('localhost', 'mysql_user', 'mysql_password'); mysql_select_db('my_database'); 

The username nobody needs a password to use the database. The error clearly states this. The user nobody for the server localhost has its access denied when using no password

Access denied for user ‘nobody’@’localhost’ (using password: NO)

OR, although this is unlike, the machine you are running your code from does not have access to the machine that it running the database.

I’m fairly sure your id is an INTEGER, so the following should work:

$query = sprintf("SELECT * FROM `customers` WHERE ", $user_id); 

There also seems to be a problem with authenticating against the database. Have you successfully connected to the database using mysql_connect()?

Источник

retrieve data from database using session

Hi I had read topics here and tried doing it in different ways but my problem still not solved. I tried storing session and use it to retrieve data again from the database. I used the session idmember and set it to a variable then used it to a query to echo his/her first and last name. I can get to the main page but the user’s name doesn’t echo it. To summarize here how it works. index > authenticate(validate) > student/index.php functions.php

  
Announcement:
USER LOGIN

Username: function blank(a) < if(a.value == a.defaultValue) a.value = ""; >function unblank(a)
Password: function blank(a) < if(a.value == a.defaultValue) a.value = ""; >function unblank(a)
 1) < //Already has some IP address records in the database //Get the total failed login attempts associated with this IP address if ($rowx['1'] >3) < header("Location: index.php"); >> //If none then insert it to the table else if ($ipcount == 0) < $loginattempts = 0; mysql_query("INSERT INTO tbl_sec_login (ip_address,login_attempts,username) VALUES ('$iptocheck','$loginattempts','$user')"); >//Second step of validation //if count is equal to 1 then proceed to next condition if($count==1)< //Third Step of Validation // If result matched $user and $crypt_pass, table row must be 1 row if ($user==$result2[0] AND $crypt_pass==$result2[1])< $_SESSION['idmember'] = $_POST['id']; $loginattempts = 0; mysql_query("DELETE FROM tbl_sec_login WHERE ip_address = '$iptocheck' AND username='$user'"); if($result2[2]==3) < header("Location: student/index.php?id=$user"); >elseif ($result2[2]==2) < header("Location: epersonnel/index.php"); >elseif ($result2[2]==1) < header("Location: admin/index.php"); >>else < $loginattempts = $rowx['1'] + 1; mysql_query("UPDATE tbl_sec_login SET login_attempts = '$loginattempts' WHERE ip_address = '$iptocheck' AND username='$user'"); header("Location: login.php"); >> else < $loginattempts = $rowx['1'] + 1; mysql_query("UPDATE tbl_sec_login SET login_attempts = '$loginattempts' WHERE ip_address = '$iptocheck' AND username='$user'"); header("Location: login.php"); >> else < header("Location: index.php"); >?> 
require 'include/conn.php'; $id = $_SESSION['idmember']; $query="SELECT first_name,last_name FROM tbl_studentmasterlist WHERE sid ='$id'"; $result=mysql_query($query); $row = mysql_fetch_array($result); include "header.php"; ?>
Welcome,
Students Portal
»
  • Home
  • Account Setting
  • Enrollment Guide
  • Enroll
  • Logout

Источник

Использование MySQL для хранения данных сессий

Для высоко нагруженных проектов использование файлов для хранения файлов сессий становится недопустимым.

В этой статье мы рассмотрим использвоание БД MySql для хранения данных сессий.


    все настройки сессий производятся до старта сессии, поэтому необходимо отменить автостарт сессий:

ini_set('session.auto_start', '0');
ini_set('session.save_handler', 'user');
  • files — значение по умолчанию, PHP использует стандартные функции обработки сессий, сессии храняться в файлах, необходимо определить ini_set(‘session.save_path’, путь); место для хранения файлов сессий.;
  • mm — PHP использует стандартные функции обработки сессий, сессии храняться в памяти;
  • user — позволяет переопределять стандартные функции обработки сессий, и соответственно в этих функциях указывать, где мы будем хранить сессии и как мы будем их обрабатывать.
session_set_save_handler ( "sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
  • sess_open — открывает сессию. Функция создает уникальное ID сессии. Требует для своей работы два параметра ‘session.save_path’ и ‘session.name’. Т.к. мы храним сессии в базе, то ‘session.save_path’ нам не нужен, а вот ‘session.name’ можно определить вместо стандартного — ‘PHPSESSID’. Итак дописываем в конфигурацию:
ini_set('session.gc_maxlifetime', XXX); ini_set('session.cookie_lifetime', YYY);

‘sess_gc’ не всегда вызывается при инициализации сессии, есть еще одна настройка которая управляет этим параметром — ‘session.gc_probability’. Этот параметр определяет вероятность запуска ‘sess_gc’ в процентах, соответственно валидные значения 1-100. Значение по умолчанию 1%. Т.е. это означает, что с вероятностью в 1%, при открытии новой странице сайта, будет происходить очистка сессионной таблицы, по моему опыту оптимально значение 5-10. Добавляем к конфигурации:

ini_set ('session.gc_probability', 5);
CREATE TABLE "session" ( session_id character varying(32) NOT NULL, session_user_id integer DEFAULT 0 NOT NULL, session_counter integer DEFAULT 0 NOT NULL, session_ip character varying(16), session_agent character varying(255), session_last integer DEFAULT 0 NOT NULL, session_created integer DEFAULT 0 NOT NULL, session_data text );
CREATE TABLE "user" ( user_id character varying(32) NOT NULL, user_ip character varying(16), user_agent character varying(255), /* могут быть и другие поля */ );

session.php — Хранение данных сессии в MySQL таблице и функции работы с сессиями на PHP.

Используется глобальный массив $user[] с полями из таблиц БД session, user.
Подразумевается что соединение с MySQL уже установлено и определено в глобальной переменной $db.
Текущая информация сохраняется в глобальной переменной $session.

 function sess_close () function sess_read ($session_id) < global $db, $user, $session; if (strlen ($session_id) != 32) < error_log ("sess_read(): Invalid SessionID = ".$session_id); return ''; >$sql = "SELECT `session_id`, `session_user_id`, `session_counter`, `session_ip`, `session_agent`, `session_data` FROM `session` WHERE `session_id` = '".$db->sql_escape($session_id)."' AND `session_last` > '".(time() - live_sess_time)."'"; $result = $db->sql_query ($sql); if ($db->sql_numrows ($result) == 1) < $session = $db->sql_fetchrow ($result); if ($session AND $session['session_ip'] == $user['user_ip'] AND $session['session_agent'] == $user['user_agent']) < // выборка информации о пользователе. TODO замените при необходимости на свою . $sql = "SELECT * FROM `user` WHERE `user_id` = '".$db->sql_escape($session['session_user_id'])."' LIMIT 1"; $result = $db->sql_query ($sql); if(!$result) < $result = $db->sql_error ($result); error_log ('sess_read(): Failed to read user info - '.$result['message']); return ''; > else < $user_data = $db->sql_fetchrow ($result); $user = array_merge ($user, $user_data, $session); // слить три массива в один unset($user['session_data']); return $session['session_data']; > > else < if (isset($_REQUEST[session_name()])) sess_destroy($_REQUEST[session_name()]); return ''; >> elseif (!$result) < $result = $db->sql_error ($result); error_log ('sess_read(): Failed to read sessions - '.$result['message']); return ''; > else < $session = NULL; if (isset($_REQUEST[session_name()])) sess_destroy($_REQUEST[session_name()]); return ''; >> function sess_write ($session_id, $session_data) < global $db, $user, $session; if (strlen ($session_id) != 32) < error_log ('sess_write(): Invalid Session return false; >if (4294967295 < strlen($session_data)) < error_log ('sess_write(): Session data too large. '.$session_id.'(max. 4294967295) ->'.strlen($session_data)); if (isset($_REQUEST[session_name()])) sess_destroy($_REQUEST[session_name()]); return false; > if ($session AND $session['session_ip'] != $user['user_ip']) < if (isset($_REQUEST[session_name()])) sess_destroy($_REQUEST[session_name()]); return false; >if ($session) < $sql = "UPDATE `session` SET `session_user_id` = '".intval ($session['session_user_id'])."', `session_last` = '".time ()."', `session_counter` = '".intval(++$session['session_counter'])."', `session_data` = '".$db->sql_escape($session_data)."' WHERE `session_id` = '".$db->sql_escape($session_id)."' LIMIT 1"; > else < $sql = "INSERT INTO `session` (`session_id`, `session_created`, `session_last`, `session_ip`, `session_agent`, `session_data`) VALUES ('".$db->sql_escape ($session_id)."', ".time().", ".time().", '".$db->sql_escape ($user['user_ip'])."', '".$db->sql_escape ($user['user_agent'])."', '".$db->sql_escape ($session_data)."')"; > $result = $db->sql_query ($sql); if (!$result) < $result = $db->sql_error ($result); error_log ('sess_write(): Failed to INSERT/UPDATE session. '.$result['message']." 
Query: ".$sql); return false; > return true; > function sess_destroy ($session_id) < global $db; $sql = "DELETE FROM `session` WHERE `session_id` = '".$db->sql_escape ($session_id)."'"; $result = $db->sql_query ($sql); if (!$result) < $result = $db->sql_error ($result); error_log ('sess_destory(): Failed to DELETE session. '.$result['message']); return false; > return true; > function sess_gc ($sess_gc_maxlifetime) < global $db; $sql = "DELETE FROM `session` WHERE `session_last` < '".(time () - $sess_gc_maxlifetime)."'"; $result = $db->sql_query ($sql); if (!$result) < $result = $db->sql_error ($result); error_log ('sess_gc(): Failed to DELETE old sessions.'.$result['message']); return false; > $sql = "OPTIMIZE TABLE `session` "; $result = $db->sql_query ($sql); if (!$result) < $result = $db->sql_error ($result); error_log ('sess_gc(): Failed to OPTIMIZE sessionstable.'.$result['message']); return false; > return true; > session_set_save_handler ("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc"); // Можно активировать при проблемах register_shutdown_function ('session_write_close'); session_start (); ?>

При этом в базе остаются записи только о тех сессиях, которые сейчас активны, просроченные сессии удаляются, изменяя значение ‘session.gc_probability’ вы можете подобрать тот балланс который подходит Вашему сайту. Таким образом регулировать размер таблицы сессий.

Источник

Оцените статью