Cannot access html form data in a post message (PHP) - php

I am trying out a php sample code given here: https://www.tutorialrepublic.com/php-tutorial/php-mysql-login-system.php
This gives a log in form, where you can register username password and then log in with a registered user. A welcome page is only visible after you have logged in, and the welcome page shows the specific username of the currently logged in account.
I am trying to modify the welcome.php given in the above link, to add a data entry form that will save some personal data like name and age to a mariadb database. Here is my version of the welcome.php file:
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
$uname=htmlspecialchars($_SESSION["username"]);
$name = "";
$age = 0;
if($_SERVER["REQUEST_METHOD"] == "POST"){
// /*
echo '<script language="javascript">';
echo 'alert("submit button clicked")';
echo '</script>';
// */
// /*
$tempvar = trim($_POST["name"]);
// $tempvar='sdsd';
var_dump($tempvar);
if($tempvar == "")
echo $tempvar.' found';
// */
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; text-align: center; }
</style>
</head>
<body>
<div class="page-header">
<h1>Hi, <b><?php echo htmlspecialchars($_SESSION["username"]); ?></b>. Welcome to our site.</h1>
</div>
<p>
Reset Your Password
Sign Out of Your Account
</p>
<p>Enter your data here:</p>
<!-- <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> -->
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit" name="save" value="submit">
<!-- <input type="submit" class="btn btn-primary" value="submit"> -->
</form>
</body>
</html>
If I understand this correctly clicking the submit button should generate a post message which should be captured by the php script at the beginning of the file. This much is happening, but I cannot display the content of the text box given by <input type="text" name="name">. The var_dump($tempvar); in the php code at the beginning comes up with String(0) "". I have tried moving the php code to a separate file (as given here in insert.php) instead of attempting to process the post message in the same file, but I am getting the same result. I am not getting any errors.
How do I access the contents of the text box in the post message handler? I am testing this in XAMPP on Windows 10.

Did the example with the login work correctly? This would prove that POSTing data works.
Which version of PHP are you using? There was a feature called register_globals up to 5.4.0 which allowed accessing POST data via named variables. Since you are setting $name = "" this could overwrite your data. I would take it out at that position anyway (use an else clause if necessary). If you have register_globals active either update PHP or turn it off to avoid confusion.
The next step to debug the issue is to print the whole array of $_POST like mentioned here but more pretty
if($_SERVER["REQUEST_METHOD"] == "POST"){
echo '<pre>';
print_r($_POST);
echo '</pre>';
die();
This will show you what values were actually POSTed.
Same can be done with the $_SERVER array like this
echo '<pre>';
print_r($_SERVER);
echo '</pre>';
die();
$uname=htmlspecialchars($_SESSION["username"]);
The die() command will halt execution so you need to remove it when you want the script to continue.

Your code works fine for me. I ran it in my system, it shows the submitted name with the var_dump i.e. string(18) "Md Shabbir Hossain".

There are some flaws that I would fix.
Initial user get to Welcome.php.
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
$uname=htmlspecialchars($_SESSION["username"]); //username is not defined or it does not exists yet.
$name = "";
$age = 0;
if($_SERVER["REQUEST_METHOD"] == "POST"){
// /*
echo '<script language="javascript">';
echo 'alert("submit button clicked")';
echo '</script>';
// */
// /*
$tempvar = trim($_POST["name"]);
// $tempvar='sdsd';
var_dump($tempvar);
if($tempvar == "")
echo $tempvar.' found';
// */
}
I would do this:
<?php
// Initialize the session
session_start();
//Check if the user already logged.
if(!isset($_SESSION["loggedin"])){
//Redirect
header("location: login.php");
exit;
}
// Check if post to login is submitted
if(isset($_POST['save'])){
// /*
echo '<script language="javascript">';
echo 'alert("submit button clicked")';
echo '</script>';
$uname = '';
//Check if Username is submitted
if(isset($_POST['username'])){
$_SESSION["username"] = $_POST['username'];
$uname=htmlspecialchars($_SESSION["username"]);
}
$name = "";
$age = 0;
//For test
var_dump($_POST[]);
}

Related

Login implementation in PHP

Suppose, I have two pages login.php and index.php. In index.php I have two buttons Login and register.After clicking the buttons ,the user is directed to login.php.
If I want to implement a login functionality using PHP, something related to facebook such that the if a user has logged in before, then it bypasses the index page once the username and password are set and directly lands into the login page. Is $_SESSION a proper way of doing it.
For example:
<?php
session_start();
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Ayu</title>
</head>
<body>
<?php if (isset($_SESSION["user"])) { ?>
<h1>Hi <?php echo $_SESSION["user"]; ?></h1>
Logout
<?php } else { ?>
<h1>Login</h1>
<?php echo (isset($_GET["error"])) ? '<p>You idiot!</p>' : ""; ?>
<form action="new-user.php" method="post">
<div>
<label>
<strong>Username</strong>
<input type="text" name="username" />
</label>
</div>
<div>
<label>
<strong>Password</strong>
<input type="password" name="password" />
</label>
</div>
<input type="submit" value="Log In" />
</form>
<?php } ?>
</body>
</html>
In the login functionality, I am setting the $_SESSION values
<?php
session_start();
if (count($_POST))
if ($_POST["username"] == "ayu" && $_POST["password"] == "shee") {
$_SESSION["user"] = "Ayushi";
header("Location: ./");
} else {
unset($_SESSION["user"]);
header("Location: ./?error");
}
?>
Yes using and creating ($_SESSION) session is the correct way to check logged in users.
$_SESSION is a 'superglobal', or automatic global, variable. This
simply means that it is available in all scopes throughout a script.
There is no need to do global $variable; to access it within functions
or methods.
Check for session on very top of a page, if found redirect to index else to login page.
if(!isset($_SESSION['login_user'])){
header("location:login.php");
}
Refer this simple login example using my sql in php Here
EDIT
As requested by OP - if you want to hide a particular section in index.php page based on session value or say if a user is logged in or not that can be done like:
<?php
if(isset($_SESSION['login_user'])){
?>
<form>
<input type="submit" name="whatever" />
<!-- Other Fields -->
</form>
<?php
}
?>
Html Form in the above code will only be shown if a user is logged in else it will be hidden.
Yes, Session is best way to implement the same. You can use the below php code to solve your problem
<?php
session_start();
if (!empty($_POST))
if ($_POST["username"] == "ayu" && $_POST["password"] == "shee") {
$_SESSION["user"] = "Ayushi";
header("Location: ./");
} else {
if($_SESSION["user"]!=''){
unset($_SESSION["user"]);
}
header("Location: ./?error");
}else{
/* Write code for form */
}
?>

session_start() not working properly

I hope you are doing great,
I'm making this website with login accounts apparently, I have registered my users in a local database and in a server database. My HTML/PHP code doesn't show any errors when I run it.I have checked my DB connection. it's correct. The website allows me to sign in with any user and password. It doesn't seem to validate my entered data properly. Although I checked my SQL command.
I wonder if you could help me with this guys. You are the best! :)
thanks in advance, Cheers
here is a useful piece of my code:
My header - Header.php:
<html>
<?php
/* static $called = FALSE;
if (!$called)
{*/
session_start();
/*$called = true;
}*/
include_once 'debugging.php';
?>
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div >
<dt id="navbar1" class ="navbar">
Home
Upload Videos
</dt>
</div>
<?php
if (isset($_SESSION['logged'])) {
echo '<div class="right navbar" id = "navbar2">
Log out
<p class = "right">/</p>
Edit Account
<img src="http://www.extremetech.com/wp-content/uploads/2013/11/emp-blast.jpg?type=square"
height="42" width="42" class = "right"/>
</div>';
} else {
echo '<div class="right navbar" id = "navbar2">
Login
<p class = "right">/</p>
Sign Up
</div>';
}
?>
Progress - Feedback:
Ok guys, I tried what you told me to do. It started to make me sign in automatically. Probably the session['logged'] variable declaration is considered to be true. I set it to be true only if the user login from the login page. but it is not functioning in that way.
Here is my login page code:
<?php
include_once 'Header.php';
?>
<div id="container">
<br>
<?php
/*
if($_DEBUG)
{
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
error_reporting(E_ALL);
}
$page_title = 'Login';/* */
//in this page we do things slightly differently - the code for validation
and displaying messages is done
//before we display the form
echo '<div id = "div_1"><h1>Login</h1>';
//display the form
echo '<div id="div_2"><div id="div_2">
<form action="index.php" method="post">
<label>UserName<br>
<span class="small">enter your username</span>
</label>
<input type="text" name="UserName" value=""/>
<label><br>Password<br>
<span class="small">enter your password</span>
</label>
<input type="password" name="Password" />
<button type="submit" name="submit" value="Login" />Log in</button>
<input type ="hidden" name="submitted" value="TRUE">
</form>
</div>
</div>';
if (isset($_POST['submitted'])) {
//require_once is similar to 'include' but ensures the code is not
copied multiple times
require_once('LoginFunctions.php');
//list() is a way of assigning multiple values at the same time
//checkLogin() function returns an array so list here assigns the
values in the array to $check and $data
list($check, $data) = checkLogin($_POST['UserName'],
$_POST['Password']);
if ($check) {
setcookie('FName', $data['FName'], time()+ 900 ) ; //cookie
expires after 15 mins
setcookie('LName', $data['LName'], time() + 900 ) ;
//
//use session variables instead of cookies
//these variables should now be available to all pages in the
application as long as the users session exists
$_SESSION['FName'] = $data['FName'];
$_SESSION['LName'] = $data['LName'];
$_SESSION['UserName'] = $data['UserName'];
//to enable $_SESSION array to be populated we always need to call
start_session() - this is done in header.php
//print_r is will print out the contents of an array
print_r($_SESSION);
//
//Redirect to another page
$url = absolute_url('Index.php'); //function defined in
Loginfunctions.php to give absolute path for required page
$_SESSION['logged'] = TRUE;
//this version of the header function is used to redirect to
another page
header("Location: $url");//since we have entered correct login
details we are now being directed to the home page
exit();
} else {
$errors = $data;
}
}
//create a sopace between the button and the error messages
//echo'<div class="spacer"></div>';
if (!empty($errors)) {
echo '<br/> <p class="error">The following errors occurred: <br
/>';
//foreach is a simplified version of the 'for' loop
foreach ($errors as $err) {
echo "$err <br />";
}
echo '</p>';
}
//this is the end of the <div> that contains the form
echo '</div>';
/* */
?>
</div>
<?php
include 'Footer.php';
?>
See the notes section of the session_start documentation. Revise your code as follows:
<?php
// Start the session before ANY output.
// Start the session always - there's little / no value to only starting sometimes.
session_start(); ?>
<html>
<?php
/* static $called = FALSE;
if (!$called)
{*/
/*$called = true;
}*/
include_once 'debugging.php';
?>
<head>
session_start must run before any output is sent to the browser. Additionally, there's no value in having it in an if statement, so keep it simple and put it where it runs consistently before any output.

Checking the session value that is available or not

I wrote the following login.php file.
<?php
session_start();
//Check everything and if everything is correct and the username and password is correct and available
echo "Successfully";
$_SESSION['login_user'] = $username;
// and etc
?>
Now if the username is session as the the result $_SESSION['login_user'] value is session also.
and then I create check-session.html file and it is as follows:
<html>
<body>
<form method = "POST" action = "check.php">
<input type = "submit" value = "check-session">
</form>
</body>
</html>
And then the check.php file is as follows:
<?php
if(isset($_SESSION['login_user'])) {
echo "session is available";}
else { echo "session is not available"; }
?>
But the problem is when the login operation is successfully and now I want to know that the session is created really or not, after clicking the check-session button in the check-session.html page, I see the result from server as the follows:
session is not available
Also for more information I use wamp server.
Put session_start(); in the start of every page that's using sessions or is related to them in any way.
In the start of your check.php file
<?php
session_start();
if(isset($_SESSION['login_user'])) {
echo "session is available";}
else { echo "session is not available"; }
?>
You can solve this problem by making a separate file for setting session and include that file on the starting of each logged in page.
this is c.php for checking session...
<?php
include 'b.php';
if(isset($_POST['check_session']))
{
if(isset($_SESSION['login_user']))
echo "session is available";
else
echo "session is not available";
}
?>
<form method = "POST" action = "c.php">
<input type = "submit" name="check_session" value = "check-session">
</form>
a.php for login
<?php
if(isset($_POST['login']))
{
header("Location: c.php");
}
?>
<html>
<body>
<form method = "POST" action = "a.php">
<input type="submit" name="login" value="Login">
</form>
</body>
</html>
and also make b.php simply for setting session using session_start()

How to prevent user from bypassing php authentication

We call it html1 for simplicity.
When a user goes to html1, there's a login2.php login page to enable access to client.php which is the hidden page.
It then goes to checklogin.php...if the password and user name matches...it then goes to the hidden client.php page...if not..it goes back to homepage.
The user has to login to be able to view the contents of hidden client.php page.
However the user can access client.php by typing in ..../client.php on the address bar...therefore bypassing the auth page and rendering it useless. I can just type servername/client.php...and it still shows me the contents of client.php...but I want client.php...to be private!
How do I prevent this from happening?
thanks.
first login page...
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<table>
<form method="post" action="checklogin2.php">
<div id="name">User Id: <input type="text" name="****"></div>
<div id="password">Password: <input type="password" name="*******"></div>
<div class="button"><input type="submit" value="Login"></div>
</form>
</table>
</body>
</html>
then it goes to....
checklogin2.php
<?php
$*** = $_POST['****'];
$***** = $_POST['***'];
if($uid == '****' and $***** == '*****')
{
session_start();
$_SESSION['sid']=session_id();
header("location:securepage.php");
}
else
{
header("location:index.html");
}
?>
Then it goes to...
securepage.php
<?php
session_start();
if($_SESSION['sid']==session_id())
{
header("location:client.php");
echo "<a href='logout.php'>Logout</a>";
}
else
{
header("location:login.php");
}
?>
In the beginning of your every page you have to check if user is authorized.
On checklogin.php if user entered correct login and password, just set something like
$_SESSION['authorized'] = TRUE;
...and on other pages just check if user is authorized:
if (isset($_SESSION['authorized']) && $_SESSION['authorized'] === TRUE) {
// Alright, let's show all the hidden functionality!
echo "Psst! Hey! Wanna buy some weed?";
} else {
// User is not authorized!
header('Location: login.php');
exit();
}
Note that you don't have to mess with cookies, session IDs etc. - just add session_start() before everything and freely use $_SESSION var.
This is the main pro of sessions (and $_SESSION variable in particular): you can remember some data among different pages on same website.
All pages has to check if the user is authed. I would recommend using objects, and always inherit a class that checks this for you. It's not fun to have the same code everywhere, doing the same thing.
if($_SERVER["PHP_SELF"] == '/yourpagefolder/yourpage.php' && !isset($_SESSION['login_user'])){
header('location: login.php');
}

PHP - Checking if the user is logged on

I am quite new at PHP, so I hope there are some that can help.
I have a login page which works fine.
My problem is if you know the url, you can still access the subpages.
This is what it says on my login page
<body>
<?php
if(#!empty($_SESSION['acesses'])) {
echo '<script language="JavaScript">{ location.href="subpage.php"; self.focus(); }</script>';
}
?>
<div id="loginWrapper">
<div id="login">
<form name="loginform" action="<?php $_SERVER['REQUEST_URI']; ?>" method="post" autocomplete="on">
<fieldset id="input">
<h1>Log Ind</h1>
<?php
if(isset($_POST['submit'])) {
echo '<div class="errorBox">';
$username = mysqli_escape_string($conn,$_POST['username']);
$password = mysqli_escape_string($conn,$_POST['password']);
if(!empty($username) && !empty($password)) {
$query = mysqli_query($conn,"SELECT * FROM member WHERE username='$username' LIMIT 1");
$result = mysqli_fetch_array($query);
if($result['username'] == $username && $result['password'] == $password) {
//Sesstion Information
$_SESSION['acesses'] = $result['id'];
echo '<script language="JavaScript">{ location.href="subpage.php"; self.focus(); }</script>';
}else {
echo 'Brugernavnet eller Adganskoden stemmer ikke overens.';
}
}
echo '</div>';
}
?>
<label for="username"> Dit Brugernavn</label>
<input name="username" id="user" type="text" placeholder="Brugernavn">
<label for="password"> Dit password </label>
<input name="password" id="pass" type="password" placeholder="Password">
<input name="submit" type="submit" value="Log ind" />
</fieldset>
</form>
..........
This is what it says at the top of my subpage
<?php
session_start();
if(!empty($_SESSION['acesses'])) {
echo '<script language="JavaScript">{ location.href="login.php"; self.focus(); }</script>';
}
?>
<!doctype html>
<html lang="en">
<head>
You could do redirect the user, if they are not logged in, and vice-versa.
if (!empty($_SESSION['acesses'])){
header("Location: yourpage.php"); // or whatever page you like
exit();
}
else{
// your code for when user is logged in
}
Don't use JavaScript to redirect, especially when dealing with sessions. A user can simply turn off JavaScript in their browser and the redirect won't work anymore.
First of all, your subpage redirects away if the user isn't logged in. Second of all, instead of a javascript redirect, use an HTTP one:
<?php
session_start();
if(!isset($_SESSION['acesses']) || empty($_SESSION['acesses'])) {
Header("Location: index.php");
}
?>
You can use the following logic in the page(s) you wish to protect:
if(isset($_SESSION['acesses']) && !empty($_SESSION['acesses'])){
// give access
}
else{
// don't give access
}
and do the same for all your pages.
Sidenote: The code you posted for your login page doesn't contain session_start(); - If it's not in your working code, include it. It must be inside all pages using sessions.
<body>
<?php
session_start();
if(#!empty($_SESSION['acesses'])) {
echo '<script language="JavaScript">{ location.href="subpage.php"; self.focus(); }</script>';
}
?>
You should also consider embedding <noscript>Please enable Javascript</noscript> into your code and redirect the user if it isn't enabled.
Important sidenote: I noticed you are storing passwords in plain text. This is highly discouraged.
If your PHP version is 5.5, you can use the password_hash() function, or crypt() or bcrypt()
Here are a few resources you can look into:
http://en.wikipedia.org/wiki/Bcrypt
http://codahale.com/how-to-safely-store-a-password/
http://www.php.net/manual/en/function.crypt.php
http://www.php.net/manual/en/function.password-hash.php
About using Javascript:
If you absolutely want to use JS in your code, you can use the following logic:
<?php
echo "<div id=\"hide\">This line is hidden in PHP and will appear once JS is enabled.</div>";
// you can include your JS anywhere in here and will execute once the user enables JS.
?>
<body>
<div class="hide_class">This is hidden using a CSS class and will appear once JS is enabled.</div>
<noscript>
Please enable Javascript to view the content of this page, thank you.
<style>
#hide {
display:none;
}
.hide_class {
display:none;
}
</style>
</noscript>
</body>
First of all, you should use PHP-PDO in order to prevent SQL Injection attacks.
Also your code is wrong at subpage. You should check out variable acesses like following example.
if(!isset($_SESSION['acesses']) or empty($_SESSION['acesses'])) {
echo '<script language="JavaScript">{ location.href="login.php"; self.focus(); }</script>';
}

Categories