How to avoid the alert after the first time loading the page - php

I want to check if the form was filled out correctly but the alert appears after I load the page. I guess a site refresh is submitting the login button.
I try to check the incoming data and if they are wrong, it should show an alert.
<?php
$alert = "";
if ($_POST['username'] == null || $_POST['password'] == null){
$alert = "Please fill in all fields!";
}
if ($alert){
echo $alert;
}
?>
<form method="POST" action=""> <!-- reloads this page -->
<input type="text" name="username"/>
<input type="password" name="password"/>
<button type="submit" name="login">Login</button>
</form>
If I open the page, the alert appears instantly. How should I do the check, that the alert does not appear after the first load.

I hate to suggest javascript as the solution, but in this case, javascript is the best solution.
With javascript, you can interrupt the form submission process - do some stuff (such as validate the form fields) and then either return false (cancels the submit) or do nothing (the form submission will continue). But Barmar is straight-on correct with his explanation of what is happening. (Of course he is: it's Barmar )
So the overview is:
Use $('#yourFormID').submit(function(){}) to trap the form submission process
Inside that function, perform your field validation
If a field fails validation, display a message and return control to the user
If all fields validate okay, do nothing else - the form will finish submitting as if there was no interruption at all.
Here is another question/answer that demonstrates how to do that.
How to direct a user directly to a form

The IF-Statement is fine, so your problem is in your Session or Cache.
You can destroy your Session, if you close your browser, but this maybe need some time to destroy the session, so you could delete cache, cookies, etc in your browser setting.
But you can also use session_destroy(); in php to destroy all Variables of POST or GET.

Related

Smooth login without javascript

What i want: clicking on login / pressing on enter will validate the login and redirect if correct (without javascript).
What i tried:
A form with a submit button and validating on an other php page PROBLEM: if login is not correct, i don't want to redirect and display an error message instead.
<form action="loginServerside.php" method='POST'>
A form with a submit button and validating when the submit button is set.
PROBLEM: submit button reloads page and then redirects if login was correct
<form method='POST'>
<input name="email" type="email" id="email" placeholder="Email" />
<input name="pass" type="password" id="pass" placeholder="Password">
<input type="submit" name='login' value="LOGIN" id="login" class="button"/>
</form>
if (isset($_POST['login']))
/*validate*/
Trying to prevent the page reload by using an input type="button" PROBLEM: the isset only works for submit buttons
I would appreciate the help!
You can't run server-side code (login credentials validation, in this case) without reloading the page. This requires AJAX, which involves Javascript.
If i understand your question correctly, You want to validate the users input without a page reload or refresh, Doing this without client side scripts is as far as i know Impossible. Once PHP (Pre Hypertext Processor) has finished playing with your code its then sent to the client and PHP "Goes to sleep" until another page is loaded. Javascript is the best way to achieve your desired result. This isnt really an answer i guess but what your trying to do is act upon data that has not been sent to the server using only a server side technology. It is not possible.
Javascript can be a pain in the rear but there are tools out there now that make debuging simple Chrome even has a dev console built in that takes sme of the pain out of it.
For a login to take place, the client (browser) has to POST to the server and then receive a response. If you want that response to be something other than a full-page reload, you will need javascript in order to fetch JSON, or a page fragment via AJAX, or a signal over websockets, or a data channel through WebRTC or some other mode of full-duplex communication not in any way supported by normal request flow standards.
If it's just a matter of keeping something on the screen through that page reload, look up iframes.
Check this tutorial... It has everything you need.
http://www.phpeasystep.com/phptu/6.html
Query the db for the count of results for the post values - If value is 1 login is success, else displays the error message
if( $count==1 ){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("email");
session_register("password");
header("location:[name_of_your_success_page.php");
}
else {
echo "Wrong Username or Password";
}

How to make a form submit only on button click not on refresh?

I have a form where i should make the form submit(request to a service) only if the form field is changed, If the field is not changed when the user refresh the page it should not submit the form again.
OBJECTIVE is to reduce the number of form submission as possible, So if the user has the same entered data and he refresh, we shouldn't waste the previous returned datas and try to give new request and show the same datas.
Instead it should be submitted only if the TEXT(searchdirectory) is changed. So there won't be repeating request for same datas.
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<label>TEXT :</label>
<input type="text" id="search_dir" name="searchdirectory"
value="<?php
if (isset($_POST['searchdirectory']))
{
echo($_POST['searchdirectory']);
}
?>"
/>
<input type="submit" value="Search" name="submit" id="searchB"/>
<?php
if (isset($_POST['submit']))
{
//functions to show results queried from searchdirectory
}
?>
</form>
I guess this would be to deal with refresh behaviour of browsers, Is there a way to stop the form submission if user refresh the page. It should show the same datas.
Use redirect when form data was sent at first.
<?php
if (isset($_POST['submit']))
{
//do function
header("Location: http://". $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
?>
Where "http://". $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] - is a link to which the user will be redirected after form submit.
There is two ways to go. But I try to address your objective, and not your specific question :)
You can forward the browser to a new url after form submit. This is a very normal procedure. So that when your form submits the browser redirects immediately to a normal GET URL. Now if the user hit refresh the form is not submitted again.
2 The other approach that you should use if the form is login dialog etc. Add a one time session key to a forms hidden field, and store the same key in on the server. Now if the user submits the form check that the keys match. If they do accept the submit, and clear the key. If the user now hit F5 again, and you've already removed the key, simply reject the values submitted.
why don't you clear the form after submitting, or add session for each submit request

unset form submit button

<body>
<?php
if(isset($_POST['vendor_add_submit'])){
//INSERT INTO DB
unset( $_POST['vendor_add_submit'] );
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>" >
<label>Email</label>
<input type="text" name="vendor_email" value="" />
<input type="submit" name="vendor_add_submit" value="SAVE" />
</form>
</body>
unset( $_POST['vendor_add_submit'] ); is used to prevent more than one time insertion into db on page refresh. I tested with print_r($_POST['vendor_add_submit'] ) before and after the unset and found that the unset() function does not work.
How can I achieve the purpose of the unset function, plz?
Unset isn't going to stop the refresh from being able to replay the POSTed data to the script. The unset function eliminated it for the remaining execution of that script, but a refresh is a fresh execution.
You could simply re-direct the browser to the entry pageafter doing your insert, that way a subsequent refresh will be safe.
//INSERT INTO DB
//...
header('Location: samepage.php');
exit();
I'm sure there are other ways to accomplish this as well.
Your approach cannot work, you would just be editing the data that the PHP script has recieved. If the user refreshes the browser then it will submit the same data again, and PHP will populate a fresh new $_POST with the data the browser sent.
If you want to stop a refresh resubmitting the data, then use the POST-REDIRECT-GET pattern.
The $_POST value will only be removed on the Server-Side Meaning that on that one request PHP will not be able to see or use it (You removed it).
But you are rendering the Submit button on the page's HTML so every time someone visits the page and submit the form they will submit the value again. And you will remove it again for PHP on that current request. So every request would insert the data into the database.
You might want to rather look into rather checking if the record already does exists (OR if the user has one already, not sure what you want) and then redirect them away from the page using header('Location: otherpage.php');.
Hope that helps...

Same page processing

How can process a form on the same page vs using a separate process page. Right now for signups, comment submissions, etc I use a second page that verifies data and then submits and routes back to home.php. How can I make it so that on submit, the page itself verifies rather than using a second page.
You can tell the form to submit to the PHP's self, then check the $_POST variables for form processing. This method is very good for error checking as you can set an error and then have the form reload with any information the user's previously submitted still in tact (i.e. they don't lose their submission).
When the "submit" button is clicked, it will POST the information to the same page, running the PHP code at the top. If an error occurs (based on your checks), the form will reload for the user with the errors displayed and any information the user supplied still in the fields. If an error doesn't occur, you will display a confirmation page instead of the form.
<?php
//Form submitted
if(isset($_POST['submit'])) {
//Error checking
if(!$_POST['yourname']) {
$error['yourname'] = "<p>Please supply your name.</p>\n";
}
if(!$_POST['address']) {
$error['address'] = "<p>Please supply your address.</p>\n";
}
//No errors, process
if(!is_array($error)) {
//Process your form
//Display confirmation page
echo "<p>Thank you for your submission.</p>\n";
//Require or include any page footer you might have
//here as well so the style of your page isn't broken.
//Then exit the script.
exit;
}
}
?>
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
<?=$error['yourname']?>
<p><label for="yourname">Your Name:</label><input type="text" id="yourname" name="yourname" value="<?=($_POST['yourname'] ? htmlentities($_POST['yourname']) : '')?>" /></p>
<?=$error['address']?>
<p><label for="address">Your Address:</label><input type="text" id="address" name="address" value="<?=($_POST['address'] ? htmlentities($_POST['address']) : '')?>" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
The easiest construction is to detect whether the $_POST array is not empty
if(isset($_POST['myVarInTheForm'])) {
// Process the form
}
// do the regular job
you can check if it was POST request inside the page's code and then check the data. If it was GET request - just show the form.
But please remember that is is a good practice to show successfull form submission results on a different page served through GET request, i.e. any successfull form POST should be answered with redirect to the success page.
You could of course explore looking into AJAX requests, where you would make an asynchronous call to your handler script, and then update then update the sending page with a success message. This gives the impression of "Same page processing" i.e. The page doesn't have to refresh.
It really depends on the effect you are trying to achieve however.
#Michael Irigoyen: It works fine, but on first rn/load, it shows:
"Notice: Undefined variable: error in C:\xampp\htdocs\same_page.php on line 28"
How to handle this notice?
Got it now:
"Used isset, # etc. to supress errors..."
"Works like a charm!!!"
"Now i'll try it on my code..."
I have saved a thank you message and refreshed using session variables.
if(!is_array($error)){
$_SESSION['message'] = 'Thank You!';
header('Location: yourpage.php');
exit();
}
and then use this in the top of the form:
if(isset($_SESSION['message'])){
echo $_SESSION['message'];
unset($_SESSION['message'];
}
This should refresh the page and show the message and then if they refresh the page the session variable is empty so the thank you won't show. This is called a flash message.

pass value from page to another in PHP

I am sending login status = fail, back to my login page.Here is my code-
header("location:index.php?login=fail");
but that is sending through URL like-
http://localhost/303/index.php?login=fail
is there any way to pass value without showing in URL? And how to get this value on the second page?
You are passing that value via a GET request, which is why it appears in the URL. In order to pass a value without showing it in the URL, you want to pass it via a POST request.
In order to do this you aren't going to want to "return" the value to your login page. Instead, whatever php form is handling the process of logging in the user after they click the "login" button, will decide what to show the user.
In PHP post variables can be accessed by the global $_POST object -
$_POST['username'];
Would get the value with the name "username" that you passed via POST:
<form method="post" action="checkLogin.php">
Username:
<input type="text" name="username" maxlength="25" />
Password:
</td><td><input type="password" name="password" />
<input type="submit" name="submit" value="Login">
</form>
In order to dynamically save and show errors to the user, you can store them in the session, for example have a file called "errors.php"
<?php
if (isset($_SESSION['errors']))
{
echo $_SESSION['errors'];
}
unset($_SESSION['errors'])
?>
And in your php that checks the login, do:
session_start();
$_SESSION['errors'] = "Invalid username or password.";
Then redirect to your login page (don't pass any variables) and on your form always have this field:
<?php include("errors.php"); ?>
If you didn't have any errors, it won't show anything and the login page will look normal.
Note: In any php form that you use a session_start(), it HAS TO BE THE FIRST THING in the form.
Other ways are to use session or hidden fields but you what you are doing is fine for the purpose. You can later retrieve the value like this:
if ($_GET['login'] === 'fail')
{
// failed.......
}
there are several ways to accomplish your task
Modern AJAX way. Form being sent using AJAX. No page reload until password is correct. Errors shown in place. Requres javascript.
Post/Redirect/Get pattern. Form being sent using regular POST. No redirect on errors, shown in place.
sessions, when we store an error in the session

Categories