This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 7 years ago.
I'm building a form to be used to input data into a database. I have the basic form and validation built (I think). When I try testing it on my server/domain I keep getting the error undefined Index: Form Submit. I'm certain it's something minor, but I can't find my error. An extra set of eyes looking at this would be greatly appreciated.
<!DOCTYPE HTML>
<html lang = "en">
<head>
<link rel="stylesheet" type="text/css" href="mystylesheet.css">
<title>Tech Order Department.html</title>
<meta charset = "UTF-8" />
</head>
<body>
<!--Designing my form-->
<h2>New Projects</h2>
<br>
<?php
if($_POST['formSubmit'] == "Submit")
{
$varMovie = $_POST['formProject'];
$varMovie = $_POST['formClient'];
$varMovie = $_POST['formLastName'];
$varMovie = $_POST['formDateReceived'];
}
?>
<form action="myform.php" method="post">
Project:<br>
<input type="text" name="Project">
<br>
Client:<br>
<input type="text" name="Client">
<br>
Last Name:<br>
<input type="text" name="LastName">
<br>
Date Received:<br>
<input type="text" name="DateReceived">
<br><br>
<input type="submit" name="formSubmit" value="Submit">
</form>
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['formProject']))
{
$errorMessage .= "<li>You forgot to enter a project name!</li>";
}
if(empty($_POST['formClient']))
{
$errorMessage .= "<li>You forgot to enter a client name!</li>";
}
if(empty($_POST['formLastName']))
{
$errorMessage .= "<li>You forgot to enter the tech writer name!</li>";
}
if(empty($_POST['formDateReceived']))
{
$errorMessage .= "<li>You forgot to enter the date received!</li>";
}
$varMovie = $_POST['formProject'];
$varName = $_POST['formClient'];
$varMovie = $_POST['formLastName'];
$varMovie = $_POST['formDateReceived'];
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
}
?>
</body>
</html>
You should change :
if($_POST['formSubmit'] == "Submit")
To :
if(isset($_POST['formSubmit']) && $_POST['formSubmit'] == "Submit")
When you're using form, you should ALWAYS verify at least once posted that your fields are set.
For example :
We have this quick form :
<form action="action_page.php" method="POST">
First name:<br>
<input type="text" name="firstname" value="">
<br>
Last name:<br>
<input type="text" name="lastname" value="">
<br><br>
<input type="submit" value="Submit">
</form>
First note that on the I've put two attributes :
action : Which is where the form will be send
method : Which is how the form will be send
There are two inputs "firstname","lastname" and a button submit.
Let's say that on the "action_page.php" you want to display : "Hello, firstname lastname".
You could just do the following :
<?php
echo 'Hello, '.$_POST['firstname'].' '.$_POST['lastname'];
?>
And that will print out what you want.
But in the case where those fields would be empty that would create "Undefined Index"...
So to be sure that you won't be using variables that doesn't exist you should do the following :
<?php
//First we create an array that will errors if they occurs
$error = array();
//Then we test if firstname exist
if(isset($_POST['firstname'])) {
//if it does we can assign him.
$firstname = $_POST['firstname'];
}else{
//if it doesn't that's an error.
$error[] = 'Please enter your firstname';
}
//Then we test if lastname exist
if (isset($_POST['lastname'])) {
//if it does we can assign him.
$lastname = $_POST['lastname'];
}else{
//if it doesn't that's an error.
$error[] = 'Please enter your lastname';
}
//In the end we check if we have any error stocked:
if(empty($error)) {
//if it's empty we have all our required data to display our echo
echo 'Hello, '.$firstname.' '.$lastname;
}else{
//else let's show the error
print_r($error);
}
?>
This way we handle any possible "Undefined Index" before they occur and we are sure that our data will return something or at least have an error related.
For check if there was a POST action :-
if (!empty($_POST))
or
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Updated your code , check this
<!DOCTYPE HTML>
<html lang = "en">
<head>
<link rel="stylesheet" type="text/css" href="mystylesheet.css">
<title>Tech Order Department.html</title>
<meta charset = "UTF-8" />
</head>
<body>
<h2>New Projects</h2>
<?php
if ($_POST['formSubmit'] == "Submit") {
$varMovie = $_POST['formProject'];
$varMovie = $_POST['formClient'];
$varMovie = $_POST['formLastName'];
$varMovie = $_POST['formDateReceived'];
}
?>
<form action="myform.php" method="post">
Project:<br>
<input type="text" name="Project">
<br>
Client:<br>
<input type="text" name="Client">
<br>
Last Name:<br>
<input type="text" name="LastName">
<br>
Date Received:<br>
<input type="text" name="DateReceived">
<br><br>
<input type="submit" name="formSubmit" value="Submit">
</form>
<?php
if(isset($_POST['formSubmit']) && $_POST['formSubmit'] == "Submit") {
$errorMessage = "";
if (empty($_POST['formProject'])) {
$errorMessage .= "<li>You forgot to enter a project name!</li>";
}
if (empty($_POST['formClient'])) {
$errorMessage .= "<li>You forgot to enter a client name!</li>";
}
if (empty($_POST['formLastName'])) {
$errorMessage .= "<li>You forgot to enter the tech writer name!</li>";
}
if (empty($_POST['formDateReceived'])) {
$errorMessage .= "<li>You forgot to enter the date received!</li>";
}
$varMovie = $_POST['formProject'];
$varName = $_POST['formClient'];
$varMovie = $_POST['formLastName'];
$varMovie = $_POST['formDateReceived'];
if (!empty($errorMessage)) {
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
}
?>
</body>
</html>
Related
I have a problem. I don't know why when I did run the HTML and javascript only (without PHP part), the validation works really well. However, when I did run the PHP with the HTML and JavaScript, the validation doesn't work. For example, when the username is 123john (everything else such as password, name,... met the requirements) which is not allowed. The form still submitted successfully (I did check the MySQL database and the user 123john is there). Can someone help me with this? Thank you for your help.
The original code structure is the PHP and HTML are in the same file, only the JavaScript is on a separate file.
<?php
session_start();
require 'connect.php';
if(isset($_POST['register'])){
$username = !empty($_POST['user_name']) ? trim($_POST['user_name']) : null;
$pass = !empty($_POST['pass']) ? trim($_POST['pass']) : null;
$firstName = !empty($_POST['first_name']) ? trim($_POST['first_name']) : null;
$lastName = !empty($_POST['last_name']) ? trim($_POST['last_name']) : null;
$collegeName = !empty($_POST['uni']) ? trim($_POST['uni']) : null;
$majorName = !empty($_POST['major']) ? trim($_POST['major']) : null;
$sql = "SELECT COUNT(user_name) AS num FROM users WHERE user_name = :username";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
die('Username existed');
}
$sql = "INSERT INTO users (user_name, pass, first_name, last_name, uni, major) VALUES (:username, :password, :first_name, :last_name, :uni, :major)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $pass);
$stmt->bindValue(':first_name', $firstName);
$stmt->bindValue(':last_name', $lastName);
$stmt->bindValue(':uni', $collegeName);
$stmt->bindValue(':major', $majorName);
$result = $stmt->execute();
if($result){
echo 'Thank you for registering with our website.';
}
}
?>
var check_form=document.getElementById("registration");
var pattern=/^[a-zA-Z\s]+$/;
var patternUsername=/^[A-Za-z]\w*$/;
function check(event){
var userName=document.getElementById("username");
var passWord=document.getElementById("password");
var last_name=document.getElementById("lastName");
var first_name=document.getElementById("firstName");
var collegeName=document.getElementById("uni");
var majorName=document.getElementById("majoring");
event.preventDefault();
if(userName.value==""){
alert("User name needs to be specified");
userName.focus();
}
else{
if(!patternUsername.test(userName.value)){
alert("Invalid username");
userName.focus();
}
}
if(passWord.value==""){
alert("Password needs to be specified");
passWord.focus();
}
else{
if(passWord.length<8){
alert("Password needs to be longer than 8 characters");
passWord.focus();
}
}
if(first_name.value==""){
alert("First name needs to be specified");
first_name.focus();
}
else{
if(!pattern.test(first_name.value)){
alert("First name does not allow number");
first_name.focus();
}
}
if(last_name.value==""){
alert("Last name needs to be specified");
last_name.focus();
}
else{
if(!pattern.test(last_name.value)){
alert("Last name does not allow number");
last_name.focus();
}
}
if(collegeName.value==""){
alert("College name needs to be specified");
collegeName.focus();
}
else{
if(!pattern.test(collegeName.value)){
alert("Invalid college name");
collegeName.focus();
}
}
if(majorName.value==""){
alert("Major name needs to be specified");
majorName.focus();
}
else{
if(!pattern.test(majorName.value)){
alert("Invalid major name");
majorName.focus();
}
}
/*
if(first_name.value!=="" && last_name.value!==""&&email!==""&&pattern.test(first_name.value)&&pattern.test(last_name.value)){
alert("Perfect");
}
*/
}
check_form.addEventListener("submit",check);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Register</title>
<!--<link rel="stylesheet" href="./register.css">-->
<script src="./script.js" defer></script>
<style>
form div{
padding: 8px;
}
</style>
<link href="https://fonts.googleapis.com/css2?family=PT+Sans&display=swap" rel="stylesheet">
</head>
<body>
<h1>Register</h1>
<form id="registration" action="register.php" method="post">
<div id='userName'>
<label for="username">Username: </label>
<input type="text" id="username" name="user_name"><br>
</div>
<div id="passWord">
<label for="password">Password: </label>
<input type="text" id="password" name="pass"><br>
</div>
<div id='firstname'>
<label for="firstName">First Name: </label>
<input type="text" id="firstName" name="first_name"><br>
</div>
<div id="lastname">
<label for="lastName">Last Name: </label>
<input type="text" id="lastName" name="last_name"><br>
</div>
<div id="uniName">
<label for="uni">College Name: </label>
<input type="text" id="uni" name="uni"><br>
</div>
<div id="majorName">
<label for="majoring">Major: </label>
<input type="text" id="majoring" name="major"><br>
</div>
<br>
<input type="submit" name="register" value="Register"><br><br>
Already have an account?
</form>
</body>
</html>
If you want to do your client-side validation. you must change the type of the button from (send) to (button). Then, create a function in JS to validate your form.
Call the function by clicking onclick button = "ItsFunctionForValidateAndSubmit ()".
After checking: Create a form submission method using javascript.
Here is a link to some sample form submissions.
Send POST data using XMLHttpRequest
<input type="buttom" name="register" value="Register" onclick="ItsFunctionForValidateAndSubmit()">
I have the below code which calls a .php file to insert data into a MySQL database, but cant seem to get the .php file to run. Any suggestions?
I am very new to script so i am trying this registration form example. The database, 'college', with its table, 'registration', seems to be fine, but no php code executes. It must be something really simple but i cant seem to work it out?
$(document).ready(function() {
$("#register").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || email == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
} else if ((password.length) < 8) {
alert("Password should atleast 8 character in length...!!!!!!");
} else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
} else {
//alert(name); //This line reads fine
$.post("register.php",
{
name1: name,
email1: email,
password1: password
},
function(data) {
if (data == 'You have Successfully Registered.....') {
$("form")[0].reset();
}
alert(data);
});
}
});
});
<?php
$connection = mysql_connect("localhost", "root", "Winchester12"); // Establishing connection with server..
$db = mysql_select_db("college", $connection); // Selecting Database.
$name=$_POST['name1']; // Fetching Values from URL.
$email=$_POST['email1'];
echo $email;
$password= sha1($_POST['password1']); // Password Encryption, If you like you can also leave sha1.
// Check if e-mail address syntax is valid or not
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Sanitizing email(Remove unexpected symbol like <,>,?,#,!, etc.)
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "Invalid Email.......";
}else{
$result = mysql_query("SELECT * FROM registration WHERE email='$email'");
$data = mysql_num_rows($result);
if(($data)==0){
$query = mysql_query("insert into registration(name, email, password) values ('$name', '$email', '$password')"); // Insert query
if($query){
echo "You have Successfully Registered.....";
}else
{
echo "Error....!!";
}
}else{
echo "This email is already registered, Please try another email...";
}
}
mysql_close ($connection);
?>
<!DOCTYPE html>
<html>
<head>
<title>Squash Registration Form</title>
<meta name="robots" content="noindex, nofollow">
<!-- Include CSS File Here -->
<link rel="stylesheet" href="style.css"/>
<!-- Include JS File Here -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="registration.js"></script>
</head>
<body>
<div class="container">
<div class="main">
<form class="form" method="post" action="#">
<h2>Squash Registration Form</h2>
<label>Name :</label>
<input type="text" name="dname" id="name">
<label>Email :</label>
<input type="text" name="demail" id="email">
<label>Password :</label>
<input type="password" name="password" id="password">
<label>Confirm Password :</label>
<input type="password" name="cpassword" id="cpassword">
<input type="button" name="register" id="register" value="Register">
</form>
</div>
</body>
</html>
It could be a path related issue.
you might want to review the path to the register.php file to be sure its in the right place.
It seems that nothing is passed to register.php file. Please try with 'ajax' instead of jquery post.
I have made two pages. I have used php form validation in my first page, i.e., form.php and I have to give action on second page i.e., data_ins.php. Please let me know how will it possible with my coding.
Here are my pages:
form.php
<?php $fnameErr = $lnameErr = "";
$fname = $lname= ""; if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST['fname']))
{
$fnameErr = "First Name is required";
}
else
{
$fname= formVal($_POST['fname']);
}
if(empty($_POST['lname']))
{
$lnameErr = "Last Name is required";
}
else
{
$lname= formVal($_POST['lname']);
} }
function formVal($data)
{
$data = trim($data);
$data = stripcslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?> <!DOCTYPE html> <html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
First Name:
<input type="text" name="fname"> <span style="color:red;"><?php echo $fnameErr ?></span> <br>
Last Name:
<input type="text" name="lname"> <span style="color:red;"><?php echo $lnameErr ?></span> <br>
<input type="submit" name="submit">
</form>
</body> </html>
data_ins.php
<?php $conn = mysqli_connect("localhost","root","","test_db");
$sql = "insert into records (FirstName, LastName) values ('$fname', $lname)";
if($result=mysqli_query($conn, $sql))
{
echo "Data Inserted Successfull";
}
else
{
echo "Invalid";
}
mysqli_error($conn); ?>
Personally, I think you may of made it harder than you needed to.
Here is what I'd do with the PHP side:
if (isset($_POST['submit']))
{
if (!empty($_POST['fname']))
{
if (!empty($_POST['lname']))
{
// Add Database insert code here..
} else {
echo "Last name is required";
}
} else {
echo "First name is required";
}
}
As for the form, you don't need to add the PHP self (just add the method) like so:
<form method="POST" action="">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
<input type="submit" name="submit">
</form>
Hope this helps more so than your initial idea of doing it.
PLEASE NOTE: I haven't added the $data trim etc in but you'd add these in firstly where // do code note is.
1.change your form like this
`<form method="POST" action="location of your data_ins.php">`
2.in your data_ins.php must have database config code or include it.
3.get your all form value in data_ins.php pass to insert query
<form method="POST" action="">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
<input type="submit" name="submit">
</form>
Besides your code, your method (as question is not about it).
To execute other .php file you can use PHP statements:
require
include
include_once
In your case require should be the one to use, like: require 'data_ins.php'; after validation.
Need quick help, if anyone can...
I have a quite simple html one page with form
and I'm trying to validate it with php (check blanks and verify email)
for some reason something going wrong and it doesn't show me anything
on action form
anyone have any idea? will really help me a lot.
the icons present the obvious (the text is hebrew)
(if someone knows how to validate phone, bless you as well)
the html:
<!DOCTYPE html>
<html lang="he" dir="rtl">
<head>
<title>Safari Company</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="js/script.js"></script>
</head>
<body>
<div id="top-wrapper">
<div id="top-background">
<p class="image-text">.אפריקה. נקודת מבט חדשה</p>
<p class="credit-english">Ziv Koren</p>
</div>
</div>
<div id="costumer-wrapper">
<div id="info-for-client">
<p class="secondary-text">הדרך לאפריקה מתחילה בטיסה ישירה לטנזניה</p>
<p class="offer-text">פסח 2015 <span>|</span> 9 ימים מלאים</p>
<p class="ratz-border-above">ספארי קומפני בטיסת (סאנדור) אל-על ישירה לטנזניה וחזרה ישירות מזנזיבר. מבחר תוכניות ספארי מותאמות באופן אישי.</p>
<p class="strong">תמיד אמרתם שפעם תעשו את זה. עכשיו זה הזמן</p>
<p class="secondary-text">למידע נוסף, התאמת ספארי אישי </br> והזמנות 03-5617021</p>
</div>
<form method="post" action="confirmation.php" name="myForm" onsubmit="return validate();">
<input type="text" class="name" name="Name" placeholder="שם">
<input type="text" class="email" name="Email" placeholder="דוא״ל" >
<input type="text" class="phone" name="Phone" placeholder="טלפון" >
<textarea placeholder="הערות"></textarea>
<input type="checkbox" > ארצה לקבל עדכונים וחדשות
<button type="submit"> שלח</button>
</form>
<p class="hebrew-credit">זהות ושפה - מוסנזון פורת</p>
</div>
<div id="bottom-background">
<div id="bottom-image"> </div>
<p class="credit-english"></p>
</div>
<div id="footer-wrapper">
<footer>
<p>ספארי, בשפה הסווהילית, פירושו מסע, בשפה שלנו, מסע פירושו יציאה לדרך של גילויים חדשים, מראות, ריחות, טעמים.</br>
תחושה שאין דומה לה. לגלות את אפריקה, בכל פעם מחדש, כבר 20 שנה. נשמח להיות הדרך שלכם לאפריקה.</p>
<p class="adress-border-above"> סעדיה גאון 24, תל אביב טל. 03-5617021 פקס. 15335468614 <span> | www.safaricompany.co.il | info#safaricompany.co.il</span></p>
<img src="images/logo.png">
</footer>
</div>
</body>
<script>
function validate(){
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.Email.value == "" )
{
alert( "Please provide your Email" );
document.myForm.Email.focus() ;
return false;
}
if( document.myForm.Phone.value == "" )
{
alert( "Please provide your Phone" );
document.myForm.Phone.focus() ;
return false;
}
return true;
}
</script>
</html>
the php:(confirmation.php)
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
$name = trim($_POST["Name"]);
$email = trim($_POST["Email"]);
$phone = trim($_POST["Phone"]);
if( $name == "" || $email=="" || $phone==""){
echo "Please fill name, email and phone";
exit;
}
require_once("Inc/phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
if(!$mail -> ValidateAddress($email)){
echo "You must specify a valid email.";
exit;
}
?>
<html>
<body>
Welcome <?php echo $_POST["Name"]; ?><br>
Your email address is: <?php echo $_POST["Email"]; ?>
</body>
</html>
It probably is overkill to use a custom library just to verify an email address. You could use https://secure.php.net/filter_var with the FILTER_VALIDATE_EMAIL filter. As far as I know, there is no real way of validating phone numbers.
That being said, your PHP error is that you do not close the if statement started on line 2. That causes an unexpected end, as the compiler still wants a closing accolade for your if statement.
EDIT: There is a very good SO answer for validating phone numbers.
There are a few things going on with the approach to your script.
Here is what I came up with that works on the script page.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["Name"]);
$email = trim($_POST["Email"]);
$phone = trim($_POST["Phone"]);
if( $name == "" || $email=="" || $phone==""){
$error = "Please fill name, email and phone";
}
}
else {
$error = "ERROR if someone came here directly";
}
?>
<html>
<body>
<?php if(isset($error)): ?>
<p><?php echo $error; ?></p>
<?php else: ?>
Welcome <?php echo $_POST["Name"]; ?><br>
Your email address is: <?php echo $_POST["Email"]; ?>
<?php endif; ?>
</body>
</html>
EDIT: To address the email validation you would use this to check if true or false:
This method checks if the email is NOT valid.
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailError = "Invalid email";
}
So I have an index.php and a r.php. R.php is the registration part. And index.php is the actual form. My question is how can I have errors from r.php be send back to index.php if they exist. So instead of displaying errors on r.php I want them on index.php and prevent the form from advancing.
Here's the index.php
<!DOCTYPE html>
<html>
<body>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
Its all very simple. Now here's r.php
<?php
$name = $_POST['name'];
if ($name < 3){
//display error
}
else {
//proceed
}
?>
Should I do this with JS? Or this there a better way.
One way is to use sessions:
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<body>
<?php echo isset($_SESSION['message']) ? $_SESSION['message'] : ''; ?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
<?php
session_start();
unset($_SESSION['message']);
$name = $_POST['name'];
if ($name < 3){ // you probably want strlen($name) < 3
$_SESSION['message'] = 'error';
header('Location: index.php');
exit;
}
else {
//proceed
}
?>
Other than sessions you could redirect back with a query string and use that:
header('Location: index.php?message=' . urlencode('some kind of error');
Then:
<?php echo isset($_GET['message']) ? $_GET['message'] : ''; ?>
Using a single script for this would be easier, just put this all in one file, and check to see if the form has been submitted. If the form has been submitted, you an just include the variables you want straight away.
This is pretty crude, but it gives you an idea of where you can go with this:
<?php
if (isset($_POST['name'])) {
// Begin processing form stuff
$name = $_POST['name'];
// Initialise error variable
$error = null;
if ($name < 3) {
// Display error, for example:
$error = 'Name is less than 3';
} else {
// Proceed
}
}
?>
<!DOCTYPE html>
<html>
<body>
<?php if ( ! empty($error)) { ?>
<p><?php echo $error; ?></p>
<?php } ?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<?php
$msg = '';
if(isset($_GET['e'])
{
$msg = "Error! Input not valid.";
}
?>
<body>
<?php
if($msg!='')
{
echo "<font color='red'>".$msg."</font>";
}
?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
Just pass a variable e using GET request to the index page if an error is found.
<?php
$name = $_POST['name'];
if ($name < 3){
header("Location: index.php?e=error");
}
else {
//proceed
}
?>
GET request will send the variable e using the URL, and if e is found to be having a value, it means there was an error in r.php
Use javascript for simple form validation. In case you require some security stuff or db stuff, you can use session/cookie or use header function to go back.