Seeking advice on Simple profile system - php

I want to create simple profile system. I want to display data of user from the database on the profile page. I dont want to make setting page. I just simply want to display it.
There are three columns in db right now, Id,username and password. I am adding first name,lastname, about me and about me to database.
I want to improve on my current php page and dont want to create new page. Please give me advice on how can i create simple profile system?
Here is my code of index.php
<?php
session_start();
if(isset($_SESSION['user'])){
header("location: profile.php");
echo "Welcome ".$_SESSION['user']." !";
}
else{
display_form();
}
function display_form(){
?>
<form action="verify.php" method="POST">
Name:<input name = "username" type = "text" />
Pass:<input name = "password" type = "text" />
<input name = "submit" type="submit" />
</form>
<?php
}
?>
My code of profile.php
<?php
session_start();
if (isset($_SESSION['user'])){
$loggeduser = $_SESSION['user'];
echo "Welcome ".$loggeduser." !";
?>
Log out now!
<?php
//Start displaying profile
}
else
header("location: index.php");
?>
Code of verification page
<?php
session_start();
//Make sql connection and select databases
$database_connect = mysql_connect('localhost','root','');
if(!$database_connect){
die('Could not connect to databse');
}
else{
echo "Connected to database successfully!<br/>";
}
$db_table_connect = mysql_select_db('selftest');
if(!$db_table_connect){
echo "Connection to table failed";
}
else{
echo "Connected successfully to table!<br/><br/>";
}
//Begin with user verifications
if(isset($_POST['submit'])){
$username = $_POST['username'];
$userpass = $_POST['password'];
$sql = "SELECT * FROM users WHERE username = '$username' and password = '$userpass'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1){
echo "Successfully logged in!";
$_SESSION['user'] = $username;
header("refresh:5;url=profile.php");
}
else{
echo "Failed to log in!";
header("refresh:5;url=index.php");
}
}

Such questions are not acceptable in SO Read This.
But i'll try to help.
1) Never trust user input, always sanitize it. you are inputting login information directly in query. Thats a SQL injection right there. Read prevent SQL injection
2) mysql API is deprecated, means its production will stop soon. make habit of using new API which is mysqli. there is not much difference 90% same. Or PDO which is kind of same thing as mysqli.
3) Try to make use of classes for database interaction. That way you can easily get query information and show within same page.
For now, you can put the information the result variable of select query in session, do following:
//Code of verification page
if($count == 1){
echo "Successfully logged in!";
$_SESSION['user'] = $username;
$_SESSION['user_info'] = mysql_fetch_array($result);
header("refresh:5;url=profile.php");
}
//Start displaying profile
echo $_SESSION['user_info'][name];
echo $_SESSION['user_info'][aboutme];

Related

Unable to protect pages/area with password

I'm trying to create a password protected area of a website.
I'd like to allow access by checking username and password from a MySql table, then start a session and allow access to a number of pages while the session is active. If someone tries to directly access one of these pages directly, I'd like to redirect them to login page.
My code for the login page is:
if (isset($_POST['submit']))
{
include("config.php");
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
$passwordc=md5($password);
$query = "SELECT username FROM admin WHERE username='$username' AND password='$passwordc'";
$result2 = $conn->query($query);
if ($result2->num_rows != 0) {
$_SESSION["username"] = $user;
echo "<script language='javascript' type='text/javascript'> location.href='admin_view.php' </script>";
}else{
echo "<script type='text/javascript'>alert('User Name Or Password Invalid!')</script>";
}
}
It seems to work (correctly redirects if username and password matches, shows alert if not).
What I fail to do, is actually protect my pages from display if session is not active.
session_start();
if (!$_SESSION["username"]) {
header("Location: login.php");
}
I'm not a programmer or fully-educated web developer. I know HTML and CSS, and I'm barely able to use ready-to-use php and js scripts following readme files.
Any help would be greatly appreciated.
modify your login code as
if (isset($_POST['submit']))
{
include("config.php");
$username= $crud->escape_string($_POST['username']);
$password= $crud->escape_string($_POST['password']);
$passwordc=md5($password);
$query = "SELECT username FROM admin WHERE username='$username' AND
password='$passwordc'";
$result2 = $conn->query($query);
if ($result2->num_rows != 0) {
session_start();
$_SESSION["username"] = $user;
header("Location:admin_view.php");
}else{
$Message = urlencode("user name password invalid!");
header("Location:login.php?Message=".$Message);
}
}
if your values successfully stored in session then you can use like
session_start();
if(!isset($_SESSION['username']))
{
header("Location: login.php");
}
on everypage top
you must store name from query into session

Php login code, data does not match

Here is my code that I made when I tried to make a login page to my site. I get wrong details everytime I try to login, I have checked the details several times so that they match, I do get a clear dbconnection so there is not a problem with that either. I do not have an md5 encryption so that I have thought of too... I use LONGTEXT as datatype in my mysql database for storage of name and password. I got 3 rows of information in the table users of the database. ID, Name, password, named exactly as I have written.
I hope this was enough information to get some help?
Thanks in advance!
<?php
session_start();
include_once 'dbconnect.php';
if(isset($_SESSION['user'])!=""){
header("Location: index.php");
}
if(isset($_POST['login'])){
$email = mysql_real_escape_string($_POST['email']);
$upass = mysql_real_escape_string($_POST['pass']);
$res = mysql_query("SELECT * FROM users WHERE Name='$email'");
$row = mysql_fetch_array($res);
if($row['password']==$upass){
$_SESSION['user'] = $row['user_id'];
header("Location: index.php");
} else {
?>
<script>alert('wrong details');</script>
<?php
}
}
?>
You don't need to do this because will not pass this to the query anyway.
$upass = mysql_real_escape_string($_POST['pass']);
The value of the password is not equal to the value of the escaped password. So this will not be accurate.
if($row['password']==$upass){}
You could just do something like
if($row['password']==$_POST['pass']){}
I would suggest following fixes to your script..
1) Make sure that the name should be unique in your db table..
e.g. if some one has already registered with name as "admin" then do not allow any other person use that as username( or name in your case) to use.
2) Check name and password both in the query it self.
See the below modified code..
<?php
session_start();
include_once 'dbconnect.php';
if(isset($_SESSION['user'])!="")
{
header("Location: index.php");
}
if(isset($_POST['login']))
{
$email = mysql_real_escape_string($_POST['email']);
$upass = mysql_real_escape_string($_POST['pass']);
$res = mysql_query("SELECT * FROM users WHERE Name='$email' AND password = '$upass' ");
if($res) // check if there is any error in the query
{
if(mysql_num_rows($res) == 1) // check for the number of Name - password pair
{
$row = mysql_fetch_array($res);
$_SESSION['user'] = $row['user_id'];
header("Location: index.php");
}
else
{
?>
<script>alert('wrong details');</script>
<?php
}
}
else
{
echo "Error while log in: ".mysql_error();
}
}
?>
Note:
1) Stop using mysql_. They are deprecated Use mysqli_ or PDO
2) Make sure that you have used proper columns names in PHP code, similar to those in the db table.

How to get user data after login in php with session

I am new at this php and session and trying to learn it.
I created a login system in php. I create a registration form so different users can register. Now when they login I want to show the user data of who logs in at that time.
I am learning sessions in php so I don't know how to carry a logged in user data in to logged in area.
Simply I don't know how to get login user data through sessions in php.
THIS IS LOGIN.PHP:
<?php
error_reporting(0);
$con = mysql_connect('localhost','root','') or die('could not connect to database');
mysql_select_db('addscloud');
#session_start();
if(isset($_POST['submit']))
{
$query = "SELECT * FROM tbl_reg where reg_mobile = '".$_POST['reg_mobile']."' and reg_pass = '".$_POST['reg_pass']."' ";
var_dump($query);
$result=mysql_query($query);
$row=mysql_fetch_array($result);
if($row)
{
$_SESSION['var']=2;
header('Location:registration_user.php');
}
else
{
$_SESSION['msg']="invalid user Name or Password";
header('Location:login_form.php');
}
}
?>
<?php
if(isset($_SESSION['msg']))
{
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
?>
AND THE LOG AFTER SUCCESSFUL LOGIN:
<?php
#session_start();
if (isset($_SESSION['var']))
{
}
else
{
header('location:login_form.php');
}
?>
<?php
if(isset($_SESSION['msg'])){
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
?>
On successful validation of the user, put all the necessary user details into a session.
For example at login.php,
$_SESSION['user'] = $row;
so you can get the necessary user details anywhere at site.
Hope this helps to you.. ;)

MySQLi / PHP: Not redirecting to error page?

So what I'm trying to do here is have my users login in.
This is the script I am using to do that.
I have just used an converter found here: https://wikis.oracle.com/display/mysql/Converting+to+MySQLi to convert my Mysql to mysqli because I am a beginner and had no idea how to do that.
Now when the users puts in an correct password and username.
It goed exactly how I want it and the user gets redirected to 'dashboard.php'
However, when user enters incorrect data, the users ends up on a black 'login.php' (which is the code I am showing here) instead of 'loginerror.php' which is what I want.
I hope some people here can help me out because I am pretty lost.
PS: Yes I know the passwords are in plain text right now but don't worry about that because I will fix that later.
<?php
session_start();
if(!$_SERVER['REQUEST_METHOD'] == 'POST') {
echo "Please leave.<br /><br />";
echo "<a href='index'>Click to go back</a>";
exit();
}
if(($GLOBALS["___mysqli_ston"] = mysqli_connect('localhost', 'root', ''))) {
if(((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE users"))) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$zoekresultaat = mysqli_query($GLOBALS["___mysqli_ston"], $query);
if($zoekresultaat = mysqli_affected_rows($GLOBALS["___mysqli_ston"]) > 0) {
$record = mysqli_fetch_assoc($zoekresultaat);
$zoekresultaat = mysqli_query($GLOBALS["___mysqli_ston"], $query);
if($zoekresultaat = mysqli_affected_rows($GLOBALS["___mysqli_ston"]) > 0) {
$record = mysqli_fetch_assoc($zoekresultaat);
$_SESSION['login'] = true;
$_SESSION['username'] = $record['username'];
header('location: dashboard.php');
} else {
header('location: loginerror.php');
}
exit();
} else {
echo "<br /><br />Could not find Database";
}
} else {
echo "<br /><br />Could not connect to Database";
}
}
?>
You cannot redirect using the header method after anything has been outputted. In this case, you use Echo before your header redirection, so it will not work.
See this thread for reference : How to fix "Headers already sent" error in PHP
What you should do define redirection before outputting anything in your application, if it seems difficult, your application might need to be restructured.
Here are some alternatives if you don't want to do that, but they are bad practice :
HTML
<meta http-equiv="Location" content="http://example.com/">
Javascript
<script> location.replace("target.html"); </script>
Also as usual, defend yourself against MySQL injections : How can I prevent SQL injection in PHP?.

User login using PHP

I haven't been able to trace what's wrong with this code. I am trying to login the user by taking his username and password. Here is what I am trying to do.
index.php:
This file checks if the username cookie is set and displays the file accordingly. This file submits the username and password to a file called validate.php.
validate.php:
<?php
session_start();
include("connector.php");
$var=connect();
if($var==10)
{
$valid=false;
$row= mysql_query('select * from users where username="'.$_POST["username"].'"');
if($row['password']==$_POST["password"])
$valid=true;
if($valid)
{
$_SESSION["username"]=$_POST["username"];
$_SESSION["userid"]=$row['userid'];
echo "<script>document.location.href='./session_creator.php'</script>";
}
else
{
echo "invalid";
}
}
?>
connector.php==>
<?php
$connection=0;
function connect()
{
$dbc = mysql_connect('localhost:3306','root','root');
if (!$dbc)
{
die ('Not connected:'. mysql_error());
return -10;
}
else
{
$connection = mysql_select_db("citizennet",$dbc);
if(!$connection)
{
die("Not connected: ". mysql_error());
return -20;
}
}
return 10;
}
?>
session_creator.php:
<?php
session_start();
setcookie("username",$_SESSION['username'],time()+3600);
setcookie("userid",$_SESSION['userid'],time()+3600);
echo "<script>document.location.href='./index.php'</script>";
?>
the redirected index.php file reports that the cookie is not set. I am newbie, please correct me if the process I am following is wrong.
I am adding index.php that verifies if the user is logged in:
<?php
if(!isset($_COOKIE["username"]))
echo '<a id="login_button">login</a> <div id="login_box_pane"><form action=validate.php method="post">Username: <input type="text"/> Password:<input type="password"/><input type="submit"/></form></div>';
else
echo "<a>".$_COOKIE["username"]."</a>";
?>
When you set your cookie on your page it should be like this:
<?php //login page
session_start()
$username = $_POST['username'];
$password = $_POST['password'];
/*
Check authentication with database values
*/
//if login successful set whatever session vars you want and create cookie
$_SESSION['username'] = $username;
setcookie($username, $password, time()+3600);
?>
Prior to this you will have check the users credentials and log them in or deny them. Once logged in you set the session variables. Then to create the cookie you use the code above.
$user = mysql_real_escape_string($_POST['user']);
$pass = mysql_real_escape_string($_POST['pass']);
$sql = "SELECT * FROM users WHERE username='$user' AND password='$pass'";
$result = mysql_query($sql);
That will take care of your sql injection vulnerabilities and also get you the correct account only if both the username and password are correct
Now you can use your conditions to set the cookies and sessions

Categories