PHP - Users links - javascript

I have created a registration & login system, it is working properly.
But, I only knew how to make a register & login system, I don't know how to make a link for every registered user
like :
example.com/marwan
example.com/user/marwan
Here is my Register PHP Code :
<?php
error_reporting(0);
session_start();
if( isset($_SESSION['user_id']) ){
header("Location: /");
}
require 'includes/database.php';
$message = '';
if(!empty($_POST['email']) && !empty($_POST['password'])):
// Enter the new user in the database
$sql = "INSERT INTO users (full_name, email, password, phone, country) VALUES (:full_name, :email, :password, :phone, :country)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':full_name', $_POST['full_name']);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
$stmt->bindParam(':phone', $_POST['phone']);
$stmt->bindParam(':country', $_POST['country']);
if( $stmt->execute() ):
header("Location: account-created.php");
else:
header("Location: failed.php");
endif;
endif;
?>
And my Login code is :
<?php
session_start();
if( isset($_SESSION['user_id']) ){
header("Location: /tregolapp/home");
}
require 'includes/database.php';
if(!empty($_POST['email']) && !empty($_POST['password'])):
$records = $conn->prepare('SELECT id,email,password FROM users WHERE email = :email');
$records->bindParam(':email', $_POST['email']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
$message = '';
if(count($results) > 0 && password_verify($_POST['password'], $results['password']) ){
$_SESSION['user_id'] = $results['id'];
header("Location: /tregolapp/index.php");
} else {
header("Location: /tregolapp/failed");
}
endif;
?>
Can someone help me please?

What is your purpose in giving each user their "own URL"?
If you want each user to see their "own information" upon login, then after login go to a common "home page" while holding a session id. Use that id to pull "user specific" data from your database and display it on the "home page".

Related

Automatic password error message on php BEFORE atempting to login

I have created a simple php login form which connects to a database and checks the validity of username and password. If they are correct it allows access if not an error message is displayed. My problem is that when I go to my login page it is automatically giving me an error message saying"invalid user etc" before i have even attempted to login in. Any suggestions as to why this might be?
<?php
session_start();
include('conn.php');
$theUserID = $_POST['userID'];
$theUserPassword = $_POST['password'];
$query = "SELECT userID, firstName, password FROM user INNER JOIN password ON user.passwordID=password.passwordID WHERE userID='$theUserID' AND password='$theUserPassword'";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if(mysqli_num_rows($result)>0){
//let them in
$_SESSION['myuser40058058']=$theUserID;
Header("Location:index.php");
}
else{
$message = "Incorrect Username or Password";
echo "<script type='text/javascript'>alert('$message');</script>";
}
?>
<?php
session_start();
check if the form was posted and user and password are set
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['userID']) && isset($_POST['password'])){
THIS IS ABSOLUTE UNSECURE !!!
check Paths for include and test values of the form!!
include('conn.php');
$theUserID = $_POST['userID'];
$theUserPassword = $_POST['password'];
THIS IS UNSECURE !!!
use at least a $mysqli->real_escape_string($YOUR_VARIABLES) in the query
$query = "SELECT userID, firstName, password FROM user INNER JOIN password ON user.passwordID=password.passwordID WHERE userID='$theUserID' AND password='$theUserPassword'";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if(mysqli_num_rows($result)>0){
//let them in
$_SESSION['myuser40058058']=$theUserID;
Header("Location:index.php");
}else{
$message = "Incorrect Username or Password";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
?>

how to display an alert after redirect to another page

login form (index.php) was already created. when form is submitted username and password are passed in to another page (login-controller.php). after verifying, if username or password is incorrect user was redirected to login form(index.php) after display the alert box in login-controller.php.but i want to display an alert box like "invalid login credentials" after redirect to login form(index.php). how can i solve this. code of login-controller.php are given bellow.
<?php
session_start();
if (isset($_SESSION['username'])) {
header('Location: ../service/index.php');
}
include '../include/conn.php'; //database connection
if (isset($_POST["submit"])) {
if (empty($_POST["username"] && $_POST["password"])) {
header('Location: index.php');
} else {
$username = mysqli_real_escape_string($conn, $_POST["username"]);
$password = mysqli_real_escape_string($conn, $_POST["password"]);
$password = md5($password);
$sqli = "SELECT * FROM user WHERE name = '$username' AND password = '$password'";
$result = $conn->query($sqli);
$count = mysqli_num_rows($result);
if ($count == 1) {
$_SESSION['username'] = $username;
header('Location: ../service/index.php');
} else {
include '../include/bootstrap.php'; //bootstrap js and css
echo '<div class="alert alert-danger"><strong>Oops!</strong> Invalid Login Credentials.</div>';
echo "<script>setTimeout(\"location.href = 'index.php';\",3000);</script>";
}
}
}
?>
Using session variables you can display alerts:
$_SESSION['alerts'][] = "Test Alert";
$_SESSION['alerts'][] = "Another Test Alert";
Then in your config, or any other .php file that gets executed on every page that you have ( If you have a templating system, do that in the template) do this:
if(isset($_SESSION['alerts'])){
foreach($_SESSION['alerts'] as $alertmessage){
echo '<div class="alert">' . $alertmessage . '</div>';
}
}

How to manage Php sessions in same page in php

I have a Index page in Php and a login link. When user login to the site then i want to redirect to the same page (index.php). At the place of login link I want to show the username of the user or client. I have a php login code like this
$error = '';
if (isset($_POST['login']) && !empty($_POST['email'])
&& !empty($_POST['password'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$sel_user = "select * from customer where email='$email' AND password='$password'";
$run_user = mysql_query($sel_user);
$check_user = mysql_num_rows($run_user);
if($check_user == 1){
$_SESSION['email']=$email;
echo "<script>window.open('userinfo.php','_self')</script>";
}
else {
$error = 'Invalid username or password';
}
}
in this code page is redirecting to another page after login but i want to redirect it to same page as index.php. And add links like my account and logout links instead of login link in index.php. I have a Php sessions page code like this
if(!isset($_SESSION))
{
session_start();
}
$login_session=$_SESSION['email'];
if(!isset($_SESSION['email']))
{
// not logged in
header('Location: login.php');
exit();
}
How can i make this for example like flipkart.com. Please help me.
You can do one thing:
Go for the code that you have already written for the login, i.e.,
$error = '';
if (isset($_POST['login']) && !empty($_POST['email'])
&& !empty($_POST['password'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$sel_user = "select * from customer where email='$email' AND password='$password'";
$run_user = mysql_query($sel_user);
$check_user = mysql_num_rows($run_user);
if($check_user == 1){
$_SESSION['email']=$email;
echo "<script>window.open('userinfo.php','_self')</script>";
}
else {
$error = 'Invalid username or password';
}
}
After this you do a check of the session variable
if(!isset($_SESSION))
{
session_start();
}
$login_session=$_SESSION['email'];
if(!isset($_SESSION['email']))
{
// not logged in
header('Location: index.php'); //change the redirect page to index.php
//now customize the menu accoringly
echo "<nav class='your-class'>";
echo "<li>";
echo "<ul>Login</ul>";
//Some more menus
echo "</nav>";
exit();
}
else
{
header('Location: index.php'); //now configure the menu accordingly
//now customize the menu accoringly on login
echo "<nav class='your-class'>";
echo "<li>";
echo "<ul>My Account</ul>";
//Some more menus
echo "<ul>Logout</ul>";
echo "</nav>";
}
But as far as I know this is somewhat tiresome and please try to avoid the queries like this. Use PDO instead. Thanks.
Try this
header('location:'.$_SERVER['PHP_SELF']);
instead of
echo "<script>window.open('userinfo.php','_self')</script>";
and for manage links
<ul>
<?php if(isset($_SESSION['email'])){ ?>
<li><a href="logout.php" >Logout</a></li>
<?php }else{ ?>
<li><a href="index.php" >Home</a></li>
<?php }?>
</ul>

php login form pass vars

i have a page login
in page have html form with textboxes and submit button
and in top of page i have PHP code thet chacke if name and password in database
if name and password in database page go to new page and pass the name and password to next page
i can do it with get metod like the vars in the URL
but i want to pass and go to new page with Post metod
how i can do it??
pleas help me with code....
in code html :
form name="frmlogin"action="<?= $_SERVER['PHP_SELF'] ?>" method="post" >
and in top of the page have PHP code:
$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST["name"];
$password = $_POST["password"]; if ($name == '' || $password == '') {
$msg = "You must enter all fields";
} else {
$sql = "SELECT * FROM tbluser WHERE fldUsername = '$name' AND fldPass = '$password'";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
/*header('Location: YOUR_LOCATION');
exit;*/
$msg = "Username and password match";
echo '<script type="text/javascript">
window.location.href = "smartphon100.php?name='. $name .'&password='. $password .'";
}
if (mysql_num_rows($query) <= 0) {
$msg = "Username and password do not match";
}
}
}
help me to change the javascript window.location to post metod
You can go for php redirect also.
header('location:smartphon100.php?name='. $name .'&password='. $password) ;
BTW: you are passing password in browser?
If I understand correctly, you're trying to redirect a user after successfully logging in.
I see that your current code attempts to redirect using Javascript, the issue seems to be with the quotes on the value you tried to enter.
Try to change this line:
window.location.href = "smartphon100.php?name='. $name .'&password='. $password .'";
to this:
window.location.href = "smartphon100.php?name='.$name.'&password='. $password";
Overall you should read about security as the code you presented is very vulnerable.
PHP: SQL Injection - Manual
If you're trying to pass the values to another page in a POST method using Javascript, you could take a look at this answer:
JavaScript post request like a form submit
Although as I don't see a reason for posting the values more than once,
I recommend you to read about PHP sessions, cookies, and encryption, which allow you to store values that you can use across the website securely.
A simple example to using session:
<?php
//Starts the session, you need to use this line in every PHP file that'll need to access session variables
session_start();
$_SESSION['user'] = "Donny"; //Storing a user name
?>
A simple example of session use with your code:
Foo.php
session_start();
$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST["name"];
$password = $_POST["password"]; if ($name == '' || $password == '') {
$msg = "You must enter all fields";
} else {
$sql = "SELECT * FROM tbluser WHERE fldUsername = '$name' AND fldPass = '$password'";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
$_SESSION['user'] = $name;
$_SESSION['pass'] = $password;
$msg = "Username and password match";
echo '<script type="text/javascript">window.location.href = "smartphon100.php";</script>';
}
if (mysql_num_rows($query) <= 0) {
$msg = "Username and password do not match";
}
}
}
Bar.php
<?php
session_start();
//Accessing the values:
echo $_SESSION['user'];
echo $_SESSION['pass'];
?>
NOTE:
It's not good to store values like that as again, they're not secure, please read about hashing passwords.
PHP: Password Hashing

Registration Form (HTML, PHP & MySQL) redirect after error or missing values

I am new to development with HTML, PHP, CSS etc.
I need to do this small Registration and Login Form. I haven't gone into detail in Object-Oriented PHP and I'm working in the simplest manner as this task needs to be done in a short time and I've only been coding and experimenting with these languages these past two days.
What I already have is a working Registration and Login forms that when they are submitted the information is posted to another php file. Than it verifies that the data has been entered and that the e-mail isn't already used. What i need is that when either the e-mail is already used and when a field is left empty that it automatically goes back to Registration/Login forms and displays a message with their respective errors.
I know this might have been done in a different way but the deadline is really close and so i need a solution that works with what I already have.
I'm sorry if a similar question is already available, but i might be using incorrect keywords to search for the solution.
Keywords currently that I'm using are Redirection, "Going back to previous page".
If JavaScript is more suitable for this kind of operation it is also excepted and would like this to be pointed out, although a php solution would be appreciated a bit more as i currently obtain more knowledge on PHP than on JavaScript.
Thanks, any help or directions to suitable solutions would be mostly appreciated.
You can use
A) PHP header() function
B) echo a META HTTP - EQUIV=" refresh "
CONTENT=" seconds; URL = \the-other-url">
C) Use JS like this but you
will need to set a timeout
Example:
if (empty ($_POST ['username']) || empty ($_POST ['password']))
{
echo "Please enter a username, or password";
header ("refresh:5; url=back.php");
exit;
}
There are many different ways to do this. If when the form is submitted your executing the code on a different php file then you could have an IF statement there which redirects the headers back to the form page if there are errors with the users input such as:
if($username == "")
{
header("Location: YOUR_FORM_PAGE.php");
}
Hope this helps.
To add the execution to the same page you can do this.
add these buttons;
<input type="hidden" id="submitted" name="submitted" value="1">
<span class="label"></span><input type="submit" class="submit" value="Submit"><input type="reset" class="submit" value="Clear">
set the form action to the form page. Add this to the top of the page and add any PHP you want to it;
if(isset($_POST["submitted"]) && $_POST["submitted"] == 1)
{
for example;
if($from_fullname == "")
{
$submission_status = '<div class="vpb_info" align="left">Please enter your fullname in the required field to proceed. Thanks.</div>';
}
and add this to the page where you want the error displayed;
<p> <?php echo $submission_status; ?></p>
Sounds like http-redirect (http://php.net/manual/en/function.http-redirect.php) should help you out. You can redirect on your error conditions with that.
Update
With redirect you can attatch QueryString Parameters so you could redirect back to the login.php page with an errror code and/or message as a query string perameter.
These will get you started, a registration or signup php file and a login php file I made once
(personal info is faked).
SignUp.php
<?php
session_start();
$name = $_REQUEST['name'] ;
$userpassword = hash('sha512',$_REQUEST['password'] );
$signature = $_REQUEST['signature'] ;
$image = $_REQUEST['image'];
$email = $_REQUEST['email'] ;
$emailreplies = $_REQUEST['emailreplies'] ;
if (!isset($_REQUEST['name'])) {
header( "Location: MotesBlog.php" );
}else{
$username="root";
$password="root";
$database="MotesBlog";
mysql_connect("localhost",$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query=sprintf("SELECT Name FROM users WHERE Name LIKE '%s';",
mysql_real_escape_string($name));
$query=mysql_query($query);
if(mysql_num_rows($query)){
$query = sprintf("SELECT Email FROM users WHERE Name='%s';",
mysql_real_escape_string($name));
$query=mysql_query($query);
$_SESSION['NameTaken'] = true;
$_SESSION['UsedName'] = $name;
$_SESSION['UsedEmail'] = mysql_result($query,0);
header("Location: SignUp.html");
}else{
$query=sprintf("SELECT Email FROM users WHERE Email LIKE '%s';",
mysql_real_escape_string($email));
$query=mysql_query($query);
if(mysql_num_rows($query)){
$_SESSION['EmailTaken'] = true;
$_SESSION['UsedEmail'] = $email;
header("Location: SignUp.html");
}else{
$query = sprintf(" INSERT INTO users VALUES (
NULL , '%s', '%s' , '%s', '%s', '%s', CURRENT_TIMESTAMP , 0, $emailreplies);",
mysql_real_escape_string($name),
$userpassword,
mysql_real_escape_string($signature),
mysql_real_escape_string($image),
mysql_real_escape_string($email));
mysql_query($query);
$query = sprintf("SELECT JoinDate FROM users WHERE Name='%s';",
mysql_real_escape_string($name));
$vcode=md5(mysql_result(mysql_query($query),0));
mysql_close();
require_once "Mail.php";
$from = "PocketWoods Hunting Hall<pwoods#email.com>";
$to = $email;
$subject = "Welcome to Motes Blog";
$body = "<html>
<body>Thank you for your time. <br/>
To ensure a human made this account and not an
automated process please click the link below:<br>
<a href=\"http://site.com/MotesBlog/verifyaccount.php?vcode=".$vcode."&name=".$name."\">
Activate Account
</a>
</body>
</html>";
$host = "mail.root.com";
$username = "root#root.com";
$password = "root";
$headers = array ( 'From' => $from,
'To' => $to,
'Subject' => $subject,
'MIME-Version' => "1.0",
'Content-type' => "text/html; charset=iso-8859-1");
$smtp = Mail::factory('smtp',
array ( 'host' => $host,
'auth' => false,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
header("Location: success.html");
}
}
}
?>
Login.php
<?php
session_start();
$username="root";
$password="root";
$database="MotesBlog";
mysql_connect("localhost",$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$user_name = $_REQUEST['name'];
$user_password = $_REQUEST['password'];
if (!isset($_REQUEST['name'])) {
header( "Location: MotesBlog.php" );
}else{
if(isset($_SESSION['User'])){
if( ($_SESSION['CreatedTime'] + 3600) < time() ){
$_SESSION['Expired'] = true;
}
unset($_SESSION['User']);
}
$query = sprintf("SELECT Password FROM users WHERE Name='%s';",
mysql_real_escape_string($user_name));
$query=mysql_query($query);
if(mysql_num_rows($query)){
$real_password=mysql_result($query,0);
$query = sprintf("SELECT Email FROM users WHERE Name='%s';",
mysql_real_escape_string($user_name));
$query=mysql_query($query);
$email = mysql_result($query,0);
if($real_password == hash('sha512',$user_password)){
$query = sprintf("SELECT Validated FROM users WHERE Name='%s';",
mysql_real_escape_string($user_name));
$query=mysql_query($query);
mysql_close();
if(mysql_result($query,0)){
$_SESSION['User'] = $user_name;
$_SESSION['CreatedTime'] = time();
setcookie("User", $_REQUEST['name'], time() + 60*60*24*365);
header( "Location: MotesBlog.php" );
}else{
$_SESSION['resend_name'] = $user_name;
$_SESSION['resend_email'] = $email;
$_SESSION['NotValidated'] = true;
header( "Location: MotesBlog.php" );
}
}else{
$_SESSION['WrongPW'] = true;
$_SESSION['UsedEmail'] = $email;
header( "Location: MotesBlog.php" );
}
}else{
$_SESSION['WrongName'] = true;
header( "Location: MotesBlog.php" );
}
}
?>

Categories

Resources