I am new to PHP...
Just trying this simple piece of code inside my about.php file (which links to index.php file via a hyperlink):
<form action ="about.php" method="POST">
<ul>
<li>
<label for="name"> Enter your name please:</label>
<input type="text" name="name"/>
</li>
<li>
<label for="comments" rows="20"> Enter your comments :</label>
<textarea id="comments" name="comments" rows="5" cols="38">
<?php
$name = $_POST["name"];
if (!empty($name)) {
echo "Your name is ".$name."and you like ny site!";
} else {
echo "Please enter your name";
}
?>
</textarea>
</li>
<li>
<input type="submit" />
</li>
</ul>
I get the following error:
Notice: Undefined index: name in D:\xampp\htdocs\stathis1\about\about.php on line 71
Please enter your name
Because $_POST["name"] is not set, you get that notice. So you need to test if it exists first, and then assign it to your $name variable, or empty string if it's not set.
You can change
$name = $_POST["name"];
to
$name = isset($_POST["name"])?$_POST["name"]:'';
use isset() instead of empty() because isset() function not triggering notice when the index not defined.
It's because $_POST['name'] hasn't been submitted/set yet. You need to either use an if statement or a ternary operator:
if (isset($_POST['name'])) {
$name = $_POST['name'];
if (!empty($name)) {
echo 'Your name is ' . $name . ' and you like ny site!';
} else {
echo 'Please enter your name';
}
}
Or, a shorter method:
$name = isset($_POST['name']) ? $_POST['name'] : '';
Right after starting your php part add this if sentence surrounding the code, so it only executes when the "name" exists.
if(isset($_POST["name"]))
Like this:
<?php
if(isset($_POST["name"])){
$name = $_POST["name"];
if (!empty($name)) {
echo "Your name is ".$name."and you like ny site!";
} else {
echo "Please enter your name";
}
} else {
echo "Please enter your name";
}
?>
Related
I made a website using css, html, javascript and a little php. I have it hosted on a hosting site with a domain name, but I'm having issue with the server side validation for the form.
It's just a simple contact form:
First Name
Last Name
Email
Message (textarea)
Submit button
I have javascript validation and it works fine. The form won't submit at all unless the correct amount of characters are input, but obviously that's useless if the user has js disabled. I've also finally gotten the form to email to my personal email using php... But obviously I need server side validation as well.
Today was my first day really getting into php and I was hoping to have the php validation done by today, but of all the videos I watched, I just came away more confused. All I want to do is just make it so that if the user has javascript disabled for whatever reason, or if he leaves the fields blank, the form won't submit...
Anyeay, I was working on this all day today with the intention of getting the form to send to my email, I finally accomplished that. Then realized I had no server side validation. I spent a few hours researching it and attempting it to no avail. Can anyone here just give me the php validation code for the kind of form I described above? It's for my business website so the sooner I can have a working contact form on it, the better...
Here is the html contact form I made.
<form action="message_sent.php" method="POST" onSubmit="return validateTextbox();">
<p class="message">
<div class="row">
<label for="firstname"><!--First Name (Required):--> </label>
<input type="text" id="firstname" name="first_name" size="40" placeholder="First Name (Required)"></br> </br> </div>
<div class="row">
<label for="lastname"><!--Last Name (Required):--> </label>
<input type="text" id="lastname" name="last_name" size="40" placeholder="Last Name (Required)"/> </br> </br></div>
<div class="row">
<label for="email"><!--Your Email (Required):--></label>
<input type="email" id="email" name="email" size="40" placeholder="Email (Required)"/> </br> </br></div>
<!--<p class="yourMessage">Your Message (10 Character Minimum):</p>-->
<textarea id="theform" rows="30" cols="80" name="message" placeholder="Your Message (10 Character Minimum):"></textarea></br>
</p>
<input type="submit" name="submit" onclick="return val();" value="SUBMIT">
</form>
</body>
</html>
Here is the javascript validation:
/*============================ CONTACT US PAGE ==========================*/
function validateTextbox() {
var box = document.getElementById("firstname");
var box2 = document.getElementById("lastname");
var box3 = document.getElementById("email");
var box4 = document.getElementById("theForm");
if (box.value.length < 1 || box2.value.length < 1 || box3.value.length < 5){
alert("You must enter a value");
box.focus();
box.style.border = "solid 3px red";
box2.focus();
box2.style.border = "solid 3px red";
box3.focus();
box3.style.border = "solid 3px red";
return false;
}
}
function val(){
if(document.getElementById("theform").value.length < 10
&& document.getElementById("theform").value.length > 0){
alert("You must enter at least 50 characters. Tell us what you need so we can better assist you.");
return false;
}
else if(document.getElementById("theform").value.length === 0){
alert("You cannot submit an empty form.");
theform.focus();
theform.style.border = "solid 3px red";
return false;
}
}
/*function val(){
if(document.getElementById("theform").value==null || document.getElementById("theform").value==""){
alert("The Message field cannot be blank.");
return false;
}
*/
/*
*/
/*=======================|| box4.value.length < 70) ================================================ */
/*========= CONTACT PAGE========================================*/
/*
function contactPage(){
alert("This Contact Form is NOT OPERATIONAL.");
Here is the php submission success page... the code I used to have the form send to my email:
<?php
$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
$email=$_POST['email'];
$message=$_POST['message'];
$to="default#email.com";
$subject="A visitor has sent you a new message";
$body="You have received a message from: \n\n
First Name: $first_name\n
Last Name: $last_name\n
Email: $email\n\n
MESSAGE: $message";
mail($to, $subject, $body);
print "<p>Message Sent! <a href='index.html'>Click. here</a> to return to the homepage</p>"
?>
Simple and complete example:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
//Define variable as empty to avoid "undefined variable error".
$FnameErr = $LnameErr = $emailErr = ""; //Each variable contain error string of specific field.
$fname = $lname = $email = $message = ""; //Main inputed data of specific field
if ($_SERVER["REQUEST_METHOD"] == "POST") { //check if request is posted.
//First name check
if (empty($_POST["fname"])) { // check if empty then assign a error string in spacific variable
$FnameErr = "First Name is required";
}else{ // if not empty then store as right data
$fname = filter_data($_POST["fname"]); //filter with unexpected special char and trim.
}
//Last name
if (empty($_POST["lname"])) { // check if empty then assign a error string in spacific variable
$LnameErr = "Last Name is required";
}else{ // if not empty then store as right data
$lname = filter_data($_POST["lname"]); //filter with unexpected special char and trim.
}
//email
if (empty($_POST["email"])) { // check if empty then assign a error string in spacific variable
$emailErr = "Email is required";
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // validate email with php build-in fucntion.
$emailErr = "Invalid email format";
}else{ // if not empty and valide email then store as right data
$email = filter_data($_POST["email"]); //filter with unexpected special char and trim.
}
}
//message with no validation
if (empty($_POST["message"])) {
$message = "";
} else {
$message = filter_data($_POST["message"]);
}
//Database query
if($FnameErr =="" && $LnameErr =="" && $emailErr==""){
//MYSQL insert statement that you know
// $sql = "INSERT INTO tablename .................."; values = $fname; $lname; $email; $message;
}
}
// A function to trim data and remove special charecter
function filter_data($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
First Name: <input type="text" name="fname" value="">
<span class="error">* <?php echo $FnameErr;?></span><br><br>
Last Name: <input type="text" name="lname" value="">
<span class="error">* <?php echo $LnameErr;?></span><br><br>
E-mail: <input type="text" name="email" value="">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Message: <textarea name="message" rows="5" cols="40"></textarea>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $fname;
echo "<br>";
echo $lname;
echo "<br>";
echo $email;
echo "<br>";
echo $message;
?>
</body>
</html>
This is just a basic empty check validation.
Validations in PHP are not very difficult.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(trim($_POST['firstname']) === ''){
echo 'Please enter firstname';
}
}
You can also learn some validations here
http://www.w3schools.com/php/php_form_validation.asp
Continuing from my previous post "PHP and MYSQL database connection and table creation only once", I created the registration form with the PHP code and server side validation. I’m getting some errors as stated below.
i.e. all errors are occurring at the place where i try to print the errors in their respected html class “”. I've made the html "span class" text bold for easy recognition. If their is anything extra solutions for better performance of the form please let me know...
List of errors:
Notice: Undefined variable: error_name in C:\wamp\www\18+\register.php
Notice: Undefined variable: error_username in C:\wamp\www\18+\register.php
Notice: Undefined variable: error_password in C:\wamp\www\18+\register.php
Notice: Undefined variable: error_password2 in C:\wamp\www\18+\register.php
Notice: Undefined variable: error_email in C:\wamp\www\18+\register.php
Register.php
<?php
include ‘database.php';
session_start();
if (isset($_POST['submit'])) {
$error = " "; //Declare a null variable to store error messages
//validation for fullname
if (empty($_POST['fullname'])) {
$error_name = 'Enter Fullname...';
} else {
$fullname = mysql_real_escape_string(trim($_POST['fullname']));
}
//validation for username
if (empty($_POST['username'])){
$error_username = 'Enter Username...';
} else {
$username = mysql_real_escape_string(trim($_POST['username']));
}
//validation for password
if(empty($_POST['password'])){
$error_password = 'Please Enter Your Password...';
} else {
if (empty($_POST['password2'])) {
$error_password2 = 'Re-enter Your Password...';
} else {
if(($_POST['password'])!=($_POST['password2'])){
$error_password2 = 'Passwords Do not match...';
} else {
$confirm = mysql_real_escape_string(md5($_POST['password2']));
}
}
}
//validation for e-mail
if (empty($_POST['email'])) {
$error_email = 'Please Enter your Email ';
} else {
if (preg_match("//custom preg match characters", $_POST['e-mail'])) {
//regular expression for email validation
$email = mysql_real_escape_string($_POST['email']);
} else {
$error_email = 'Your E-mail Address is invalid ';
}
}
if (empty($error)) //send to Database if there's no error '
{
$query= "DB INSERT QUERY";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo 'Failed to Register Your Account...!';
} else {
echo 'Account Registered Successfully...!';
}
}
mysqli_close($sql);//Close the DB Connection
}
?>
Index.php
<form action="register.php" method="post" id="user_registration">
<p id="head">Create Account</p>
<input type="text" id="fullname" name="fullname"/>
**<span class="error" id="fullname"><?php echo $error_name; ?></span>**
<input type="text" id="username" name="username"/>
<span id="availability_status"></span>
**<span class="error" id="username"><?php echo $error_username; ?></span>**
<input type="password" id="password" name="password"/>
**<span class="error" id="password"><?php echo $error_password; ?></span>**
<input type="password" id="password2" name="password2"/>
**<span class="error" id="divCheckPasswordMatch"><?php echo $error_password2;?></span>**
<input type="email" id="email" name="email"/>
**<span class="error" id="email"><?php echo $error_email; ?></span>**
<p class="submit">
<button type="submit"id="submit" name="submit" value="Register”>Register</button>
</p>
</form>
First of all You need to fix the quote at include ‘database.php'; to include 'database.php'; never use curly quote due to this all your code is being blocked.
Next You need to initialize all variable to null or simply ""
OR
You can check if the variable exist or not using isset() like if you want to print value of an variable $val then use this if(isset($val)) echo $val;
UPDATE
You can easily use an array to store errors:
simply use like
$error['name']='Enter Fullname...';
And to check if name error occurs use
if(isset($error['name'])){
//Its an error print error
}
you may need to define these variable on top of the page before using them in code something like this.
$error_name = '';
$error_username = '';
$error_password = '';
$error_password2 = '';
$error_email = '';
Put an else to your if (isset($_POST['submit']))
else { /* What if the user didn't click submit? Else is the answer */
$error_name="";
$error_username="";
$error_password="";
$error_password2="";
$error_email="";
}
The problem is, you are setting the messages only if certain conditions are true. Thus, these variables are not found if those conditions aren't true. To resolve this, use isset() when displaying the errors, e.g.
<?php echo isset($error_name)?$error_name:'' ; ?>
This means check if $error_name is set, if yes display it or display nothing.
Another thing (logically) is that your code is not actually checking for the errors. The $error remains an empty string and you are checking if it is empty which will always be true. You need to either store the errors as arrays or check if all the variables are empty.
Additional:
Can u tell me how to store the errors as arrays..plz
Try this:
<?php
include 'database.php';
session_start();
if (isset($_POST['submit'])) {
$error = array(); //<-- Declare array here
//validation for fullname
if (empty($_POST['fullname'])) {
$error['fullname'] = 'Enter Fullname...'; //<-- adding error into array
} else {
$fullname = mysql_real_escape_string(trim($_POST['fullname']));
}
//validation for username
if (empty($_POST['username'])){
$error['username'] = 'Enter Username...'; //<-- here too and so on..
} else {
$username = mysql_real_escape_string(trim($_POST['username']));
}
//validation for password
if(empty($_POST['password'])){
$error['password'] = 'Please Enter Your Password...';
} else {
if (empty($_POST['password2'])) {
$error['password2'] = 'Re-enter Your Password...';
} else {
if(($_POST['password'])!=($_POST['password2'])){
$error['password2'] = 'Passwords Do not match...';
} else {
$confirm = mysql_real_escape_string(md5($_POST['password2']));
}
}
}
//validation for e-mail
if (empty($_POST['email'])) {
$error['email'] = 'Please Enter your Email ';
} else {
if (preg_match("//custom preg match characters", $_POST['e-mail'])) {
//regular expression for email validation
$email = mysql_real_escape_string($_POST['email']);
} else {
$error['email'] = 'Your E-mail Address is invalid ';
}
}
if (!empty($error)) //send to Database if there's no error '
{
$query= "DB INSERT QUERY";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo 'Failed to Register Your Account...!';
} else {
echo 'Account Registered Successfully...!';
}
}
}
?>
Change your HTML to:
<form action="register.php" method="post" id="user_registration">
<p id="head">Create Account</p>
<input type="text" id="fullname" name="fullname"/>
<!-- checking if error message is set -->
**<span class="error" id="fullname"><?php echo isset($error['fullname'])?$error['fullname']:''; ?></span>**
<input type="text" id="username" name="username"/>
<span id="availability_status"></span>
**<span class="error" id="username"><?php echo isset($error['username'])?$error['username']:''; ?></span>**
<input type="password" id="password" name="password"/>
**<span class="error" id="password"><?php echo isset($error['password'])?$error['password']:''; ?></span>**
<input type="password" id="password2" name="password2"/>
**<span class="error" id="divCheckPasswordMatch"><?php echo isset($error['password2'])?$error['password2']:''; ?></span>**
<input type="email" id="email" name="email"/>
**<span class="error" id="email"><?php echo isset($error['email'])?$error['email']:''; ?></span>**
<p class="submit">
<button type="submit"id="submit" name="submit" value="Register">Register</button>
</p>
</form>
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
I created a little form validator with PHP and having some problems with it.
MY VIEW FILE is here :
<form action="" method="post">
<?php if( isset($status) ) : ?>
<p class="notice"><?php echo $status; ?> </p>
<?php endif; ?>
<ul>
<li>
<label for="name">Your Name : </label>
<input type="text" name="name">
</li>
<li>
<label for="email">Your Email : </label>
<input type="text" name="email">
</li>
<li>
<input type="submit" value="Sign Up">
</li>
</ul>
</form>
and here's my little controller :
<?php
require 'index.tmpl.php';
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
if (empty($name) || empty($email)) {
$status = "Please provide a name and a valid email address";
}
echo $name;
}
?>
Now what happens is that , when I open up the page and leave the form fields blank and submit it ,it just reloads ,does not echo anything.
You want to echo $status, not $name.
How about moving the require line to below the if?
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
if (empty($name) || empty($email)) {
$status = "Please provide a name and a valid email address";
}
echo $name;
}
require 'index.tmpl.php';
?>
The <form action="" points to the location where the form will be submitted. If blank, it submits the form back to itself.
<form action="yourLittleController.php" method="POST">
Edited with more info:
in php, post is not POST. Example here: https://eval.in/89002
make sure you have
method="POST">
and not
method="POST">
you should mention your second file name in your view file's form's action attribute like action = "controller.php"
Intro: I'm trying to learn PHP on $_SESSION. What I was trying to do is call the value assigned through sessions that when you close your tab will keep the value assigned and echoes it on the browser when you open a tab in the browser.
Issue: There's something wrong with my code where for some reason I couldn't echo the value entered in on a form.
The form looks like this:
Name:_____________
Email:_____________ Remember me? __ SUBMIT
I made it so that $_SESSION['name'] = "John" and $_SESSION['email'] = "someemail#email.com" only when user click on "remember me".
If you close a "tab" on the browser but not the browser itself should echo...
John
someemail#email.com
Here's your download link (some link here)...
But of course if you close the browser, session is lost. Cookies can be used but I'm working on sessions to learn more.
Below's code runs but for some reason I couldn't echo values from $_SESSION variables.
<?php
//Start session
session_start();
// session
if (isset($_POST['remember'])) {
$customer_name = $_SESSION['name'];
if (!($customer_name)) {
$customer_name = $_POST['name'];
}
$customer_email = $_SESSION['email'];
if (!($customer_email)) {
$customer_email = $_POST['email'];
}
}
//If form submit validate
if (isset($_POST['Submit'])) {
// Santize fields here but FILTER_VALIDATE_STRING isn't necessary as there is no absolute way
//to validate names absolutely
// Also shows error message if there's error
if ($_POST['name'] != "") {
$_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
if ($_POST['name'] == "") {
$errors .= 'Please enter a valid first name.<br/><br/>';
}
} else {
$errors .= 'Please enter your first name.<br/>';
}
// Sanitize and validate email
// Error message shows if any
if ($_POST['email'] != "") {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors .= "$email is NOT a valid email address.<br/><br/>";
}
} else {
$errors .= 'Please enter your email address.<br/>';
}
// If no errors, submitted form is emailed
if (!$errors) {
echo "I did something!<br /><br />"; // might add some message
//downloadLink();
echo "<br /><br />";
}
} else {
echo '<div id="error">' . $errors . '<br /></div>';
}
?>
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Name:
<?php
if (isset($_SESSION['name'])) {
echo $_SESSION['name']."<br />";
}
else {
?>
<input type="text" name="name" value="<?php echo $_POST['name']; ?>" size="25" /><br />
<?php } ?>
Email:
<?php
if (isset($_SESSION['email'])) {
echo $_SESSION['email']."<br /><br />";
// echo link.. downloadLink();
}
else {
?>
<input type="text" name="email" value="<?php echo $_POST['email']; ?>" size="25"/>
<input type="checkbox" name="remember" /> Remember me
<input type="submit" name="Submit" />
<?php } ?>
</form>
</div>
Put this at the beginning under session_start();
if (!isset($_SESSION['name'])) {
echo "Your session is not good";
} else { echo "Session is set";
}
then replace $customer_name = $_SESSION['name']; with $_SESSION['name']=$_POST['remember']; and you will start getting results.
<?php
If ( isset ($_POST['name'] ) ) {
$name = $_POST['name'];
if (!empty ($name)) {
$sentence = $name . " is the best footballer of his generation. ";
} else {
echo "Please enter a name";
}
}
?>
<html>
<head>
</head>
<body>
<!-- ********************************** -->
<form action="form3.php" method="POST">
Name: <input type="text" name="name"><br>
<input type="submit" value="Send">
</form>
<textarea rows="7" cols="30"> <?php echo $sentence; ?> </textarea>
</body>
</html>
The code works just fine, but for some reason the text inside the textarea shows this error
Notice: Undefined variable: sentence in C:\xampp\htdocs\form3.php on line 29
Please help.
$sentence is only initialized when this statement is true: if (!empty ($name)) {.
To avoid the error, put $sentence = ""; above the if-statement.
You can solve this using different options:
1- define $sentence at top of the page such as:
$sentence = '';
2- or use isset($sentence) before printing it:
<?php echo isset($sentence)? $sentence : ''; ?>