<?php
$fp = fopen("users.txt", "w");
if(!$fp) die ("Errore nella creazione dell'utente");
$fp=fwrite($email $password);
fclose($fp);
$name="";
$surname="";
$email="";
$password="";
$nazionalita="";
$telefono="";
$errors= array();
if($_SERVER["REQUEST_METHOD"]=="POST"){
$name = htmlspecialchars($_POST["name"]);
$surname = htmlspecialchars($_POST["surname"]);
$email = htmlspecialchars($_POST["email"]);
$password = htmlspecialchars($_POST["password"]);
$nazionalita = htmlspecialchars($_POST["nazionalita"]);
$telefono = = htmlspecialchars($_POST["nazionalita"]);
}
if(empty($name)) {
$errors[] = "Name is required!";
}
if(empty($surname)) {
$errors[] = "Surname is required!";
}
if(empty($email)) {
$errors[] = "Email is required!";
}
if(empty($password)) {
$errors[] = "Password is required!";
}
header("location: index.php");
?>
But of course, this doesn't work.
How can I save to a specific location with PHP?
Then I'll have to do an explode which will only get my email and password. on the login.php page.
Thank you.
I'm not going to fix your code for you, but give you three tips:
Think like a computer. The computer is going to run your program one statement at a time, in the order you've written them; so if you have a line that writes a variable to a file, it needs to come after the line where you've put a value into that variable. It is also going to do exactly what you ask it, not guess what you meant, and not let you get away with typos; read your code back carefully.
Make use of the PHP manual. If you type in https://php.net/ followed by the name of a built-in function, like https://php.net/fwrite, you will get a page that explains what the input and output of that function is. Often, there are examples which show various ways of using the function, which you can use as inspiration for how to write your own code.
Turn on the display_errors setting, or learn where your log file is. Most of the mistakes in the code you show will result in errors or warnings, telling you exactly which line you need to look at. Read the messages carefully, and they'll often point out exactly what you've done wrong.
If you want to write to the file you could do $fpw = fwrite($fp,$email.' : '.$password);
you should pass the $fp to fwrite() method as follow
$fp = fopen('user.txt', 'w+') or die('Unable to open file!');
$fp=fwrite($fp, $email.'~'.$password.'\n'); // make sure to choose whatever seperator suits your need and be careful when choosing it
fclose($fp);
Thanks everyone, I fixed my code!!!
Following the correct code!
<?php
$name="";
$surname="";
$email="";
$password="";
$nazionalita="";
$telefono="";
$errors= array();
//$fp = fopen("users.txt", "w");
//$fpw = fwrite($fp,$dati $email.' : '.$password);
//fclose($fp);
if(isset($_POST["submitPut"])){
$name = htmlspecialchars($_POST["name"]);
$surname = htmlspecialchars($_POST["surname"]);
$email = htmlspecialchars($_POST["email"]);
$password = htmlspecialchars($_POST["password"]);
$nazionalita = htmlspecialchars($_POST["nazionalita"]);
$telefono = htmlspecialchars($_POST["telefono"]);
$dati= "\n". $name . ",". $surname .",".$email.",". $password . ",". $nazionalita. ",". $telefono;
$file= fopen("users.txt", "a+");
$credenziali=fwrite($file, $dati);
fclose($file);
if(empty($name)) {
$errors[] = "Name is required!";
}
if(empty($surname)) {
$errors[] = "Surname is required!";
}
if(empty($email)) {
$errors[] = "Email is required!";
}
if(empty($password)) {
$errors[] = "Password is required!";
}
}
//header("location: index.php");
?>
<!DOCTYPE html>
<html lang="en">
<?php include_once "views/head.php" ?>
<body>
<?php include_once "views/navbar.php" ?>
<main>
<div class="container my-5">
<h2>Registration user</h2>
<form action="registration.php" method="post">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name" >
</div>
<div class="form-group">
<label for="surname">surname:</label>
<input type="text" class="form-control" id="surname" name="surname" placeholder="Enter surname" >
</div>
<div class="form-group">
<label for="email">email:</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email" >
</div>
<div class="form-group">
<label for="password">password:</label>
<input type="text" class="form-control" id="password" name="password" placeholder="Enter password">
</div>
<div class="form-group">
<label for="nazionalita">nazionalita:</label>
<input type="text" class="form-control" id="nazionalita" name="nazionalita" placeholder="Enter nazionality" >
</div>
<div class="form-group">
<label for="telefono">telefono:</label>
<input type="text" class="form-control" id="telefono" name="telefono" placeholder="Enter phone" >
</div>
<button type="submit"name="submitPut" class="btn btn-primary">Submit</button>
</form>
</div>
</main>
<?php include_once "views/footer.php" ?>
<?php include_once "views/scripts.php" ?>
</body>
</html>
Related
I have an HTML file that contains the following form:
<form action="" class="contact-form">
<div class="input-group tm-mb-30">
<input name="username" type="text" class="form-control rounded-0 border-top-0 border-end-0 border-start-0" placeholder="Name">
</div>
<div class="input-group tm-mb-30">
<input name="email" type="text" class="form-control rounded-0 border-top-0 border-end-0 border-start-0" placeholder="Email">
</div>
<div class="input-group tm-mb-30">
<textarea rows="5" name="message" class="textarea form-control rounded-0 border-top-0 border-end-0 border-start-0" placeholder="Message"></textarea>
</div>
<div class="input-group justify-content-end">
<input type="submit" class="btn btn-primary tm-btn-pad-2" value="Save">
</div>
</form>
It seems fine to me. I also have a php script:
> <?php
extract($_REQUEST);
> $file=fopen("form.txt.", "a");
fwrite($file, "----");
fwrite($file," name :");
fwrite($file, $username ."\n");
fwrite($file," email :");
fwrite($file, $email ."\n");
frwite($file," message .:");
fwrite($file, $message ."\n");
fclose($file);
> ?>
Both are in the same file, the form in between html tags, the php script after the /html tag.
If will not execute. No matter what I do, form.txt remains empty. form.txt is in the same directory and has 777.
Since I cannot find any problem with the script (there are no error messages in the apache log file), I am wondering if there is something wrong with the php on this server (there are also no entries in syslog). phpinfo page displays fine, and php --version tells me 8.2.1 is running.
I then changed action in form to "form.php" and added method=POST to test with separate script. form.php was simply:
<?php
echo "NAME:";
echo $username;
echo "EMAIL:";
echo $email;
echo "MESSAGE:";
echo $message;
echo "POSTNAME:";
echo $_POST['username'];
echo "POSTEMAIL:";
echo $_POST['email'];
echo "POSTMESSAGE:";
echo $_POST['message'];
?>
I did not get any output for the first three entries. But I got output for the last three entries. I expected to get output for all - since the form, by sending the inputs, should automatically create/define those variables. Am I wrong?
I then added this to form.php (in front of the code mentioned above) in order to define the variables:
if(isset($_POST['submit']))
{
//fetch form data
$username = $_POST['username'];
$email = $_POST['email'];
$message = $_POST['message'];
}
because I thought defining them would solve the problem. It did not. When executing form.php (by sending the form in the html), apache.log now tells me that $username, $email and $message are not defined. But I just defined them.... ärx
Remove the last dot (.) from filename form.txt.
WRONG FILE NAME form.txt.
$file=fopen("form.txt.", "a");
CORRECT FILE NAME
$file=fopen("form.txt", "a");
Now all entries will go to form.txt file.
Full Code is shared here:
Add form method as POST and add name='submit' to submit button
<form action="" class="contact-form" method="post">
<div class="input-group tm-mb-30">
<input name="username" type="text" class="form-control rounded-0 border-top-0 border-end-0 border-start-0" placeholder="Name">
</div>
<div class="input-group tm-mb-30">
<input name="email" type="text" class="form-control rounded-0 border-top-0 border-end-0 border-start-0" placeholder="Email">
</div>
<div class="input-group tm-mb-30">
<textarea rows="5" name="message" class="textarea form-control rounded-0 border-top-0 border-end-0 border-start-0" placeholder="Message"></textarea>
</div>
<div class="input-group justify-content-end">
<input type="submit" class="btn btn-primary tm-btn-pad-2" value="Save" name="submit">
</div>
</form>
If form is submitted then write to file. Also you have typo mistake in frwite which is corrected too here.
if(isset($_POST['submit'])){
extract($_REQUEST);
$file=fopen("form.txt", "a");
fwrite($file, "----");
fwrite($file," name :");
fwrite($file, $username ."\n");
fwrite($file," email :");
fwrite($file, $email ."\n");
fwrite($file," message .:");
fwrite($file, $message ."\n");
fclose($file);
}
So this solved it for me:
I added "name=submit" to the submit input in HTML. The form posts to form.php, which now looks like this:
<html>
<body>
<?php
// turn on error reporting
ini_set('error_reporting', 'on');
error_reporting(E_ALL);
// Remove all illegal characters from email
// $email_address = filter_var($email_address, FILTER_SANITIZE_EMAIL);
// check if form has been submitted
if(isset($_POST['submit']))
{
//fetch form data
$username = $_POST['username'];
$email = $_POST['email'];
$message = $_POST['message'];
//write form data
$fp = fopen('form.txt', 'a');
fwrite($fp, "---");
fwrite($fp,"name :");
fwrite($fp, $username ."\n");
fwrite($fp," email :");
fwrite($fp, $email ."\n");
fwrite($fp," message :");
fwrite($fp, $message ."\n");
fclose ($fp);
}
//show submitted data
echo "NAME:";
echo $username;
echo "<br>";
echo "EMAIL:";
echo $email;
echo "<br>";
echo "MESSAGE:";
echo $message;
echo "<br>";
echo "POSTNAME:";
echo $_POST['username'];
echo "<br>";
echo "POSTEMAIL:";
echo $_POST['email'];
echo "<br>";
echo "POSTMESSAGE:";
echo $_POST['message'];
echo "<br>";
// extract($_REQUEST); might need to be added
?>
The data has been submitted - thanks
</body>
</html>
For some reason, the extract command seems unnecessary; it works fine without it, but I am not sure why. Anyhow, the data is now processed into the file. I got it. Thanks so much, everyone!
I'm learning coding and created a simple form where error messages are
displayed just below each input field. However, when I check the form
the success message appears at the same time as error messages instead
of displaying when all the fields are correctly entered and form
validated. Can you please help. Thank yo in advance. Here is my
code.
</php>
$errorMessage = "";
$successMessage = "";
$emailError = "";
$emailconfirmError = "";
$nameError = "";
$messageError = "";
$servicesError = "";
$name = $email = $emailConfirm = $services = $message = "";
$email = isset($_POST['email']) ? $_POST['email'] : '';
$emailConfirm = isset($_POST['emailConfirm']) ? $_POST['emailConfirm'] : '';
if ($_POST) {
if (!$_POST['email']) {
$emailError .="The email is required";
}
if (!$_POST['emailConfirm']) {
$emailconfirmError .="Please confirm your email <br>";
}
if ($_POST['emailConfirm'] && $email != $emailConfirm) {
$emailconfirmError .="The email addresses do not match <br>";
}
if (!$_POST['name']) {
$nameError .="The name field is required <br>";
}
if (!$_POST['services']) {
$servicesError .="Please select a service required <br>";
}
if (!$_POST['message']) {
$messageError .="The message field is required <br>";
}
if ($_POST['email'] && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$emailError .= "The email address is invalid.<br>";
}
if ($name = $email = $emailConfirm = $services = $message != "") {
echo $emailError;
echo $emailconfirmError;
echo $name;
echo $services;
echo $message;
}else {
$emailTo = "kamala_guliyeva#hotmail.com";
$services = $_POST['services'];
$message = $_POST['message'];
$headers = "From: ".$_POST['email'];
if (mail($emailTo, $services, $message, $headers)) {
$successMessage = '<div class="alert alert-success" role="alert">Thank you for your message. We\'ll get back to you ASAP!</div>';
} else {
$errorMessage = '<div class="alert alert-danger" role="alert"><p>Your message couldn\'t be sent - please try again</div>';
}
}
}
and HTML
<div id="quote">
<div class="container">
<h2 class="section-title">Request a Quote</h2>
<hr align="left" width="8%" class="style-one">
<br>
<div><? echo $errorMessage.$successMessage; ?></div>
<form id="quoteForm" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="email" class="form-control" style="height:60px" id="email" name="email" placeholder="Your email">
<label class="error" id="emailError"><?php echo $emailError; ?></label>
</div>
<div class="form-group">
<input type="email" class="form-control" style="height:60px" id="emailConfirm" name="emailConfirm" placeholder="Re-type your email">
<label class="error" for="e-mailConfirm" id="emailconfirmError"><?php echo $emailconfirmError; ?></label>
</div>
<div class="form-group">
<input type="name" class="form-control" id="name" style="height:60px" name="name" placeholder="Your Name">
<label class="error" for="name" id="nameError"><?php echo $nameError; ?></label>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<select class="form-control" id="services" name="services" style="height:60px">
<option value="">Select Services</option>
<option value="Installation">Installation</option>
<option value="Repair">Repair</option>
<option value="Service and Maintenance">Service and Maintenance</option>
</select>
<label class="error" for="services" id="servicesError"><?php echo $servicesError; ?></label>
</div>
<div class="form-group">
<textarea class="form-control" id="message" name="message" placeholder="Message" style="height: 163px;" cols="35"></textarea>
<label class="error" for="message" id="messageError"><?php echo $messageError; ?></label>
</div>
</div>
</div>
<div class="form-row text-center">
<div class="col-12">
<button type="submit" style="width:10rem" class="btn quoteButton pt-3 pb-3 text-align-center">Get a Quote</button>
</div>
</div>
</form>
</div>
</div>
You've a few problems there...
So first thing is how you are doing your checks.
if(!$_POST) {
is not a valid way of checking that a post has occurred you need to do something like
if(isset($_POST) && !empty($_POST)) {
would be more appropriate as you are checking if the POST array is actually set and then that it is not empty the && operator is a short circuit operator so if either condition isn't met then the check will fail.
Similarly on your comparisons saying if(!$_POST['email']) { isn't valid because you're effectively asking "if the email part of the post array is not true" where as you need to be asking "if it's not blank and is a valid email address"
You need to be aware of the difference between = == and === operators. You can find some more information here: The 3 different equals
And also the filter_var function here: http://php.net/manual/en/function.filter-var.php
if($_POST['email']!=="" && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
//all good
} else {
//set your error message
}
you can use regular expressions to validate 'name' see preg_match in the manual http://php.net/manual/en/function.preg-match.php
Aside from all of this if you want to have real time monitoring of the fields and the error messages etc you're going to have to look at incorporating Javascript and using AJAX to communicate with your script and then parse the response back into the appropriate div.
Have a look at Rasmus 30 second AJAX tutorial will give you a starting point for this http://rajshekhar.net/blog/archives/85-Rasmus-30-second-AJAX-Tutorial.html
However it is better practice to do both client and server side validation hope this helps even if it is not a complete answer per sé.
i make a login system using php with json file data. i tried to login with JavaScript file and it works fine. but it is not secure well. then i change some code with php login.
this is my php code
if(isset($_POST['submit'])){
$json_string = file_get_contents('login.json');
$parsed_json = json_decode($json_string, true);
foreach($parsed_json as $key => $value){
$jsonemail = $value['email'];
$jsonpass = $value['pass'];
}
if($email == $jsonemail && $pass == $jsonpass){
header('location: view.php');
}
else{
echo "please check your email or password";
}
}
but this not working. i want to fix this code. i want to check email and password is correct with json file data.
this is my login.json file data like
"1": {
"email": "test123#gmail.com",
"pass": "123"
},
and this is my html login form
<div class="container">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" name="email" id="email" aria-describedby="emailHelp" required="require" placeholder="Enter email">
</div>
<div class="form-group">
<label for="pass">Password</label>
<input type="password" class="form-control" id="pass" required="require" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary" name="submit" >Submit</button>
</form>
</div>
<div class="col-md-4"></div>
</div>
</div>
I think your email and pass variable are not defined. Have a look at it.
if (isset($_POST['submit'])) {
$json_string = file_get_contents('login.json');
$parsed_json = json_decode($json_string, true);
$email = $_POST['email']; // I think you miss this
$pass = $_POST['pass']; // and this lines as in your code its missing
$flag = false;
foreach ($parsed_json as $key => $value) {
if ($value['email'] == $email && $value['pass'] == $pass) {
$flag = true;
break;
}
}
if ($flag) {
header('location: view.php');
} else {
echo "Please check your email and password."
}
}
And one more thing
while posting any form you must name element which you want in $_POST.
<input type="password" class="form-control" id="pass" required="require" placeholder="Password">
In above line you are missing name as pass. Replace above line with
<input type="password" class="form-control" id="pass" required="require" placeholder="Password" name="pass">
This should solve your problem.
Your foreach is just overwriting the values of $jsonemail and $jsonpass each time, so when you reach the if() part to check the user details, these will always be the last values in the file.
if(isset($_POST['submit'])){
$json_string = file_get_contents('login.json');
$parsed_json = json_decode($json_string, true);
foreach($parsed_json as $key => $value){
if($email == $value['email'] && $pass == $value['pass']){
header('location: view.php');
exit();
}
}
echo "please check your email or password";
}
This code redirects if the user is found and if it gets to the end of the loop, then the user doesn't exist in the file.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Goodday house,i'm developing this site that has a registration/login page as my first project and i'm stucked right now.
I added php validation to my registration form but the database insert statement refuses to work after,though all conditional statements were fulfilled,i tried putting a redirect loop immediately after the insert statement but my script automatically (somehow) jumps the "Insert statement" and processes the redirect code..
This is the code below
<!-- Php validation-->
<?php
include 'var.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array(); // Starts an array to store errors.
//Validation rules involves trimming,validating and sanitizating
$name = trim($_POST['name']);
$strippedname = mysqli_real_escape_string($con, strip_tags($name)) ;
$length = mb_strlen($strippedname, 'utf-8') ;
if ($length < 8 ) {
$errors[]= 'Your full name shouldn\'t be less than 8 letters' ;
} else {
$name = $strippedname ;
}
$email = FALSE ;
if (empty($_POST['email'])) {
$errors[] = 'You didn\'t provide any email address' ;
} // Next is removal of spaces and validation.
if (filter_var((trim($_POST['email'])), FILTER_VALIDATE_EMAIL)) {
$email = mysqli_real_escape_string($con, (trim($_POST['email'])));
}
else {
$errors[] = 'Email address was provided in the wrong format';
}
$pho = trim($_POST['phone']) ; // next line of code removes all characters that aren't digits
$phon = preg_replace('/\D+/', '', ($_POST['phone']));
$strippedphone = mysqli_real_escape_string($con, strip_tags($phon));
$length = mb_strlen($strippedphone, 'utf-8') ;
if ($length <> 11 ) {
$errors[] = 'Phone number should contain only eleven digits';
}
else {
$phone = $strippedphone ;
}
$add = trim($_POST['address']) ;
$strippedadd = mysqli_real_escape_string($con, strip_tags($add)) ;
$length = mb_strlen($strippedadd, 'utf-8') ;
if ($length < 15) {
$errors[]= 'Address should not be lesser than 15 letters' ;
} else {
$address = $strippedadd ;
}
if (empty($_POST['gender'])) {
$errors[] = 'You didn\'t select a gender';
} else {
$gend = trim($_POST['gender']);
}
$user = trim($_POST['username']);
$strippeduser = mysqli_real_escape_string($con, strip_tags($user)) ;
$length = mb_strlen($strippeduser, 'utf-8') ;
if ($length < 6) {
$errors[] = 'Username should contain a minimum of 6 letters and maximum of 18';
} else {
$confirmeduser = $strippeduser ;
}
if (empty($_POST['password'])){
$errors[] ='Please enter a valid password';
}
if(!preg_match('/^\w{10,40}$/', $_POST['password'])) {
$errors[] = 'Invalid password, use 10 to 40 characters without applying spacing.';
} else{
$password = $_POST['password'];
}
if($_POST['password'] == $_POST['confirm_password']) {
$pass = mysqli_real_escape_string($con, trim($password));
$newpass = password_hash($pass, PASSWORD_DEFAULT) ;
}else{
$errors[] = 'passwords don\'t match.';
}
if(empty($errors)) { // If no problems occurred
//Determine whether the email address has already been registered for a user
$query = mysqli_query($con, "INSERT INTO `customer`(`name`, `email`,
`phone`, `address`, `gender`, `username`, `password`) VALUES($name,$email,$phone,
$address,$gend,$confirmeduser,$newpass)") ;
echo "Done";
// end of mysqli_num_Rows
} // End of if (empty($errors))
else{ // Display the errors if any are found.
echo '
<p class="error">The following error(s) were found in the submitted form :<br>';
foreach ($errors as $msg) { // Echo each error
echo " $msg<br>";
}
}
}
?>
This is the html form
<form action="register.php" method="POST" class="form-horizontal" style="margin-top:30px" id="signup">
<fieldset> <div class="form-group">
<legend> Customer Details </legend>
</div>
<div class="form-group">
<label for="name" class="control-label"> Full Name : </label>
<input type="text" value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>"
name="name" placeholder="Your Full Name" class="required" title="Please type in your name" >
</div>
<div class="form-group">
<label for="email" class="control-label"> Email address </label>
<input type="text" name="email" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>"
placeholder="someone#example.com">
</div>
<div class="form-group">
<label for="phone" class="control-label"> Phone Number :</label>
<input type="tel" name="phone" value="<?php if (isset($_POST['phone'])) echo $_POST['phone']; ?>"
placeholder="08137871320" class="required digits">
</div>
<div class="form-group">
<label for="address" class="control-label"> Contact Address : </label>
<input type="text" name="address" value="<?php if (isset($_POST['address'])) echo $_POST['address']; ?>"
placeholder="No 4,street name,ikeja"
class="required" title="Please type in contact address plus your city's name">
</div>
<!--<div class="form-group">
Drop down menu for selecting a state from the 36 states to be provided
</div>-->
<div class="form-group">
<label for="name">Select Your gender :</label>
<select name="gender" class="form-control">
<option value="male" > Male </option>
<option value="female">Female </option>
</select>
</div>
</fieldset>
<fieldset> <div class="form-group">
<legend> Login Information </legend>
</div>
<div class="form-group">
<label for="username" class="control-label"> Username : </label>
<input type="text" name="username" placeholder="e.g Lords" value="<?php if (isset($_POST['username']))
echo $_POST['username']; ?>">
</div>
<div class="form-group">
<label for="password" class="control-label"> Password : </label>
<input type="password" name="password" id="password" placeholder="Your Password Here">
</div>
<div class="form-group">
<label for="cpassword" class="control-label">Confirm Password : </label>
<input type="password" name="confirm_password" placeholder="Confirm Your Password Here">
</div>
</fieldset>
</div>
</div>
</div>
<div class="form-group" style="text-align:center">
<button type="submit" class="btn btn-success" name="submit"> REGISTER </button>
<button type="reset" id="fat-btn" class="btn btn-danger" data-loading-text="Loading..."> RESET </button> <br>
<p class="lead">
Already a registered user ?,do make use of the
<a href="login.php" class="navbar-link" data-toggle="tooltip" title="When clicked upon,
a page requesting for your username and password is generated,allowing you to book orders">
login page </a>
</p>
</div>
</form>
Thanks a lot for your reply
Since we're more than likely dealing with strings, these variables in your VALUES
($name,$email,$phone,$address,$gend,$confirmeduser,$newpass)
needs to be quoted:
('$name','$email','$phone','$address','$gend','$confirmeduser','$newpass')
Had you checked for errors using or die(mysqli_error($con)) to mysqli_query()
would have signaled the quotes errors.
Sidenote:
You should use prepared statements, or PDO with prepared statements, they're much safer.
Additional note that Barmar spotted:
<?phpinclude 'var.php';
there needs to be a space in there between php and include
<?php include 'var.php';
unless that's a copy/paste error or typo.
and >? again, another spotted error which should be ?>
On the PHP side of things:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
I have the following error:
Notice: Undefined index: submit in C:\wamp\www\registration\register.php on line 6
Can't seem to work out whats wrong??? Here's the code::
<?php
//Create registration form (register.php)
include "../includes/db_connect.php";
if(!$_POST['submit']) ///Line 6
{
?>
<html>
<head><link rel="stylesheet" href="style.css"></head>
<div class="divider">
<strong>Register</strong><br/><br/>
<form method="post" action="register.php">
<div class="formElm">
<label for="first">First Name</label>
<input id="first" type="text" name="first">
</div>
<div class="formElm">
<label for="last">Last Name</label>
<input id="last" type="text" name="last">
</div>
<div class="formElm">
<label for="username">Desired Username</label>
<input id="username" type="text" name="username">
</div>
<div class="formElm">
<label for="password">Password</label>
<input id="password" type="password" name="password">
</div>
<div class="formElm">
<label for="pass_conf">Confirm Password</label>
<input id="pass_conf" type="password" name="pass_conf">
</div>
<div class="formElm">
<label for="email">Email</label>
<input id="email" type="text" name="email">
</div>
<div class="formElm">
<label for="about">About</label>
<textarea id="about" cols="30" rows="5" name="about">Tell us about yourself</textarea>
</div>
<input type="submit" name="submit" value="Register">
</form>
or Login
</div>
</html>
<?php
}
else
{
$first = protect($_POST['first']);
$last = protect($_POST['last']);
$username = protect($_POST['username']);
$password = protect($_POST['password']);
$pass_conf = protect($_POST['pass_conf']);
$email = protect($_POST['email']);
$about = protect($_POST['about']);
$errors = array();
$regex = "/^[a-z0-9]+([_\.-][a-z0-9]+)*#([a-z0-9]+([.-][a-z0-9]+)*)+\.[a-z]{2,}$/i";
if(!preg_match($regex, $email))
{
$errors[] = "E-mail is not in name#domain format!";
}
if(!$first || !$last || !$username || !$password || !$pass_conf || !$email || !$about)
{
$errors[] = "You did not fill out the required fields";
}
$sql = "SELECT * FROM `users` WHERE `username`='{$username}'";
$query = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($query) == 1)
{
$errors[] = "Username already taken, please try another";
}
if(count($errors) > 0)
{
echo "The following errors occured with your registration";
echo "<font color=\"red\">";
foreach($errors AS $error)
{
echo "<p>" . $error . "\n";
}
echo "</font>";
echo "Try again";
//we use javascript to go back rather than reloading the page
// so the user doesn't have to type in all that info again.
}
else
{
$sql = "INSERT into `users`(`first`,`last`,`username`,`password`,`email`,`about`)
VALUES ('$first','$last','$username','".md5($password)."','$email','$about');";
$query = mysql_query($sql) or die(mysql_error());
echo "Thank You for registering {$first}! Your username is {$username}";
echo " Click here to Login";
}
}
?>
If there is no POST parameter at all or if there is no parameter named submit then you're trying to access an array index that does not exists, hence the warning. You can simply test if there is such an index/element in the _POST array.
if( isset($_POST['submit']) )
It doesn't check the value (like you original script, which tests if the value of _POST['submit'] equals false, see type juggling), but the mere existence of the index/element should suffice in this case.
see http://docs.php.net/isset
To get rid of this error, it should be:
if(!isset($_POST['submit']))
However, your code is already OK.
What you are getting is not an error, it is a warning, which is caused by having strict warnings enabld. PHP is a dynamic language which does not usually require to define variables and array keys, and most documentation and code will skip this part. So you should consider turning this feature off, as it clutters code and has few additional benefits. Or, switch to a statically compiled language (say asp.net) which will really benefit from defined variables and static typing.
Your $_POST does not exist when you first load your page. Change your check to something like:
if(!isset($_POST["submit"]))
Because you did not post anything yet, there will be no "submit" key in your $_POST array. That's what causes the warning.
For those posting use if(isset($_POST['submit'])), you clearly did not read his code. He has put is there is not a submit write the HTML form else use the fields (backwards righting to me!)
If he wants to keep the structure as is, it should be
if(empty($_POST['submit']))