I try to login with one PHP file, without any HTML files. So when I'm successfully logged in I want to hide the HTML post button and the textboxes.
Here's my code..:
<?php
$showHTML = true;
if ($showHTML) { ?>
<h1> Bitte einloggen! </h1>
<form action="test2.php" method="POST">
<input name="user" type="test"><br>
<input name="pass" type="password"><br>
<input type="submit" value"Login">
</form>
<?php
}
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if ( $_POST['user'] == "test" && $_POST['pass'] == "a123" ) {
echo "user = test";
$showHTML = false;
}
}
Of course that doesn't hide the HTML code again, because its already executed I think.
Is there any way to hide the HTML output again?
Of course that doens´t hide the HTMLCode again, because its already executed I think.
Correct
Is there any way to hide the HTML output again?
Move the test so it appears before the HTML you (don't) want to output.
Short: put the HTML under the PHP.
Long: Use a decent login system. Use sessions.
You can't use a server side variable to control the already rendered html content.
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if ( $_POST['user'] == "test" && $_POST['pass'] == "a123" ) {
echo "user = test";
}
} else { ?>
<h1> Bitte einloggen! </h1>
<form action="test2.php" method="POST">
<input name="user" type="test"><br>
<input name="pass" type="password"><br>
<input type="submit" value"Login">
</form>
<?php } ?>
Related
I want to allow the user to input some text, then use that text as their session username and then echo a welcome "username" at the top of each page, and then a logout button which will end the session and allow for the user to input a new username
Currently the code will allow the user to input a name, and then a Welcome will appear for that name, but it will be destroyed if the user changes pages, and the textfield to input a name never disappears either - This is the master page in codeigniter
<form action="" method="POST">
<input type="text" name="input_value">
<input type="submit" name ='in' value="LogIn">
</form>
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
$_SESSION['userses'] = '';
}
if(session_status() == PHP_SESSION_ACTIVE && $_SESSION['userses']=='' ){
$_SESSION['userses'] = $_POST['input_value'];
echo "Welcome, ".$_SESSION['userses']."!";
}
else{
echo "Welcome, ".$_SESSION['userses']."!";
}
?>
<form action="<?php session_destroy(); ?>" method="POST">
<input type="submit" name='out' value="LogOff">
</form>
You have to change
if(session_status() == PHP_SESSION_ACTIVE && $_SESSION['userses']=='' )
to
if(isset($_POST['in']) ){
$_SESSION['userses'] = $_POST['input_value'];
}
so when he submits username, this if will catch the post request and then add input to your username
you don't need to check session_status
edit:
and as the comments said, put session_start(); at the beginning of every page
example of code :
<?php session_start();
if(isset($_SESSION['userses'])) echo "Welcome".$_SESSION['userses'];
?>
<form action="" method="POST">
<input type="text" name="input_value">
<input type="submit" name ='in' value="LogIn">
</form>
<?php
if(isset($_POST['in']) ){
$_SESSION['userses'] = $_POST['input_value'];
}
?>
<form action="<?php session_destroy(); ?>" method="POST">
<input type="submit" name='out' value="LogOff">
</form>
You are using codeigniter, why not use session library :
https://www.codeigniter.com/user_guide/libraries/sessions.html
I am new to PHP and am trying to do Server Side Form Validation. There are two PHP files Login.php and Form.php. Registration is done in Login.php and Validation in Form.php. The idea is that Form.php will process the form data sent by Login.php
My problem: even if form fields are empty, the variables are still being inserted into the database.
I don't want to insert if its empty. Rather, it has to route back to Login.php with error messages stored as a session variable.
I have checked the Form fields using !isset() and empty in Form.php using an if..else clause. In the if..else clause you can find out if the form fields are empty, and if so, they must go the session variable clause (inside the if condition). Instead, it is going to the else condition and inserting the empty values in variables ('$username','$password','$phone','$mailid','$city') in to the database.
I have read previous questions for similar problem here and even checked Youtube for Server Side Validation. What did I do wrong? Is there a problem with the use of session variables. Kindly assist
Login.php:
<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>
<?php
session_start();
$passworderr='';
if(isset($_SESSION["passworderr"])) {
$passworderr=$_SESSION["passworderr"];
}
?>
<div id="Outer">
<div id="left" >
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" name="form">
<p><label>Username</label> <input type="text" name="regusername" placeholder="Your name"/> </p>
<p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
<input type="Submit" value="Login" />
</form>
</div>
<div id="right">
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
<p>*Username <input required name="username" type="text" /><?php //echo $usernameerr;?></p>
<p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p>
<p> *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p> *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p> *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
<input type="Submit" value="Signup" />
</form></div></div></body></html>
Form.php:
<?php
session_start();
$dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';
$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}
if(!isset($_POST["username"])) {
$_SESSION["usernameerr"]="UserName is required";
}
else{
$username=mysqli_real_escape_string($dbconn,$_POST["username"]);
}
if(!isset($_POST["password"])) {
$_SESSION["passworderr"]="Enter a password";
}
else{
$password=mysqli_real_escape_string($dbconn,$_POST["password"]);
}
if(!isset($_POST["phone"])) {
$_SESSION["phoneerr"]="Phone number is required";
}
else{
$phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
}
if(!isset($_POST["mailid"])) {
$_SESSION["mailiderr"]="Enter a valid mail id";
}
else{
$mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
}
if(!isset($_POST["city"])) {
$_SESSION["cityerr"]="Enter your resident city";
}
else{
$city=mysqli_real_escape_string($dbconn,$_POST["city"]);
}
$selected = mysqli_select_db($dbconn,"$dbname")
or die("Could not select examples".mysqli_error($dbconn));
if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )
{
$res=mysqli_query($dbconn,"Insert into user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
if($res)
{
header("location:Login.php");
}
}
else
{
print "Problem in inserting";
header("location:Login.php");
}
mysqli_close($dbconn);
?>
There are a bunch of ways to do this. A blank form field is present on the server side with an empty value. So in addition to checking if the variable is set, in your case you want to check if the value is non-empty.
One way to do that is to use the strlen function.
So an example for you is:
if(!isset($_POST["username"]) || strlen($_POST["username"]) == 0) {
NOTE: Do not use the empty function since the string "0" is considered 'empty'. Read the manual for other such cases.
You may want to consider using a helper function to do the determination. Basically something like this:
function DoesPostFormFieldHaveValue($formFieldName) {
return(
isset($_POST[$formFieldName])
&& strlen($_POST[$formFieldName]) > 0
);
}
First of all, session_start should always be the first line of the php page you need to use sessions on.
Also, I'm not sure why you are using so many session variables for storing errors. Instead of this, use a single session variable, declare it as array and store all the errors in it.
Here's your updated form :-
<?php
session_start();
if((isset($_SESSION['errors']))) //check if we have errors set by the form.php page
{
echo "Please fix the following errors";
foreach($_SESSION['errors'] as $error) //loop through the array
{
echo $error;
}
}
?>
<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>
<div id="Outer">
<div id="left" >
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" name="form">
<p><label>Username</label> <input type="text" name="regusername" placeholder="Your name"/> </p>
<p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
<input type="Submit" value="Login" />
</form>
</div>
<div id="right">
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
<p>*Username <input required name="username" type="text" /><?php //echo $usernameerr;?></p>
<p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p>
<p> *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p> *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p> *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
<input type="Submit" value="Signup" />
</form></div></div></body></html>
Backend processing file :-
<?php
session_start();
$_SESSION['errors'] = array(); //declare an array
$dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';
$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}
if((!isset($_POST["username"])) || (empty($_POST['username']))) {
$_SESSION["errors"][]="UserName is required"; //push error message to array if $_POST['username'] is empty or is not set
}
else{
$username=mysqli_real_escape_string($dbconn,$_POST["username"]);
}
if((!isset($_POST["password"])) || (empty($_POST['password']))) {
$_SESSION["errors"][]="Enter a password";
}
else{
$password=mysqli_real_escape_string($dbconn,$_POST["password"]);
}
if((!isset($_POST["phone"])) || (empty($_POST['phone']))) {
$_SESSION["errors"][]="Phone number is required";
}
else{
$phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
}
if((!isset($_POST["mailid"])) || (empty($_POST['mailid']))) {
$_SESSION["errors"][]="Enter a valid mail id";
}
else{
$mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
}
if((!isset($_POST["city"])) || (empty($_POST['city']))) {
$_SESSION["errors"][]="Enter your resident city";
}
else{
$city=mysqli_real_escape_string($dbconn,$_POST["city"]);
}
$selected = mysqli_select_db($dbconn,"$dbname")
or die("Could not select examples".mysqli_error($dbconn));
if(count($_SESSION['errors']) < 1) //check if the the $_SESSION['errors'] count is less than 1 (0), this means there are no errors.
{
$res=mysqli_query($dbconn,"Insert into user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
if($res)
{
header("location:Login.php");
}
}
else
{
print "Problem in inserting";
header("location:Login.php");
}
mysqli_close($dbconn);
?>
The thing about isset is that it checks if the variable exists, and therefore allows variables that contain an empty string, like you have. When the current form is submitted without any user input, it is submitting a whole bunch of variables containing empty strings.
Now the solution is to change all your isset() to empty() and that should solve your problem!
[Note] There is no need to use both isset() and empty() like this:
if(!isset($_POST['fieldname']) && !empty($_POST['fieldname']))
because empty() is doing everything that isset() does.
check like this:
if(!isset($_POST["username"]) && $_POST["username"]!="")
Your PHP code is checking for isset only, I don't see any empty check. isset will be always true in your case to either of the forms, as the form fields are submitting - just the values are blank.
To prevent empty insertions, add a !empty check to your conditions. Your conditional statements should look like this -
if(!isset($_POST['fieldname']) && !empty($_POST['fieldname']))
first of all a little advice. If you want to start a new project, I would advice you learn how to use PDO connection to MySQL Databases, and not MySQLi. As PDO is much better method, and secured (especially when using prepared statements).
Anyway, as I can see you are storing the errors in a multiple $_SESISON variables, but after you are finishing the validation checks, you are not doing a correct if statement.
Instead of doing that:
if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )
Do something like this:
if(!isset($_SESSION['usernameerr']) && !isset($_SESSION['passworderr']) && !isset($_SESSION['phoneerr'] && !isset($_SESSION['mailiderr'] && !isset($_SESSION['cityerr'])))
Should work.
Another think I'm advising is to unset the sessions of the errors, in your case I would do that in the end of the Login.php page. Just in case, so there won't be any problems if you fix the form inputs and submit it again.
Another thing, based on the unset idea. If you will do this, it would be much more cleaner way to change the setting of the error sessions instead of:
$_SESSION['cityerr']
to:
$_SESSION['errors']['cityerr']
So afterwards, you can clean the specific form error session in one command, like that:
unset($_SESSION['errors']);
Hope it helped ;)
if(isset($_POST['field_name']))
{
$field_name=$_POST['field_name']
}else
{
unset($_POST['field_name'])
}
I'm new to PHP and I'm trying to handle a form so I added a if condition to check if the submit button was pressed and if the other elements in the form are set. For some reason it causes the page to not load (it loads, but shows a blank page) so I can't actually submit anything..
When I tried removing the php code, it loaded fine. What am I doing wrong here?
<body>
<?php
if(isset(filter_input(INPUT_POST, 'aglogin')) && isset(filter_input(INPUT_POST, 'agname')) && isset(filter_input(INPUT_POST, 'agpass')))
{
echo 'Submitted..';
}
?>
<form method="post">
Username: <input type="text" id="agname" name="agname"/>
<br>
Password: <input type="password" id="agpass" name="agpass"/>
<br>
<input type="submit" id="aglogin" name="aglogin" value="Login">
</form>
</body>
Do not use isset(); because filter_input() returns true if variable is set and return false if it is not set.
<body>
<?php
if(filter_input(INPUT_POST, 'aglogin') && filter_input(INPUT_POST, 'agname') && filter_input(INPUT_POST, 'agpass'))
{
echo 'Submitted..';
}
?>
<form method="post">
Username: <input type="text" id="agname" name="agname"/>
<br>
Password: <input type="password" id="agpass" name="agpass"/>
<br>
<input type="submit" id="aglogin" name="aglogin" value="Login">
</form>
You could try this
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
$valid=( array_key_exists('aglogin',$_POST ) && array_key_exists('agname',$_POST ) && array_key_exists('agpass',$_POST ) ) ? true : false;
if( $valid ) echo "Form submitted successfully";
}
?>
Hello, I am having trouble with some of my code. Even my teacher can't help me, and I don't know where else to go. When my foreach loop is activated and the password and username are the same as the hard-coded strings, it is still redirecting to loginerror.php. When I remove header("Location: loginerror.php"), it functions fine. Why is the last line of my code still activated, when it should load a new page?
<?php session_start(); ?>
<html>
<header></header>
<body>
<form action="login.php" Method="post">
Username: <input type="text" name="Username"> </br></br>
Password: <input type="password" name="Password"> </br></br>
<input type="submit" value="Login"></br></br>
</form>
<?php
$username=$_POST["Username"];
$password=$_POST["Password"];
if($username == NULL){print("Enter a Username please");}
else {
$users= array
(
"Bourne"=>"postcode",
"Unidan"=>"pincode",
"yoda"=>"sith"
);
foreach($users as $user=>$password_value)
{
if(($user==$username)&&($password_value==$password))
{
$_SESSION['login?']=1;
header("Location: calculation.php");
}}
$_SESSION['login?']=0;
header("Location: loginerror.php");
}
?>
</body>
</html>
Per the PHP Docs:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called.
Reference: Header Documentation
Move your PHP code to the top of the file and it should solve your problem:
<?php
session_start();
$username=$_POST["Username"];
$password=$_POST["Password"];
if ($username == NULL) {
print("Enter a Username please");
} else {
$users= array("Bourne"=>"postcode", "Unidan"=>"pincode", "yoda"=>"sith");
foreach($users as $user=>$password_value) {
if(($user==$username)&&($password_value==$password)) {
$_SESSION['login?']=1;
header("Location: calculation.php");
// Add this to terminate the script immediately and redirect.
exit();
}
}
$_SESSION['login?']=0;
header("Location: loginerror.php");
// Add this to terminate the script immediately and redirect.
exit();
}
?>
<html>
<header></header>
<body>
<form action="login.php" Method="post">
Username: <input type="text" name="Username"> </br></br>
Password: <input type="password" name="Password"> </br></br>
<input type="submit" value="Login"></br></br>
</form>
</body>
</html>
Header's must be sent before any output, including HTML output.
exit so no other code is executed after the redirect:
header("Location: calculation.php");
exit;
Changing your code structure to something like this may help you.
Note: this is not code correction.
<?php
session_start();
$username=$_POST["Username"];
$password=$_POST["Password"];
if($username == NULL){
print("Enter a Username please");
}
else {
$users= array
(
"Bourne"=>"postcode",
"Unidan"=>"pincode",
"yoda"=>"sith"
);
foreach($users as $user=>$password_value)
{
if(($user==$username)&&($password_value==$password))
{
$_SESSION['login?']=1;
header("Location: calculation.php");
exit;
}
}
$_SESSION['login?']=0;
header("Location: loginerror.php");
exit;
}
?>
<html>
<header></header>
<body>
<form action="login.php" Method="post">
Username: <input type="text" name="Username"> </br></br>
Password: <input type="password" name="Password"> </br></br>
<input type="submit" value="Login"></br></br>
</form>
</body>
</html>
Like it was mentioned prior. You are already outputting prior to sending headers.
You need to wrap this in a conditional or have a second script checking the password.
You could wrap the code in if/else $_POST as well as break operation in foreach after the condition was met.
I'm genuinely stuck on something VERY irritating. After a couple of hours of trying everything I know I've ended up here to see if anyone can help. Here's the general idea.
I want one certain page to be available with a password sent via a form. There is no user, and the password will not change. This should be easy, right!
I've got a form which submits with the method set to post, and the action set to $_SERVER['PHP_SELF']. The plan is, when the password variable I've pre-defined matches what is typed in the form, one set of content shows on the page, when it doesn't you get a different set of content (a form).
Here's what's weird. When looking at a print_r I see whatever I submit in the form in the array, but when I put the right password in the array fills, then empties quickly. I see this on the page reload. It completely empties itself. Even stranger, the 2nd time I do this, it works. What am I missing here? I'd love to know!
Many thanks, and Merry Christmas.
---- some code ----
The form
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="pass" id="pass">Password:</label>
<input type="text" name="pass" id="pass" />
<input type="submit" name="submit" value="Yes" />
</form>
Some PHP from the top of the file;
$pass = '12846565488374';
if($_POST['pass']){ $login = $_POST['pass']; } else { $login = 'empty'; }
if($login != $pass) { $show = 0; } elseif($login == $pass){ $show = 1; }
----- solved ------
Turns out this was a JS plugin reloading the page without me knowing.
Try:
if(isset($_POST['pass']) AND $_POST['pass'] == $pass) {
$show = 1;
} else {
$show = 0;
}
Copied from the comment below:
PHP can't update anything after the page is loaded from the server... You can only use refresh or JS/AJAX to change the content. It would be much easier if you uploaded the whole page somewhere.
Try:
<?PHP
if(isset($_POST['pass'])
{
$pass = '12846565488374';
($_POST['pass'] == $pass)? $show = 1 : $show = 0;
echo $show;
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="pass" id="pass">Password:</label>
<input type="text" name="pass" id="pass" />
<input type="submit" name="submit" value="Yes" />
</form>
<?PHP
}
?>
<?php
if (isset($_POST['pass']))
{
if ($_POST['pass'] == $pass)
{
$show = 1;
echo $show;
}
else
{
$show = 0;
echo $show;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="pass" id="pass">Password:</label>
<input type="text" name="pass" id="pass" />
<input type="submit" name="submit" value="Yes" />
</form>
perhaps something like this?
the purpose for the echo is to show when the correct password is entered, $show changes to 1 and when wrong, changed to 0
Edit:
Your Parameters Checking for $show
<?php
if (isset($show) AND $show === 1)
{
echo "The Variable Is Set To 1";
}
elseif (isset($show) AND $show === 0)
{
echo "The Variable Is Set To 0";
}
?>
This is tested and working with your code.
Thank you for your help everyone - as Matanya said, it was indeed a Javascript issue that was reloading the page. It's a music player and it was placed the "true" part of the IF statement. I don't understand why it has this effect, but at least I know. I thought the error would be in my PHP. Here's the player in question: SCM Music Player http://scmplayer.net
Thanks again.