Pulling data from log in? - php

ok, i have a php and mysql script that allows you to log in if you have a username / password
once entered correctly it forwards you to the members page. here i would like it to load the persons full name of who as loged in, like it does on this site top right.
here is the code to the members area
<?php
$host="localhost"; // Host name
$username="stephen2_phptest"; // Mysql username
$password="********"; // Mysql password
$db_name="stephen2_phptest"; // Database name
$tbl_name="registers"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
session_start();
if(!session_is_registered(myusername)){
header("location:index.php");
$myusername=$_POST['myusername'];
}
?>
<html>
<link rel="stylesheet" type="text/css" href="../php/css/styles.css">
<body>
<div class="members-screen">
Login Successful</br>
Welcome [persons name to load here]<?php echo $_POST['myusername'] ?> | Logout
<div class="menu">
<div class="menu-btn">
Home
</div>
<div class="menu-btn">
Search
</div>
<div class="menu-btn">
Messages
</div>
<div class="menu-btn">
Matches
</div>
<div class="menu-btn">
My Account
</div>
</div>
</div>
</body>
</html>`
any ideas?

1) You don't need db connection on members page.
2) Try this on your login.php page(with the changes as per your need i.e: here i used "users" as the name of the table.)
3) Add <?php session_start(); ?> at the top of login.php page and every other page where you need username to be echoed.
4) Here in my example code,$_SESSION['username'] is what you need to be able echo username at the right side of the page. And since you may need to use it on other pages too using $_SESSION variable would be a better idea than using $_POST var.
$sql = "select *,myusername from users where myusername = '$myusername' and mypassword = '$mypassword'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if($row)
{
$_SESSION['username'] = $row['myusername'];
$_SESSION['password'] = $row['mypassword'];
}
and echo $_SESSION['username'] where you need it.
His name will be displayed as long as he has not logged out,and also destroy session on logout.php.

Assign your login information that you plan on outputting to a Session variable array.

Related

How to create a membership site

I have a website, mostly composed with public links, that is anyone can see them.
But I was thinking in creating some pages that could only be accessed by people who were registered on my website.
I looked around and found out that for that I would need a CMS, so I went to my host's CPanel to get one (DRUPAL) but instead of using what I already had, it simply created a new site.
By searching around people only want to know "how to integrate paypal with a membership site"...
Mine is supposed to be free; people join but don't need to pay for anything (at least for now) but some links can't be displayed to non-members.
I managed to get everything setup but I get an error...:
Warning: mysql_connect(): Access denied for user 'MYDATABASE_NAME'#'XXX.XX.XX.XX' (using password: YES) in /home/USERNAME/public_html/config.php on line 10
cannot connect to server
What's this? I have a few lines of code on the config.php
<?php
$host="www.triplestrata.com"; // Host name - my website
$username="MYDATABASE_USERNAME"; // Mysql username
$password="MYSQLPASSWORD"; // Mysql password
$db_name="MEMBER"; // Database name - I called my database MEMBER without the prefix
//Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");
?>
This is right, Ya?
Use session variables.
With them, you can limit the entry to the page only when the session is occurring.
Make a login page, and then allow session start on all your pages, so the login follows.
Then, on the page you require, just add a clause that determines that only with the session started as a member, can one enter the page. If not, exit to mainpage or something.
Example:
<?php
Session_start();
if (!isset($_SESSION["lojamusica"]))
header("Location:errorlogin.php");
if ($_SESSION["lojamusica"]!="OK")
header("Location:errorlogin.php");
?>
In here, i am only allowing people with the session started, and connected to the database to enter my webpage, just need to pu this on top of the pages.
This is my loggin example, which came from a form on a previous page:
<?php
Session_start();
Session_destroy();
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("lojamusica");
$query = "SELECT username, password FROM login WHERE username='".$_POST["user"]."'";
$results = mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($results);
if ($num == 0)
echo "Username not found!";
else {
$row = mysql_fetch_array($results);
if ($row["password"] == $_POST["pass"])
{
Session_start();
$_SESSION["username"] = $_POST["user"];
$_SESSION["lojamusica"] = "OK";
header("Location:mainpage.html");
}
else
header("Location:login2.html");
}
?>
This is the login page, simplified:
<form action="login.php" method="POST">
<label>Username:</label>
<input type="text" name="user" />
<label>Password:</label>
<input type="password" name="pass" /><br>
<input type="submit" value="Submit" />
<input type="reset" value="Reset">
>
</h1></form>
To logout, simply reditect to a page like so:
<?php
Session_start();
Session_destroy();
echo "<script language='javascript'> window.top.location.href = 'login2.html'; </script>";
?>

Check the login status and save the login sessions(PHP)

I am working on a log-in system, Whenever the user tries to access the non-authorized page
then he should return on the login page to login, how can I perform it
Below is my log-in script
<?php
session_start();
$host="localhost"; // Host name
$db_username="root"; // Mysql username
$db_password=""; // Mysql password
$db_name="designshop"; // Database name
$tbl_name="member"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$db_username", "$db_password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$member_username=$_POST['member_username'];
$password=$_POST['password'];
// To protect MySQL injection (more detail about MySQL injection)
$member_username = stripslashes($member_username);
$password = stripslashes($password);
$member_username = mysql_real_escape_string($member_username);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM $tbl_name WHERE member_username='$member_username' and password='$password'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
$_SESSION['member_username']=$_POST['member_username'];
$_SESSION['password']=$_POST['password'];
header("location:login_success.php");
}
else {
header("location:try_again.html");
}
?>
All you have to do is to check for the existence (and non-emptiness) of $_SESSION['member_username']. If it is set, that means that your user is logged in, and therefore, there is no need for him to relog.
Notes:
There is no need to store the user's password in session: in fact, its better not to.
You do your authentication through MySQL, which means that you store the password in cleartext: this is a bad practice. It would be better to retrieve both username and password from the database based only on the username, and do the comparaison in your PHP code: this would allow you, for example, to store sha1'd password.
Just put this at the top underneath session_start()...
if(!empty($_SESSION['member_username'])){header("location: login_success.php");}
Like so...
session_start();
if(!empty($_SESSION['member_username'])){
header("location: login_success.php");}
$host="localhost"; // Host name
$db_username="root"; // Mysql username
$db_password=""; // Mysql password
//REST OF CODE
start code with session_start() and check if the session is set whenever any user trying to access the page, if session is set then redirect to the page otherwise redirect to login page
you can check using isset()
follow this code...
<?php session_start();
include('conn.php');
$Name = $_POST['login_id'];
$Pass = $_POST['password'];
$select="select * from admin_login where admin_name='$Name' AND admin_pwd='$Pass'";
$query=mysql_query($select) or die($select);
$rows=mysql_fetch_array($query);
$row=mysql_num_rows($query);
if($row != 0)
{
$_SESSION['admin_name']=$rows['admin_name'];
echo "<script>window.location.href='index.php'</script>";
}else
{
$message = 'Invalid Username Or Password';
echo '<script type="text/javascript">alert("'.$message.'")</script>';
echo "<script>window.location.href='login.php'</script>";
}
?>
put this code to the top of the every page
<?php session_start();
if(isset($_SESSION["admin_name"])=='') print('<script>window.location.href="login.php"</script>');

use index.php code in other php files

I'm trying to create simple login/registration page.
I'm using index.php which includes login.php in it.
I want to report the login errors in a specific position, using an answer to a preious question.
The problem is that if I encounter an error, the url changes to the login.php file and on next login I get error of "Cannot find page".
I want to eventually be able somehow display errors and be able to get another input and handle it.
login.php:
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="kupon"; // Database name
$tbl_name="users"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$email=$_POST['email'];
$password=$_POST['password'];
// To protect MySQL injection
$email = stripslashes($email);
$password = stripslashes($password);
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM $tbl_name WHERE email='$email' and password='$password'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $email and $password, table row must be 1 row
if($count==1){
// Register $email, $password
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
header("location: members.php");
}
else {
$error = '<p class="error">User does not exist</p>'
include('../index.php');
exit;
}
?>
index.php form:
<form action="php/login.php" method="post" class="form">
<p class="email">
<input type="text" name="email" /> :דואר אלקטרוני</br>
</p>
<p class="password">
<input type="password" name="password" /> :סיסמא</br>
</p>
<p class="submit">
<input type="submit" value="היכנס" />
</p>
</form>
<?php
if(isset($error)) echo $error;
?>
You shouldn't put passwords or other Personal Identification Information into the session. Better to have your login code assign a session ID with an identification that links it to the user in your database. (Like a column filled with unique values called userid)
You need to make sure you are initializing the session in the login.php and any page that you want to have require they be authenticated. This allows you to have the page check the session to confirm that the user is actually logged in.
To resolve the 404 error (Page Not Found), you need to fix this: header("location: members.php");. That needs to be the full path of the file. Since your login.php file is under the directory of php and members.php is not, when you get directed to login.php, this location forward tries to load members.php in the php directory and since it is not there, it gives a 404 error.
You are including the login.php, but the actual page is index.php - so you should post your form to index.php instead.
It looks like you have a problem using relative urls.
You start on index.php, which redirects on form submission to php/login.php.
Next time, you submit to php/php/login.php instead.
If you're in the document root, try using /index.php and /php/login.php instead. I can't be more specific without knowing more about your project's layout however.

How to edit the user information by admin

I am developing my first simple website using PHP. Now, I am working in the admin page and I want to let him adding, deleting users and editing the personal information of the existed users. I did the adding and deleting. Now, I want to develop editing users. First of all, I want him to choose the user from drop list, then fetch the user information automatically after choosing him from the drop list, and after that editing his information. So how can I do that?
My code:
<?php
ob_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="13524"; // Mysql password
$db_name="sharingi_db"; // Database name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script language="javascript">
function reload(form){
var val=form.username.options[form.username.options.selectedIndex].value;
self.location='editUser2.php?username=' + val ;
}
</script>
</head>
<body>
<div id="content_main" class="admin_student_height">
<!-- Here starts the first form -->
<form method="get">
<h3>Choose A User</h3> <br />
select name="username" onchange="reload(this.form)">
<option>
<?php
if(isset($_GET['username']))
echo "{$_GET['username']}";
else echo "Select one";
?>
</option>
<?php
if(isset($_GET['username'])){
$exceptcc = $_GET['username'];
$sql = "SELECT username FROM user WHERE user.username NOT IN
('$exceptcc')";
}
else
$sql = "SELECT username FROM user";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
echo "<option value={$row['username']}>{$row['username']}</option>";
}
?>
</select><br /><br />
<h3>User Information</h3> <br />
<?php
$thecc = $_GET['username'];
$sql = "SELECT Firstname FROM user WHERE Username=$thecc";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
echo "{$row['Firstname']}>{$row['Firstname']}}";
}
?>
<br /><br />
</form> <br />
</div>
</div>
</body>
I've been working on making a web-based ticketing system and ran into this same situation.
I solved the problem like this:
When the page is loaded, determine if they have admin rights or throw them off the page.
Do an SQL Query to get the List of users, to either display in a list or in a drop down box.
Once the User to edit has been selected, Do another Query and load each item into a field;
what I did was use the same form for adding new users but have php build the form and insert the current values for that user into the fields.
When this form is submitted, (and submitter verifed) I have the php script look at the submitted username and use that for the where clause in the sql update statement
If you want me to post up an example of what I did I can do that.
You are only echo'ing the user's information.
Instead, you need to put the information into a form, which will allow for editing.
<?php
if ($_POST['submit']) {
$username = $_POST['username'];
//if you want to update
mysql_query("UPDATE users SET username = '$username', password = '$password'");
//if you want to delete
mysql_query("DELETE FROM users WHERE username = '$username'");
}
?>
<?
//show all users
$user_query = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($user_query)) {
echo $row['username'] . ' ' . $row['first_name'] . ' ' . $row['last_name'];
//and so on.. depending on your table fields
}
?>
<form method="POST">
Username: <input name="name" value="<?echo $row['username'?>"/>
<input type="submit" name="submit"/>
</form>
Load data into your form, and add action to it like "save_user.php
On that page save_user.php get data from $_POST, $_POST["firstName"] where firstName is name of your text field where you have loaded data from db
write query "update tbl_users set FirstName='$firstName', Email='$email" and execute this query, because you are starter this can be enough but remember query written like this can be used for SQL Injection that means you can write SQL query into text field "firstname" and do some stuff, like delete all data or gain passwords, emails etc.
When you get this then use parameters in your MySQL query in order to avoid SQL Injection. But you will manage it.
if you want to fetch the user information automatically from the drop list (without clicking submit button), you need to use AJAX. Here is the link to a very good example on how to use ajax with php and mysql http://www.w3schools.com/php/php_ajax_database.asp

deny http access to the directory, but allow internal server access

First off I want to start off saying that I don't know anything about PHP so I would appreciate all the help I can get.
So I have a website hosted on godaddy where I upload files for my clients. With the help of a friend I made a simple login system with usernames and passwords. The problem is that although the websites can't be accessed without inputting the username and password, the files suchs as .jpg can be accessed by directly inputting the full link in the browser. I want it to be so that the only way the files are accessed through the user webpage. Also I want each user to be able to access only their own files and not the others. So here is my code and if there are any additional changes that need to be made to avoid hacking I will greatly appreciate the input.
index.php file code for the form that is being used to input username and password:
<form name="form1" method="post" action="checklogin.php">
<div class="lefts">
<p>Login:</p>
<p>Password:</p>
</div>
<div>
<input name="myusername" type="text" id="myusername" />
<input name="mypassword" type="password" id="mypassword" />
</div>
<div><input type="image" name="Submit" id="submit" value="Login" src="images/submitOff.png" /></div>
</form>
checklogin.php: (if correct username and password is entered, it goes to the username webpage. if not it goes to the wrong username or password webpage
<?php
ob_start();
session_start();
$host="hostname"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="dbnamey"; // Database name
$tbl_name="tablename"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT username FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
//returns false if no results returned
$row = mysql_fetch_row($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($row){
// Register $myusername, $mypassword and redirect to file
$_SESSION["myusername"] = $myusername;
$_SESSION["mypassword"] = $mypassword;
$myPage = $myusername.".php";
$_SESSION["myPage"] = $myPage;
header("location:".$myPage);
}
else {
header("location:index2.php");
}
ob_end_flush();
?>
username1.php: (webapge for user that contains files)
<?
session_start();
if(
//!session_is_registered(myusername)
!isset($_SESSION["myusername"]) ||
$_SESSION["myPage"] != basename($_SERVER['REQUEST_URI'])
){
header("location:index.php");
}
?>
<html>
//content that consist of links to the files
Png 1
</html>
The security of this script is very bad. You aren't hashing passwords. The header() allows you to add an element to the HTTP response header. THE SCRIPT STILL EXECUTES., you are not preventing access to anything. Furhter more, mysql_real_escape_string() does everything that addslashes() does and more. Doing both just tells people that you don't know what either of them does. You must start using parametrized quires with ADODB or the PDO libraries.
Use an .htaccess file to prevent accesss
Order deny, allow
Deny from all
Allow from localhost

Categories