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>";
?>
Related
I'm trying to make a simple auction website. I need to keep track of the user that adds items to the auction. I've figured out how to store the user's account id and I thought storing the username would be similar, but I am unable to work it out. No matter what I've tried, the username is never stored in my items table.
This is my additemprocess.php page.
<?php session_start(); ?>
<html>
<head></head>
<body>
<?php
require_once("dbconnect.inc");
$_SESSION['username']=$_POST['username'];
$item=$_POST['item'];
$description=$_POST['description'];
$accountid=$_SESSION['accountid'];
$sql= "INSERT INTO biditems (username, accountid, biditem, biddesc) VALUES
('{$_SESSION['username']}', '$accountid', '$item', '$description')";
$result=mysql_query($sql) or die("Error in adding item: " .mysql_error());
$mess="Item successfully added!";
echo $mess;
?>
And here is the page that should list the items, showing the username of the user that added the item.
<?php
session_start();
require_once("dbconnect.inc");
require_once("checkstatus.inc");
$sql=" select * from biditems";
$result=mysql_query($sql);
echo "Items for Auction";
while($row=mysql_fetch_array($result)) {
$itemid=$row['itemid'];
$item=$row['biditem'];
$auctionby=$row['username'];
$description=$row['biddesc'];
echo "<p>$itemid $item $auctionby $description</p>";
}
?>
Here is my code to add an item.
<?php
session_start();
require_once("dbconnect.inc");
?>
<form id="additem" name="additem" method="post" action="additemprocess.php">
Item<br>
<input type="text" name="item" id="item"/><br>
Description<br>
<textarea name="description" id="description"></textarea><br>
<input type="submit" name="submit" id="submit" value="submit"/>
</form>
You are currently using $_SESSION['username']=$_POST['username']; but you need to treat this username like the accountid. It should have been stored when you login in a session, then recalled when you enter the bid data in its database.
So for example:
On login :
$_SESSION['username']=$_POST['username'];
And on storing the bid:
$username = $_SESSION['username'];
or alternatively get the username from the users table using the accountid then add it to the query that way like:
$username = $row['username'];
Additionally, if you tried this but had trouble sharing this data between pages using sessions, then make sure you are including session_start(); on the top of each page where you are going to use sessions.
The problem is at: $_SESSION['username']=$_POST['username'];, you're setting a session to a post which doesn't even exist..? Set the $_SESSION['username']; in the process of logging in.
So on the spot where you are setting the $_SESSION['accountid'] equal to the ID of the currently logged in account using something like: $_SESSION['accountid'] = $row['id'];.
Right under there you'll add $_SESSION['username'] = $row['username'];.
Then just delete the $_SESSION['username'] = $_POST['username']; at your adding item process.
ANOTHER NOTICE: Do not use MySQL anymore since it's deprecated in versions of PHP5 or higher due safety reasons. Try using MySQLi (MySQL improved or PDO): php.net/manual/en/mysqlinfo.api.choosing.php
I have a homework which is creating a web page which user can share photos or texts in their profile. But I am stuck at using login information to do it.
Here is my login.html:
<form method="post" action="login.php">
<br><label for="username">Username:</label></br>
<input type="text" id="username" name="username">
<br><label for="password">Password:</label></br>
<input type="password" id="password" name="password">
<div id="lower">
<br><input type="submit" value="Login"></br>
<p>
Not yet registered?
Click here to register
</p>
</div><!--/ lower-->
</form>
and here is my login.php:
?php
$con=mysqli_connect("localhost","root","","webpage");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql=mysqli_query($con,"SELECT * FROM user WHERE username='$username' and password='$password'");
if (!mysqli_fetch_assoc($sql)) {
die("You entered wrong username/password.");}
while ($sql){
$sql2="SELECT * FROM user WHERE username='$username' and approval = 1";
$res = mysqli_query($con,$sql2);
if (!$res) {
echo "Your account isn't approved yet. Please wait for approval. Thanks :)";}
else echo 'You have succesfully logged in.';
header('Location: http://localhost/project2/redirect.html');
}
mysqli_close($conn);
?>
From here, I am stuck. I don't know what to do to use the username that the user has entered. What am I suppose to do?
Thanks.
You can set the username in session which can be used till the session is cleared..ie till the user logs out or close the browser
A session is a way to store information (in variables) to be used
across multiple pages.
Unlike a cookie, the information is not stored on the users computer.
By default, session variables last until the user closes the browser.
Thus, Session variables hold information about one single user, and are available to all pages in one application.
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
To Set Session variables
<?php
// Start the session
session_start();
$username = $_POST['username'];
// Set session variables
$_SESSION["uname"] =$username;
?>
To Get Session variable's value
<?php
session_start();
$username =$_SESSION["uname"];
?>
To Destroy the Session
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
Cookies! Yum!
http://www.w3schools.com/js/js_cookies.asp
Do some research here, try it out, and come back if you still can't get it.
I'm trying to make login system by a tutorial. I'm making everything like in tutorial but it says my details are incorrect and it wont log me in but everything is correct. I can't find is there anywhere mistake in code or something. Any help is welcome!
Index.php code:
<?php #admin/index.php
#####[make sure you put this code before any html output]#####
//connect to server
$dbc = mysqli_connect('localhost','root','pw') or
die('could not connect: '. mysqli_connect_error());
//select db
mysqli_select_db($dbc, 'dbname') or die('no db connection');
//check if the login form has been submitted
if(isset($_POST['go'])){
#####form submitted, check data...#####
//step 1a: sanitise and store data into vars (storing encrypted password)
$usr = mysqli_real_escape_string($dbc, htmlentities($_POST['u_name']));
$psw = SHA1($_POST['u_pass']) ; //using SHA1() to encrypt passwords
//step2: create query to check if username and password match
$q = "SELECT * FROM kasutaja WHERE name='$usr' AND pass='$psw' ";
//step3: run the query and store result
$res = mysqli_query($dbc, $q);
//make sure we have a positive result
if(mysqli_num_rows($res) == 1){
######### LOGGING IN ##########
//starting a session
session_start();
//creating a log SESSION VARIABLE that will persist through pages
$_SESSION['log'] = 'in';
//redirecting to restricted page
header('location:restricted.php');
} else {
//create an error message
$error = 'Wrong details. Please try again';
}
}//end isset go
?>
<!-- HTML FORM GOES HERE -->
<!-- LOGIN FORM in: admin/index.php -->
<form method="post" action="#">
<p><label for="u_name">username:</label></p>
<p><input type="text" name="u_name" value=""></p>
<p><label for="u_pass">password:</label></p>
<p><input type="password" name="u_pass" value=""></p>
<p><button type="submit" name="go">log me in</button></p>
</form>
<!-- A paragraph to display eventual errors -->
<p><strong><?php if(isset($error)){echo $error;} ?></strong></p>
Restricted page code:
<?php #admin/restricted.php
#####[make sure you put this code before any html output]#####
//starting the session
session_start();
//checking if a log SESSION VARIABLE has been set
if( !isset($_SESSION['log']) || ($_SESSION['log'] != 'in') ){
//if the user is not allowed, display a message and a link to go back to login page
echo "You are not allowed. back to login page";
//then abort the script
exit();
}
/**
* #### CODE FOR LOG OUT #### click here to see the logout tutorial
*/
?>
<!-- RESTRICTED PAGE HTML GOES HERE -->
<h1> TEST </h1>
Thanks for helping!
This is a fix for http://www.cramerz.com/php/php_login_system which contains errors that the OP downloaded from the Web. No wonder the OP had a hard time.
It queries the wrong columns for one thing and inserts into the wrong table.
Another error with their code is this line:
echo "You are not allowed. back to login page";
which would throw an error and should read as, and escaping the quotes for index.php
echo "You are not allowed. back to login page";
Rewrite
Most of the Websites have a sort of private section where normal users are not allowed. You can think about an ADMIN section where the webmaster finds his CMS, a private area with sensitive personal information or even just the email manager you use to handle your emails.
All of these cases have something in common: they restrict access to allowed users only, with a login system.
To create an authentication system you will need:
A database, a table called users with at least three columns: id, username, password
A HTML form where users fill in their usernames and passwords
A PHP script that will check if usernames and passwords provided actually exist
A private area users can access only if successfully logged in
STEP 1. create a table called users:
a) Use PhpMyAdmin or any other GUI to quickly create a table
CREATE TABLE `users` (
`id` INT( 5 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 50 ) NOT NULL ,
`password` VARCHAR( 50 ) NOT NULL
)
b) Insert a couple of users:
INSERT INTO `users`
( `id` , `username` , `password` )
VALUES ( NULL , 'john', SHA1('johnPsw' ) ),
( NULL , 'james', SHA1('jamesPsw') ),
( NULL , 'jim', SHA1('jimPsw' ) );
PLEASE NOTE: we are using the SHA1() function to encrypt passwords.
STEP 2. login form:
<!-- LOGIN FORM in: admin/index.php -->
<form method="post" action="">
<p><label for="u_name">username:</label></p>
<p><input type="text" name="u_name" value=""></p>
<p><label for="u_pass">password:</label></p>
<p><input type="password" name="u_pass" value=""></p>
<p><button type="submit" name="go">log me in</button></p>
</form>
<!-- A paragraph to display eventual errors -->
<p><strong><?php if(isset($error)){echo $error;} ?></strong></p>
STEP 3. php script:
<?php #admin/index.php
#####[make sure you put this code before any html output]#####
//connect to server
$dbc = mysqli_connect('localhost','root','') or
die('could not connect: '. mysqli_connect_error());
//select db
mysqli_select_db($dbc, 'examples') or die('no db connection');
//check if the login form has been submitted
if(isset($_POST['go'])){
#####form submitted, check data...#####
//step 1a: sanitise and store data into vars (storing encrypted password)
$usr = mysqli_real_escape_string($dbc, htmlentities($_POST['u_name']));
$psw = SHA1($_POST['u_pass']) ; //using SHA1() to encrypt passwords
//step2: create query to check if username and password match
$q = "SELECT * FROM users WHERE username='$usr' AND password='$psw' ";
//step3: run the query and store result
$res = mysqli_query($dbc, $q);
//make sure we have a positive result
if(mysqli_num_rows($res) == 1){
######### LOGGING IN ##########
//starting a session
session_start();
//creating a log SESSION VARIABLE that will persist through pages
$_SESSION['log'] = 'in';
//redirecting to restricted page
header('location:restricted.php');
} else {
//create an error message
$error = 'Wrong details. Please try again';
}
}//end isset go
?>
<!-- HTML FORM GOES HERE -->
STEP 4. restricted page:
<?php #admin/restricted.php
#####[make sure you put this code before any html output]#####
//starting the session
session_start();
//checking if a log SESSION VARIABLE has been set
if( !isset($_SESSION['log']) || ($_SESSION['log'] != 'in') ){
//if the user is not allowed, display a message and a link to go back to login page
echo "You are not allowed. back to login page";
//then abort the script
exit();
}
else{
echo "Success!";
}
/**
* #### CODE FOR LOG OUT #### click here to see the logout tutorial
*/
?>
<!-- RESTRICTED PAGE HTML GOES HERE -->
I have a MySQL database with a user called admin (and password admin). I am using this to test my configuration. When I click login, nothing happens. Can anyone see if I've done something wrong?
Here is my logon form:
<form action="loginProcess.php" method="POST">
Username: <input type='text' name='username'></br>
<!-- input type password makes the password hidden as it is typed -->
Password: <input type='password' name='password'></br>
<input type='submit' value='Login'/>
</form>
</br>
</br>
<!-- Register New User -->
<form action="register.php" method="POST"> </br>
Not Registered?<input type='submit' value='Click Here To Register'/>
</form>
This form takes you to this loginProcess.php file:
<?php
ob_start();
session_start();
// Include database connection and select database UFPProducts
include "./shopdb/connection.php";
?>
<?php
//
// (2) Collect data from form and save in variables
// real escape string to protect from SQLi attacks
$username=mysql_real_escape_string(htmlentities($_POST['username']));
$password=mysql_real_escape_string(htmlentities($_POST['password']));
// (3) Create query of the form below to search the user table
// "SELECT * FROM Users WHERE UserName='$username' AND Password='$password'"
$query = "SELECT * FROM USERS where Username='$username' AND Password='$password'";
$result = mysql_query($query) or die (mysql_error());
// (3) Run query through connection
// (4) Check result of query using code below
// if rows found set authenticated user to the user name entered
if (mysql_num_rows($result) > 0) {
$_SESSION["authenticatedUser"] = $username;
// Relocate to the logged-in page
header("Location: ./login/loggedOn.php");
}
else
// login failed redirect back to login page with error message
{
$_SESSION["message"] = "Could not connect as $username " ;
header("Location: login.php");
}
?>
And here is my connection.php file just incase anyone wants to see:
<?php
//*** "die()" will exit the script and show an error if something goes wrong with the "connect" or "select" functions.
//*** A "mysql_connect()" error usually means your connection specific details are wrong
//*** A "mysql_select_db()" error usually means the database does not exist.
// Place db host name. Usually is "localhost" but sometimes a more direct string is needed
$db_host = "localhost";
// Place the username for the MySQL database here
$db_username = "root";
// Place the password for the MySQL database here
$db_pass = "";
// Place the name for the MySQL database here
$db_name = "UFPProducts";
$connect = mysql_connect("$db_host","$db_username","$db_pass") or die(mysql_error());
mysql_select_db("$db_name") or die("there is no database with that name");
// echo "<center>You are successfully connected to the Under5Pounds database.</center><br>";
?>
I'm not getting any error messages right now, it just doesn't do anything once I type in the username + password and click login.
try this code in loginProcess.php
$username=$_POST['username'];
$password=$_POST['password'];
I think you should remove
ob_start();
from the first line of loginProcess.php file, it has nothing to do there (unless tell me the good reason) and it blocks data to be sent to the browser
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.