I am trying to make a "form" of the type "text" which will check whether an email is valid or not. I first tried to check if the text field was empty by making an if statement, but it didnt work, and it instead ran the "else" option of the statement. How do I fix it so it actually checks if the text field is empty? Here is the code.
INDEX.php:
<?php
include 'connection.php';
echo "<p> Example Text </p>";
?>
<h1> Submit email address </h1>
<form action = "create.php" method = "post">
<input type ="text" name = "email" value = "" />
<br />
<input type = "submit" name = "submit" />
</form>
Create.php :
<?php
include 'connection.php';
$email = $_POST['email'];
if(!isset($email)){
echo "please fill out the form";
header ('Location: index.php');
}
else{
echo "Successive login";
}
?>
When doing:
$email = $_POST['email'];
You are in fact setting $email so the !isset() will return false (meaning that it is NOT not isset)
instead you need to check if it is not empty
if(!empty($email)){
}
else{
}
================
EXTRA
Here is an example of how how you can check valid email addresses:
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
Also check out my PHP function that checks to see if the email is valid and can receive emails by connecting to the mail server and verifying it:
https://github.com/hbattat/verifyEmail
I did that. It did work when I removed the header code as well, but I
want the echo to be displayed in index.php rather than in a new page
(create.php). How do i do that? – tomSurge 3 hours ago
When you submit to the create.php basically you load the create.php page with some post parameters. So anything you display there will not be displayed in index.php because you are not in the same page.
Instead you could post to the same page index.php and do the create process there:
<?php
include 'connection.php';
if($_SERVER['REQUEST_METHOD'] == 'post'){ //check if the page was requested via post method (that means the form was submitted)
if(!isset($email)){
echo "please fill out the form";
}
else{
echo "Successive login";
}
}
echo "<p> Example Text </p>";
?>
<h1> Submit email address </h1>
<form action = "index.php" method = "post">
<input type ="text" name = "email" value = "" />
<br />
<input type = "submit" name = "submit" />
</form>
OR
You could use AJAX and not load the page when posting the info to create.php and just display the response message:
<?php
include 'connection.php';
echo "<p> Example Text </p>";
?>
<!-- include jQuery in the header of your html -->
<script src="LINK TO jQUERY .js file"></script>
<script type="text/javascript">
$(document).ready(function(){
//trigger this when the form is submitted
$('form').on('submit', function(e){
//prevent default submission and reload of the page
e.preventDefault();
//post the date to the create.php file using ajax
//get the form data
var formData = $(this).serialize();
$.post('create.php', fomrData, function(response){
var result = parseJSON(response);
$('#msg').text(result.msg);
}
});
});
});
</script>
<h1> Submit email address </h1>
<form action = "create.php" method = "post">
<input type ="text" name = "email" value = "" />
<br />
<input type = "submit" name = "submit" />
</form>
create.php
<?php
include 'connection.php';
$email = $_POST['email'];
$result = array();
if(!isset($email)){
$result['status'] = 'fail';
$result['msg'] = "please fill out the form";
}
else{
$result['status'] = 'success';
$result['msg'] = "Successive login";
}
//echo the json
echo json_encode($result);
?>
isset() only checks if the variable is set. You need to use empty($email) instead.
Replace isset with empty and it should work as you want.
If I understand your question, you have to change the statement to if(!empty($email)) Also, if you want to check if the email is in the correct format, please use a regex to do so. isset() only checks for null
You can also test for submission of something (anything) in the posted email field with:
'' == $_POST['email']
As others have suggested, empty($_POST['email']) works too, just showing another option.
Displaying the Error Message
If you want the error message to appear on index.php then you need to pass the message or some sort of flag from the create.php page (where the error is discovered) to the index.php page (where the error message is displayed).
To demonstrate a bare-bones example (one of many ways to accomplish this), first I added a PHP variable to the form. Notice the line containing echo $_GET['error']; immediately after the email input element:
index.php (form):
<form action="create.php" method="post">
<input type="text" name="email" value="" />
<?php if (isset($_GET['error'])) { echo $_GET['error']; } ?>
<br />
<input type="submit" name="submit" />
</form>
...and, instead of echo'ing the message in the create.php script, send the message along to the index.php script in the URL query:
create.php (email check):
if ( '' == $_POST['email'] ) {
header('Location: index.php?error=please+fill+out+the+form');
}
Additionally, I recommend you use this (PHP server-side validation) as a backup to a Javascript client-side validation solution. Nicer for your website visitors and uses fewer server resources.
Another way is to just add a required="" to your input Here is an example https://jsfiddle.net/57s38s2e/
Related
I am doing a school project which require me to create a buy & sell website.
I have a form for user to input values such as name, email, etc. After it is filled up, they will press "submit" button, and the values will be written to my txt file.
However, I realized that, empty data are being written into the txt file as well, causing my text file to look like this
It happens when user click on the navigation button to access the form. Even when no values are entered. Empty spaces are written to my txt just by accessing the form.
Below is my code.
<?php
// define variables and set to empty values
$sellerNameErr = $emailErr = "";
$sellerName = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["sellerName"])) {
$sellerNameErr = "Name is required";
}else {
$sellerName = test_input($_POST["sellerName"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
}else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form name="sell" action="" method="post">
<p><span class = "error">* required field.</span></p>
<p>Seller Name: <input type="text" name="sellerName" />
<span class = "error">* <?php echo $sellerNameErr;?></span></p>
<p>Email: <input type="text" name="email" />
<span class = "error">* <?php echo $emailErr;?></span></p>
<input type="submit" name="Submit" value="Submit" />
<?php
$fp=fopen("buynsell.txt", "ab");
fwrite($fp,"$sellerName\t $email\r\n");
fclose($fp);
?>
</form>
How can I prevent empty data from being added to my log file?
Before writing to the file, you need to verify that $sellerName and $email have values and that there were no errors.
if ($sellerName && $email && !$sellerNameErr && !$emailErr) {
$fp=fopen("buynsell.txt", "ab");
fwrite($fp,"$sellerName\t $email\r\n");
fclose($fp);
}
The way you have it written now you don't need to do anything to check that those variables are set because you're initializing them all to empty strings, but if you change that, you should use empty()/!empty() instead to avoid undefined variable notices.
If you move the file writing PHP code inside the post handling code at the top so that it will only run when the form has been posted, after the validation code that checks if the inputs are empty, then you should be able to just check for errors only. if (!$sellerNameErr && !$emailErr) { .... Personally, I think it makes more sense for it to be there anyway. It's easier to read if all your PHP code is together, and there's no need for that code to be down there in the form.
Mark, there are many ways to prevent that empty data does not get into your business logic.
As for your project the most simple way to achieve this would be to set an additional attribute within your html markup.
As for HTML5 this could by your first solution:
<input type="text" name="usrname" required>
https://www.w3schools.com/tags/att_input_required.asp
Not that really efficient as only on client side, so you should also implement this on your server side.
empty($_POST['user']) will not work as you are never posting that value, therefore you must add an value attribute to your input field:
<input type="text" name="user" value="" />
If for example a username isn't filled in the user is given an error stating so, but after pressing submit they're thrown to another page with the error.
How would I go around keeping the error on the same page as the registration form and keeping all the text entered by the user after submit?
Registration PHP:
<?php
require 'db_connect.php';
$count = 0;
if (isset($_POST['username']))
{
$username = $_POST['username'];
if (!empty($username))
{
$count++;
}
else
{
echo 'Please enter a username';
echo "<br>";
}
}
if (isset($_POST['email']))
{
$email = $_POST['email'];
if (!empty($email))
{
$count++;
}
else
{
echo 'Please enter an email';
echo "<br>";
}
}
if (isset($_POST['password']))
{
$password = $_POST['password'];
if (!empty($password))
{
$count++;
}
else
{
echo 'Please enter a password';
echo "<br>";
}
}
if(strlen($username) > 25)
header('Location: registration.php');
$hashword = password_hash($password,PASSWORD_DEFAULT);
if($count == 3 )
{
$query = "INSERT INTO member ( username, password, email)
VALUES ( '$username', '$hashword', '$email');";
header('Location: login.html');
}
else {
echo '<b>You will be redirected shortly</b>';
echo "<br>";
echo '<b>Please enter ALL details correctly</b>';
header( "refresh:5;url=registration.php" );
}
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
?>
Registration Form:
<!doctype html>
<html lang="en">
<head>
<title>Gumby template file</title>
<meta charset="utf-8" />
<script data-touch="gumby/js/libs" src="gumby/js/libs/gumby.min.js"></script>
<script src="gumby/js/libs/jquery-2.0.2.min.js"></script>
<link rel="stylesheet" href="gumby/css/gumby.css">
<script src="gumby/js/libs/modernizr-2.6.2.min.js"></script>
<link rel="stylesheet" href="forumhomepage_style.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
</head>
<body>
<form name="register" action="register.php" method="post">
<tr>
<td>Username: </td>
<td><input type="text" name="username" maxlength="25" /></td>
</tr>
<tr>
<td>Email: </td>
<td><input type="text" name="email" id="email" /></td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Register" /></td>
</tr>
</table>
</form>
</body>
</html>
It depends on at what level do you want to do this.
Validating that the different data is not empty and has information that makes sense (like the password is at least 7 chars long) can be done via javascript before sending the form data, this way you can stop the form to be sent. You can use jQuery Plugin Validator to help you do this.
But other validations like the insert has failed only can be done at server side, if you need also not to redirect in this case then you have to use ajax to load the data and then refresh the website info without reloading it.
I prefer to only do an initial check with javascript and send the user to the results page. But I also keep the validations as this one of the password length in the php because, even though now a days it's really strange, a user can disable javascript and I don't wana have surprises when checking the database values. But, another example, if you have lots of users you could check that the user does not exist to warn the user at the very first moment before the form is sent and this can only be done performing an ajax call.
You should know how to do both things and decide depending on what you want to do on your projects.
In your case, I would leave the php validations as they are now and check the same (non empty values) in javascript on the form submit event calling event.preventDefault() if an error has been detected.
$('form[name="register"]').submit(function( event ) {
if ($('input[name="username"]').is(":empty")) {
// append a "Username can not be empty message somewhere on your page
event.preventDefault();
}
// I let you finish the jquery code...
});
This example uses jQuery lib. but you can do it without it with just javascript if you want.
There are several ways to do this. The first step is using the required attribute in your input elements:
<input type="text" name="username" required>
This will force the user to at least put something inside the input element. Then there's Javascript or jQuery for client side validation. You can create a custom event handler to catch the form submit and validate the input like so:
document.getElementById("your_form_id_here").addEventListener("submit", function(e){
// Your Javascript validation code here, for example:
var x = document.forms["your_form_id_here"]["username"].value;
if (x == "") {
alert("Username must be filled out");
e.preventDefault();
}
});
You can also put the form handler on the same file as the form and display the errors / values in case something goes wrong. For example:
<?php
if(!empty($_POST['submit'])){
$error = false;
if($_POST['username'] === ''){
$usernameEmpty = 'The username was empty. Please enter a username!';
$error = true;
}
if(!$error){
// No errors found so proceed with the registration
}
}
?>
<form id="myForm" method="post" action="" accept-charset="utf-8">
<?php if(!empty($usernameEmpty)){ echo $usernameEmpty . '<br/>'; } ?>
Username: <input type="text" name="username" value="<?php if(!empty($_POST['username'])){ echo $_POST['username']; } ?>"/>
<input type="submit" name="submit" value="Register"/>
</form>
Lastly there's of course Ajax which will allow you to send the form towards PHP without reloading your page. You could have PHP send the errors back and use Javascript to show the errors inside the DOM.
without ajax you will need ro lead your page with some conditional logic. This will look and see if any fields are filled in and fill them in again, along with setting any error messages to return to the user.
something like:
<?php
//example fields
$username = '';
$field2 = '';
$field3 = '';
if(isset($errorToShow)){
// echo your error message here
}
if($_POST["submit"]){
foreach($_POST as $k=>$v){
$$k = $v;
}
}
// your form can be here.
of course there are other considerations and ajax is a better solution, but this type of thing can work just fine.
You may use ajax
Or if you don't know ajax
You can put all your code in one page and call $_POST indexes into the value of every input.
for ex.
<input type="text" name="username" maxlength="25" value="<?=$_POST['usename'];?>"/>
Or you may use "PHP $_SESSION"
Just store $_POST into $_SESSION
then call it from the html page
for ex.
<input type="text" name="username" maxlength="25" value="<?=$_SESSION['usename'];?>"/>
And the same idea for errors.
How can I refresh a page with a form on submission pending the outcome of the submitted data and display a result.
e.g I have a page with a form:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
The engine that handles the form is external, but required in the page:
require_once 'form_engine.php';
form_engine.php checks the input,
$success = "true";
$errorMessage = " ";
$name = $_POST['name'];
if ( $name == '') {
$errorMessage = 'Please enter your name';
$success = false;
}
else (if $success = true) {
// do something with the data
}
The form page contains the result:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<p><?php echo $errorMessage; ?></p>
Will the error message get displayed after the form is submitted incorrectly? Or do I have to use a session to store it?
You need something like this:
if (!isset($_POST['name']))
instead of
if ( $name == 'name')
UPDATE
Try this, it should give you the idea:
<?php
$errorMessage = false;
if (isset($_POST['submit'])) {
if (!isset($_POST['name']) || $_POST['name']=='') {
$errorMessage = 'Please enter your name';
}
else {
// do something with the data
echo "Success!!";
}
}
?>
<form method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="submit" name="submit" />
</form>
<p><?php if ($errorMessage) echo $errorMessage; ?></p>
Note: leaving out the action attribute will just submit the form to the current page
Note 2: The PHP here could very well be stored in another page. Using require() is the same as putting the code directly into the page.
You can use redirect on php side:
header('Location: www.mysite.com/index.php');
You seem to be a little confused in terms of the exact process that occurs in terms of rendering a page, as do some of those commenting. You do not need to use sessions to solve this problem. There is no need to store anything server-side between page requests because the user's browser with retain everything that you need, at least for this situation. My guess is the others took you mentioning an "external engine" and thought that the form would be submitting away to a different site/page.
form loops
Below is a diagram showing a typical form request loop:
You do not have to do this, as coding is as much about personal preference to anything else, but typically people will design their form to submit back to the same URI that generated it — as you seem to be doing in your example, by leaving the action attribute blank. By doing this, as long as you embed everything you wish to pass back to the server side within the form — each time the user submits — that information will be resent and be available in PHP.
Obviously you need to be wary of what information might constitute as sensitive, as this data should only ever be written into markup if your requests are protected by HTTPS/SSL. You should also filter/escape any user input to prevent markup injection into your site. You can prevent many problems by using htmlentities, however this can cause issues depending on the values you are trying to capture from the user. Because you are using double quoted HTML attributes (the right way to do them ;) I have not set the ENT_QUOTES option.
back to the point
So in the above loop the user will be shown the form for the first time, and after any subsequent submit, which means that each time your PHP notices that there is an error you can just add your message into the page flow. The trick with this kind of system is what exactly do you do once the form is fully complete. To get out of the loop most people will use a header location call:
<?php
require_once 'form_engine.php';
$name = !empty($_POST['name']) ? trim($_POST['name']) : '';
$name = htmlentities($name);
if ( $success ) {
header('location: next-step.php');
exit;
}
?>
<form action="" method="post">
<input type="name" value="<?php echo $name; ?>" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<?php
if ( $errorMessage ) {
echo "<p>$errorMessage</p>";
}
?>
form engine repairs
You should also rectify your form_engine.php as per my comments above and Shekhar Joshi's answer, although I would keep the header code outside of your engine logic, and leave that decision to the code that requires in the engine — as the above does.
may be, you are looking for this! the header() method.
$success = true;
$errorMessage = " ";
$name = $_POST['name'];
if(isset($_POST['name'])) {
if ( $_POST['name'] == '') {
$errorMessage = 'Please enter your name';
$success = false;
header('Location: www.something.com/some.php');
}
else if ($success == true) {
// do something with the data
}
}
I am looking to develop a website containing stages. I want for example to pass by the stage 2 only when i click on the finish button in the page of stage 1 so the stage 2 page can't be accessible by its url or whatever only if the user pass by another page.
Is there a method to do this ??? i am a beginner in security so please try to help me, thanks in advance coders
Make use of sessions to develop this model.
index.php
<?php
#extract($_POST);
if(isset($sub))
{
session_start();
$_SESSION['authenticate']=true;
header("location:test1.php");
exit;
}
?>
<form action='' method="post">
<input type="SUBMIT" name="sub" value="Finish" />
</form>
open.php
<?php
session_start();
if(!isset($_SESSION['authenticate']))
{
echo "You are not allowed to access";
}
else { echo "You came from index.php ! so you are a valid user"; }
session_destroy(); //<-- I added this so you can test your example multiple times.
I think, this show work :)
Use can either redirect your user directly from index.php to open.php
header('Location : open.php');
Or,
in open.php, put this
if($_SERVER['HTTP_REFERER'] == 'index.php page's full link') {
//Do or Show whatever you want to show here
} else {
// Tell the user that you are not authorized
}
If that doesn't work, echo $_SERVER['HTTP_REFERER'] and see what link it gives you. And put that link where specified above.
Cool? :)
Edit (As per the comments) --
Lets say you have a form in your form in stage1.php
<form method="post" action="">
<span class="error"><?php echo $error; ?></span>
Name: <input type="text" name="name"><br/>
Email: <input type="text" name="email"><br/>
<input type="submit" name="submit" value="Submit">
</form>
use this php in stage1.php
if (isset($_POST['name'])||isset($_POST['email'])) {
if (!empty($_POST["name"])||!empty($_POST["email"])) {
$error = "Please fill in all the fields correctly";
}
else {
$name = $_POST['name'];
$email = $_POST['email'];
//You can also save the above Variables Globally by $GLOBALS['name'] = $_POST['name'];
//So that you can use the details when you reach the final stage
header('Location : stage2 page's link');
}
}
?>
and in Page 2 lets say you have another form, then there also check
<?php
if(!empty($name)||!empty($email)) {
//the above is check for global variables email and name are not empty - means stage 2 was filled properly
//Do things for the second page's form like you did for stage 1
} else {
header('Location : stage1 page's link');
//redirect back to stage 1.
}
?>
This is a simple Captcha form which is working well and prints the requested result after I press ‘submit’.
<?php
session_start();
$msgCaptcha = "";
?>
<?php
if (isset($_POST['submit'])){
$secCode = isset($_POST['secCode']) ? strtolower($_POST['secCode']) : "";
if ($secCode == $_SESSION['securityCode']) {
$msgCaptcha = "valid code";
$result = true;
}
else {
$msgCaptcha = "wrong security code";
$result = false;
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
name:<input name="myname" type="text"><br />
Security code: <input class="text" name="secCode" type="text">
<img src="securityCode.php" /><br />
<?php echo $msgCaptcha ?>
<input name="submit" type="submit" value="submit">
</form>
. i.e.
If my input is the same as like in the picture the printing is “valid security code”
and if the input is not the same, the printing is “wrong security code”.
When I change in the form the code to action="mailer.php" this file is opened but ignore of any input in the Captcha validation.
I need mailer.php to be open after Captcha validation.
I have tried onsubmit and some other options, but none of them works as a solution for the above.
Any help would be greatly appreciated.
You could try to include mailer.php after the $msgCaptcha = "valid code"; line.
Any code inside mailer.php would be executed in that block of code, and any $_POST variables required by mailer.php would be available.
The bottom line is, when you call mailer.php, you must have captcha validation in front of that file, otherwise any bot/spammer can bypass your captcha protection just by submitting the form directly to mailer.php
Keep in mind, bots generally ignore javascript, so the validation has to be done server side.
You may want to set a variable prior to including mailer.php that it will check so even if someone did try to directly submit to mailer.php, it won't process the form unless the file was included.
If this doesn't help, post the code for mailer.php so we know what the contents of that file are.
Use header()
if ($secCode == $_SESSION['securityCode']) {
$msgCaptcha = "valid code";
header("Location: http://www.website.com/ ... /mailer.php");
}