I have a register email page, which uses referral id, but if no user doesn't get referred by anyone, then by a redirect, I use default af id = 1
with following code::
if ( !isset( $_GET['af'] ) && empty( $_GET['af'] ) ){
header('Location: register-email.php?af=1');exit();
}
Next Here is the form code:
<form class="form-horizontal" role="form" method="post" name="register_email" action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>">
<div class="form-group">
<label class="control-label col-sm-2" for="email">Email:</label>
<div class="col-sm-6">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<div class="g-recaptcha" data-sitekey="somecode"></div>
</div></div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<button type="submit" class="btn btn-warning" name="register-email">Register Email</button>
</div></div>
</form>
Here is the background PHP part:
if (isset($_POST['email'],$_POST['g-recaptcha-response'],$_GET['af'])) {
$test="OK";
}
It never prints "OK", I tested the GET part its working fine not empty or null value. But email & g recaptcha part is null. I am not sure why. Previously it used to work without bootstrap integration.
Note: I didn't use echo $test = OK because I am printing this on other pages with echo statement, whole process includes two files,
register-email.php ( Here I am using the echo $test;)
register-email.inc.php (which includes the isset POST sections)
Try to echo $test. You just have stored it, you didn't printed it. And your condition is not even in right syntax.
There are several mistakes here. You cannot mix $_GET and $_POST, in this case, it must be all $_POST. When testing isset(), you cannot just use commas. How about the following:
if (isset($_POST['email']) AND isset($_POST['g-recaptcha-response']) AND isset($_GET['af'])) {
$test="OK";
}
If the above code does not work, check this out.
if(!isset($_POST['email']) echo "Email not set";
if(!isset($_POST['g-recaptcha-response']) echo "Recaptcha not set";
if(!isset($_POST['af']) echo "AF not set";
Now you can see if any of them is not set. Do keep in mind, for $_POST['g-recaptcha-response'] to have a value, a user must correctly answer the reCaptcha image test (Human test), and reCaptcha must be correctly implemented.
form action remove and change submit button name register_email. after add this php code.
if(isset($_POST['register_email'])){header('Location: register-email.php?af=1');exit();}
I solved my problem by myself after lots of debugging. The form was not working because of the redirect. So remove the code of redirect, in fact, use another type of safe coding in order to check if GET is variable is empty or not internally.
if (isset($_POST['email']) AND isset($_POST['g-recaptcha-response'])) {
if ( !isset( $_GET['af'] ) || empty( $_GET['af'] ) ){
$af_code = 1;
}
else {
$af_code = filter_input(INPUT_GET,'af',FILTER_SANITIZE_STRING);
}
}
Now its working safe & sound
Related
I am hoping the community can give me a little insight into what is not working with my code, I am following a Udemy course. I have followed the accompanying video which developed an undefined variable error, which after doing some research I believe I have fixed by declaring variables as empty strings being able to be over-ridden by the form data.
The form sends data to the database if both are completed, and if one of the fields is empty then it doesn't, which is as it should be.
If one of the fields is empty it should return a statement asking the user to enter data into the respective field, but nothing is being sent.
The only difference between the tutorial and my code is I have used the materialize framework, where the tutorial used bootstrap, but I can't see that being the issue.
I have attached my code, and commented out redundant parts.
<?php
include('php/connection.php');
//validates data for create user form
if( isset( $_POST["createUserBtn"])){
$createUsername = "";
$createUserPassword = "";
function validateFormData( $formData ) {
$formData = trim( stripcslashes( htmlspecialchars( $formData)));
return $formData;
}
if( !$_POST["createUsername"]){
$createUsernameError = "Enter a username <br>";
} else {
$createUsername = validateFormData( $_POST["createUsername"]);
}
if( !$_POST["createUserPassword"]){
$createUserPasswordError = "Enter a Password <br>";
} else {
$createUserPassword = validateFormData( $_POST["createUserPassword"]);
}
if( $createUsername && $createUserPassword) {
$query = "INSERT INTO users (user_id, userName, userPassword) VALUES (NULL, '$createUsername', '$createUserPassword')";
// if( mysqli_query( $connection, $query)){
// echo "New User added";
// } else {
// echo "Error: ".$query."<br>".mysqli_error($connection);
// }
}
}
?>
<!DOCTYPE html>
<html lang="en">
<?php require('static/header.php'); ?>
<?php
$createUsernameError = "";
$createUserPasswordError = "";
?>
<div class="col s8 m8 l5 valign-wrapper">
<div class="container">
<form action="<?php echo htmlspecialchars( $_SERVER["PHP_SELF"] ); ?>" method="post">
<div class="row">
<div class="col s12">
<span><h4>Create your user account - create user.php</h4></span>
<div class="row form-font">
<div class="col s12">
<div class="input-field">
<a class="red-text"><?php echo $createUsernameError; ?></a>
<input placeholder="Enter your username" type="text" name="createUsername">
<label for="email">Username</label>
</div>
<div class="input-field">
<a class="red-text"><?php echo $createUserPasswordError; ?></a>
<input placeholder="Enter your password" type="password" name="createUserPassword">
<label for="password">Password</label>
</div>
<div class="row left-align">
<div class="col s2"></div>
<div class="col s8">
<button class="btn-flat waves-effect waves-custom" type="submit" name="createUserBtn"><i class="material-icons left">create</i>Create Account</button>
</div>
<div class="col s2"></div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<?php require('static/footer.php'); ?>
</html>
Look carefully at your code and the places where you make use of - for example - the $createUsernameError variable.
If there's an error, you set a message in it with this line: $createUsernameError = "Enter a username <br>";. Great, just what you wanted.
However, later on in the code, you run $createUsernameError = "";, which resets it to empty again. And that happens in all circumstances, whether an error was identified or not. And it happens before you try to echo that variable onto the page.
So basically you're setting the value and then immediately blanking it again before you output it. You need to make sure it's only set blank in situations where there's no error. It's the same problem for the password error message.
An easy way to do that would simply be to set the value blank before you run the error checks. Then it'll stay blank if there's no error, but it won't overwrite any error messages which do get set.
So just move these lines:
$createUsernameError = "";
$createUserPasswordError = "";
to the top of your script.
P.S. Please pay attention to the security warnings posted in the comments and urgently fix your code to remove these vulnerabilities before using this code in any kind of live environment. Even if you don't plan to use this code for real, you should still fix these issues so that you learn to do things the correct, safe, reliable way and don't get into bad habits. If you copied this code from a course online, I suggest finding a better course.
$_POST won't recognize the value mailuid from the login form on this page or others (profile page).
$_Get methods do not work because of how the login system is built and unsecured.I need mailuid value to bring them to their own profiles page after login.
Login Form since its's post method I should be able to grab the value on other pages and this one
<div class="modal">
<div class = "modal-content">
<section class="section-default">
<h1>Login</h1>
<?php
if (!isset($_SESSION['Id'])) {
echo'<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="login-submit">Login</button>
</form>';
} else if (isset($_SESSION['Id'])) {
echo '<div class="signup12">
You Do not have an account? Sign Up
</div>
<div class="forgotpwd">
Forgot your password?
</div>';
}
?>
</section>
</div>
</div>
Temporary check for the mailuid value. Supposed to grab the value form the login form a spit it back out, to check to see if it is recognized
<?php
$user = $_POST["mailuid"];
if (isset($_POST["mailuid"]))
{
$user = $_POST["mailuid"];
echo $user;
echo " is your username";
}
else
{
$user = null;
echo "no username supplied";
}
?>
First I would clean this up:
$user = $_POST["mailuid"];
if (isset($_POST["mailuid"]))
{
$user = $_POST["mailuid"];
echo $user;
echo " is your username";
}
else
{
$user = null;
echo "no username supplied";
}
Instead it can be written more concise:
$user = isset($_POST["mailuid"]) ? $_POST["mailuid"] : false;
if( $user ){
echo "{$user} is your username";
} else {
echo "no username supplied";
}
I prefer Boolean false over NULL, null just means it doesn't exist. Boolean false lets you know you checked it and it didn't exist. Generally should should access $_POST as few times as you can. This is because you should never trust $_POST.
$_Get methods do not work because of how the login system is built and unsecured.
Post is no more secure than get, it's quite easy to post anything to the page even without visiting the site by using something like PostMan etc. Once you assign it to a local variable you know you have at least normalized the data, even if you haven't sanitized it yet.
Also don't forget to call session_start before trying to access $_SESSION. Because of the vagueness of the question, it could be that the form works fine, just the session data isn't being maintained because you haven't started the session yet.. etc....
Hope it helps.
Personally I would clean up the HTML part that makes the form as well, so instead of this:
<div class="modal">
<div class = "modal-content">
<section class="section-default">
<h1>Login</h1>
<?php
if (!isset($_SESSION['Id'])) {
echo'<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="login-submit">Login</button>
</form>';
} else if (isset($_SESSION['Id'])) {
echo '<div class="signup12">
You Do not have an account? Sign Up
</div>
<div class="forgotpwd">
Forgot your password?
</div>';
}
?>
</section>
</div>
</div>
I would do something like this:
<div class="modal">
<div class = "modal-content">
<section class="section-default">
<h1>Login</h1>
<?php if (!isset($_SESSION['Id'])){ ?>
<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="login-submit">Login</button>
</form>
<?php }else{ ?>
<div class="signup12">
You Do not have an account? Sign Up
</div>
<div class="forgotpwd">
Forgot your password?
</div>';
<?php } ?>
</section>
</div>
</div>
See how much cleaner that is. Most of this is just readability issues. For example there is no need to check if isset($_SESSION['Id']) in the else if condition, because it's either set or not. This is one less place to maintain the session variable key, and it makes the code less convoluted.
As for the actual problem, as long as you are reaching the above code after submission of the form, it should work. So that leads me to believe that you have something wrong in the action.
You should get a clean page after going to includes/login.inc.php meaning there shouldn't be much in the way of HTML. One thing you can do that is real simple is just add at the top:
die(__LINE__.' of '.__FILE__);
$user = isset($_POST["mailuid"]) ? $_POST["mailuid"] : false;
//... other code
What this will do is die which kills PHP execution, but outputs the argument you passed in. In this case I'm just putting the line and file that the die is on, that way it's easier to find later. But the point is to see if you are even hitting the correct ending script or the forms action/endpoint.
I only suggest this because you are really vague in what it's current behaviour is
$_POST won't recognize the value mailuid from the login form on this page or others (profile page).
For example, this doesn't tell me if you are even hitting the right page. Now had you said something like "all it does is output no username supplied". Then I would at lest know that. As I said above it could be just an omission of sesion_start() which must be called before attempting to access any $_SESSION stuff. You should call it only once, at the top of each page that uses sessions.
Although it's not a solution, it was too much to post in a comment. I would really like to help you more, but there just isn't enough information to go on.
I know its a duplicate one but i'm getting this error while trying to fetch data passed from a link..I dont know how to resolve it.
here is my code:
add_package.php
echo "<td><a href='delete.php?name3=" . $row['package_type']."&id3=".$row['p_id']."'>Delete</a></td>";
echo "<td><a href='edit_package.php?name3=" . $row['package_type']."&id3=".$row['p_id']."'>Update</a></td>";
here the delete link works perfectly but when i click update it takes to the edit_package page where i'm getting an undefined error..
code for edit_package.php:
<?php
include('db.php');
$id4 = $_GET['id3'];//update the page
$name4 = $_GET['name3'];//helps to update the package
echo $id4;
echo $name4;//getting values here correctly..
if(isset($_POST['submit']) )
{
$package=$_POST['package'];
if (ctype_alnum($package) && !empty($id4) && !empty($name4))
{
$sql13="select package_type,id from tbl_package where package_type='".$package."'";
$retvali=mysql_query($sql13,$conn);
$num_rows1 = mysql_num_rows($retvali);
if ($num_rows1 == 0 || $num_rows1=="")
{
$sql = "Update tbl_package set package_type='".$package."' where package_type='".$name4."' and p_id='".$id4."'";
$retval = mysql_query( $sql, $conn );
?><script>alert("Updated Successsfully");window.location ='http://localhost/demo/add_package.php';
</script><?php
}
else
{
?><script>alert("Already Exists");window.location ='http://localhost/demo/add_package.php';
</script><?php
}
}
else
{
?><script>alert("enter only letters and numbers")</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<form id="form-validation" action="edit_package.php" method="post" class="form-horizontal" enctype="multipart/form-data" novalidate="novalidate">
<div class="col-md-6">
<div class="block" style="height:500px;">
<div class="block-title">
<h2><strong>State the Package For Tour</strong></h2>
</div>
<fieldset>
<div class="form-group">
<label class="col-md-4 control-label" for="val_username">Update Package <span class="text-danger">*</span></label>
<div class="col-md-6">
<div class="input-group">
<input type="text" id="package" name="package" class="form-control" required >
<span class="input-group-addon"><i class="fa fa-user"></i></span>
</div>
</div>
</div>
<div class="form-group form-actions">
<div class="col-md-8 col-md-offset-4">
<input type="submit" class="btn btn-info btn-primary " value="Update" name="submit">
</div>
</div>
</fieldset>
</form>
When i press update button i'm getting an undefined error i dont know why?..Thanks in advance
I'm attaching an image to it..
Try to change the <form>'s action URL to include your GET varaibles:
<form id="form-validation" action="edit_package.php?id3=<?php echo $_GET['id3']; ?>&name3=<?php echo $_GET['name3']; ?>" method="post" class="form-horizontal" enctype="multipart/form-data" novalidate="novalidate">
PLEASE NOTE: This is extremely unsafe! You need to sanitize ALL user input before using it. My example above, dis-regards security, and simply is to demonstrate my point. GET and POST data, are user variables. A malicious user could put bad code in the URL (ie ?name3=<badcode>) and it would be printed on the page, well in the source code, which they could easily pop out of. Also, in SQL queries, you need to escape the data or use prepared statements.
You should not be using mysql functions, switch to MySQLi or PDO. MySQL has been killed for a while now..
These are just asking for you to get hacked:
$sql13="select package_type,id from tbl_package where package_type='".$package."'";
and..
$sql = "Update tbl_package set package_type='".$package."' where package_type='".$name4."' and p_id='".$id4."'";
You are vulnerable to SQL injections, would could easily allow a malicious attacker to add/edit/view/delete data in your database.
The problem is, you have $package (which is raw data from POST) and $id4 and $name4 (which is raw data from GET) in your SQL query.
You would use mysql_real_escape_string() on them, but you should be using mysqli or PDO anyways...
Example:
$name4 = mysql_real_escape_string($_GET['name3']);
It's confusing, I don't know what the GET variable is called name3 but you assign it the variable $name4.. Whoever (even you) comes along later on will be lost in your code.
Updated:
Try this code. I swapped your GET for POST in your php code, and passed the GET variables from your URL as hidden fields in your form.
<?php
include('db.php');
if(isset($_POST['submit']) )
{
$package = mysql_real_escape_string($_POST['package']);
$id4 = mysql_real_escape_string($_POST['id3']); // why is variable named id4 but its id3??
$name4 = mysql_real_escape_string($_POST['name3']); // why is variable $name4 but its name3??
if (ctype_alnum($package) && !empty($id4) && !empty($name4))
{
$sql13 = "SELECT package_type,id FROM tbl_package WHERE package_type='$package' LIMIT 1";
$retvali = mysql_query($sql13, $conn);
$num_rows1 = mysql_num_rows($retvali);
if ($num_rows1 == 0 || $num_rows1=="")
{
$sql = "Update tbl_package set package_type='$package' WHERE package_type = '$name4' AND p_id='$id4'";
$retval = mysql_query( $sql, $conn );
echo '<script>alert("Updated Successsfully");window.location = "http://localhost/demo/add_package.php";</script>';
} else {
echo '<script>alert("Already Exists"); window.location = "http://localhost/demo/add_package.php";</script>';
}
} else {
echo '<script>alert("enter only letters and numbers");</script>';
}
}
?>
<form action="edit_package.php" method="post" enctype="multipart/form-data" novalidate="novalidate">
<input type="hidden" name="id3" value="<?php echo htmlspecialchars($_GET['id3'], ENT_QUOTES | ENT_HTML5); ?>" />
<input type="hidden" name="name3" value="<?php echo htmlspecialchars($_GET['name3'], ENT_QUOTES | ENT_HTML5); ?>" />
Update Package: <input type="text" id="package" name="package" class="form-control" required >
<input type="submit" class="btn btn-info btn-primary " value="Update" name="submit">
</form>
I removed your HTML formatting from the form. You had div tags that didn't match up.. I can't see your whole code, but it looks like you have a bunch of div's that are messed up (ie: not closed where they should be). I also added mysql_real_escape_string() to the passed variables, and htmlspecialchars() to the GET variables echo'd in the hidden fields of your form. It's a start.
You might be able to make better sense of your code and troubleshoot errors, if you wrote your code a bit cleaner. Not trying to bash you :) Proper indentation, spacing, and formatting go a long way. It makes it easier on your eyes, and on yourself, in times like these..
I left your <script> tags because I assumed there was a reason your wanted to popup a message box.. I would just use header('Location: /path/to/where.php'); and pass your error message through a session variable or something, like an array of errors, which you get, clear, and show on the page the errors.
I am new with php, but I have already made a registration script that works fine. But the problem is every time I press the submit button to check my error, I'm going to a new page.
My question is how I make that error comes on the same page?
The code I am useing for the html form.
I want the error display in the error div box that I made Any idea ?
<div id="RegistrationFormLayout">
<h1>Registration Page</h1>
<div id="ErrorMessage"></div>
<form action="script/registration.php" method="post">
<label for="Username">Username</label>
<input type="text" name="Regi_username">
<label for="FirstName">FirstName</label>
<input type="text" name="Regi_Firstname">
<label for="LastName">LastName</label>
<input type="text" name="Regi_Lastname">
<label for="EamilAddress">Regi_EmailAddres</label>
<input type="text" name="Regi_EmailAddres">
<label for="Password">Password</label>
<input type="password" name="Regi_password">
<button type="submit" value="Submit" class="Login_button">Login</button>
</form>
</div>
If I understand correctly, you want form validation errors there. This is a very common pattern, and the simple solution is to always set a form's action attribute to the same page that displays the form. This allows you to do the form processing before trying to display the form (if there are $_POST values). If the validation is successful, send a redirect header to the "next step" page (with header()).
The basic pattern looks like this (in very very simplified PHP)
<?php
if(count($_POST)) {
$errors = array();
$username = trim($_POST['Regi_username']);
if(empty($username)) {
$errors[] = 'username is required';
}
if(count($errors) == 0) {
header('Location: success.php');
die();
}
}
<ul class="errors">
<?php foreach($errors as $error) { ?>
<li><?php echo $error;?></li>
<?php } ?>
</ul>
I want to submit this form through PHP. with validation for required field and validation for phone number and email field also
<form action="" method="" id="get-protected">
<div class="row requiredRow">
<label for="txt_FirstName">
First Name</label>
<input id="txt_FirstName" type="text" class="required" title="First Name. This is a required field" />
</div>
<div class="row">
<label for="txt_LastName">
Last Name</label>
<input id="txt_LastName" type="text" title="First Name. This is a required field" />
</div>
<div class="row">
<label for="txt_Phone">
Phone</label>
<input id="txt_Phone" type="text" title="First Name. This is a required field" />
</div>
<div class="row requiredRow">
<label for="txt_Email">
Email</label>
<input id="txt_Email" type="text" class="required" title="Email. This is a required field" />
</div>
<div class="row">
<input type="submit" value="" class="button" />
</div>
</form>
In your method attribute inside your form, you need to declare either post or get.
Since your action attribute is "" it will submit to the page itself rather than redirecting to another page, so you can have your code that checks for validation in the same PHP file. First validation that is often checked is if the variable has a value by using isset:
if(isset($_POST['txt_Phone'])) { ... }
This just checks that the Phone number field does not contain empty data. I strongly suggest you perform other validation checks on the POST array so you do not have any users posting malicious code.
You can use functions like htmlspecialchars to prevent user-supplied text depending on what you plan to do with the values
Here are some references to help you along the way in the order they should be viewed.
Form Validation using PHP - PHP and MySQL Tutorial
PHP Advance Form Validation Tutorial
PHP Tutorial Part 2: Form Validation
Your form tag needs a target in the action field and a method in the method field (either GET or POST). So make the action your PHP script.
<form name="input" action="form_submit.php" method="get">
As for field validation, you will either have to parse that inside of the PHP and return a response or use Javascript in the browser to check on the fly.
Here is the shcema of such a script:
if ($_SERVER['REQUEST_METHOD']=='POST') {
//data validation:
$err="";
if (valid_phone($_POST['phone'])) $err="Wrong phone no";
if (!$err) {
//record data:
$sql="...";
query($sql);
Header("Location: ".$_SERVER['REQUEST_URI']); //redirect and exit
exit;
}
}
?>
<html>
<head></head>
<body>
<? if ($err) ?> <font color=red><b><?=$err?></b></font>
<form method="POST" id="get-protected">
here goes your form
Okay, firstly, I like to set the form action to <?=$_SERVER['REQUEST_URI']?> to submit it back to the current page, but leaving it as you have it will work fine too.
Secondly, you need to give all your <input>s a name attribute. This is the variable name that PHP will see.
When your users get an error (something doesn't validate correctly) you don't want all the data they entered to disappear. That means you have to set the value attributes of each input to what they had previously entered. Thus, your form starts to look like this:
<form action="<?=$_SERVER['REQUEST_URI']?>" method="" id="get-protected">
<div class="row requiredRow">
<label for="txt_FirstName">
First Name</label>
<input id="txt_FirstName" type="text" class="required" title="First Name. This is a required field" name="first_name" value="<?=htmlspecialchars($_POST['first_name'])?>" />
</div>
...
<div class="row">
<input type="submit" name="submit" value="" class="button" />
</div>
</form>
If you didn't know <?= is a basically a shortcut for <?php echo but it will only work if your server has short tags enabled. Some people prefer to type it out the long way (in case they want to switch servers later, or for future-compatibility, or because they're nutbars), but I say screw them, I'm lazy.
This page that has the form on it, has to saved with a .php extension (well, technically it doesn't have to, but that's another story). Then you need to handle you form validation. You have to code that up yourself. It might look something like this (put it above your form somewhere)
<?php
if($_POST['submit']) {
$errors = array()
if(empty($_POST['first_name'])) $errors[] = 'please enter your first name';
if(empty($errors)) {
// save the data to database or do whatever you want with it
header('redirect:succcess.php');
} else {
foreach($errors as $e) {
echo $e;
}
}
}
?>
It's been a while since I've coded in PHP so forgive me if there are syntax errors. That's the jist of it anyway, I'm sure you can find validation libraries out there if you Google. Might take some of the grunt work out of trying to validate email addresses and such.
Using Javascript you can do the validation for this form.For each condition you can use return true and return false,based on the condition.Then you can submit the value.
Using action attribute in form tag the values will be submitted to that file.