Im making a quiz/madlibs kind of site so for everything works but the validation. Whenever the user enters a special character or leaves the input field empty there should be a a warning and the submit button shouldn't be allowed to show the end result.
right now when i enter for example a "?" and after that press the submit button it will show the end result with all the answers.
what did i do wrong with my validation? how can i make it so you cant leave it empty and use special characters.
I check the validation with this code:
<?php
$Input1 = $Input2 = $Input3 = $Input4 = $Input5 = $Input6 = $Input7 = "";
$Input1Err = $Input2Err = $Input3Err = $Input4Err = $Input5Err = $Input6Err = $Input7Err = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["Input1"])){
$Input1Err = "enter something.";
}else{
$Input1 = test_input($_POST["Input1"]);
if(!preg_match("/[^a-z0-9 _]+$/i", $Input1)){
$Input1Err = "only letters and white space allowed";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
} ?>
for every input I made a validation like this:
if(empty($_POST["Input1"])){
$Input1Err = "enter something.";
}else{
$Input1 = test_input($_POST["Input1"]);
if(!preg_match("/[^a-z0-9 _]+$/i", $Input1)){
$Input1Err = "only letters and white space allowed";
}
}
and here is the full html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Mad Libs</title>
<link rel="stylesheet" type="text/css" href="Site.css">
</head>
<body>
<h1 class="text">Quiz game</h1>
<div class="container">
<nav>
<ul>
<li>quiz</li>
</ul>
</nav>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<h1> quiz</h1>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
$Input1 = $_POST["Input1"];
$Input2 = $_POST["Input2"];
$Input3 = $_POST["Input3"];
$Input4 = $_POST["Input4"];
$Input5 = $_POST["Input5"];
$Input6 = $_POST["Input6"];
$Input7 = $_POST["Input7"];
echo "Driving a car can be fun if you follow this $Input1. advice:
When approaching a $Input2 on the right, always blow your $Input4 Before making a
$Input3 turn, always stick your $Input2 out of the window.
Every 2000 miles, have your $Input1.inspected and your $Input5 checked.
When approaching a school, watch out for $Input6.
Above all, drive $Input6 the $Input7 you save may be your own!$Input2";
?>
<?php }else{ ?>
<p>Question.. <input type="text" name="Input1" placeholder="enter here"></p>
<p>Question.. <input type="text" name="Input2" placeholder="enter here"></p>
<p>Question.. <input type="text" name="Input3" placeholder="enter here"></p>
<p>Question.. <input type="text" name="Input4" placeholder="enter here"></p>
<p>Question.. <input type="text" name="Input5" placeholder="enter here"></p>
<p>Question.. <input type="text" name="Input6" placeholder="enter here"></p>
<p>Question.. <input type="text" name="Input7" placeholder="enter here"></p>
<input type="submit" name="submit" value="Send">
</form>
<?php } ?>
<footer>
<p>#2021.</p>
</footer>
</div>
</body>
</html>
I think you dont have to validate if the input is text with spaces in the php. You could use the html input pattern attribute. For example:
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php">
<label for="maininput">Input</label>
<input type="text" id="maininput" name="maininput" pattern="[A-Za-z\s]+" title="Write Here your Error"><br>
<input type="submit">
</form>
</body>
</html>
In this example the input only accepts letters and spaces. You could also add number with changing the pattern to [A-Za-z0-9\s]+.
Plus if you really want to keep using php to validate the input I think the wrong is the validation in the line if(!preg_match("/[^a-z0-9 _]+$/i", $Input1)){.
Related
<html>
<head>
<!-- SCRIPTS -->
<script type="text/javascript" src="scripts/controller.js"></script>
<!-- STYLES -->
<link href="styles/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php
$errUrl = $videoId = "";
$start = $end = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
print_r($_POST);
if (isset($_POST["yt_url"])) {
echo "hello2";
$videoId = youtube_parser($_POST['yt_url']);
}
if (!$videoId) {
$errUrl = "URL is not valid!";
$videoId = "";
} else {
$errUrl = "";
}
//$start = $_POST['startH'] * 3600 + $_POST['startM'] * 60 + $_POST['startS'] * 1;
//$end = $_POST['endH'] * 3600 + $_POST['endM'] * 60 + $_POST['endS'] * 1;
}
function youtube_parser($url) {
$regExp = '/^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$/';
$match = preg_match($regExp, $url, $matches);
return ($match && strlen($matches[5]) === 11)? $matches[5] : false;
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="left">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<span class="error">* <?php echo $errUrl; ?></span><br>
URL: <input type="text" name="yt_url">
<br><br>
Start Time:<br>
<span class="label">Hour: </span><input value="0" type="number" name="start_h"><br>
<span class="label">Minute: </span><input value="0" type="number" name="start_m"><br>
<span class="label">Second: </span><input value="0" type="number" name="start_s">
<br><br>
End Time:<br>
<span class="label">Hour: </span><input value="0" type="number" name="end_h"><br>
<span class="label">Minute: </span><input value="0" type="number" name="end_m"><br>
<span class="label">Second: </span><input value="0" type="number" name="end_s">
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</div>
<div class="player"><?php
if (isset($videoId) && !empty($videoId)) {
echo '<iframe width="560" height="315" src="https://www.youtube.com/embed/$videoId?start=$start&end=$end" frameborder="0" allowfullscreen></iframe>';
}
?></div>
</body>
</html>
The above is what I have so far. I am attempting to learn php, and I have been working through the tutorials on w3schools I got to the part about working with forms, and none of the information is being passed in the $_POST array, I have set names for all of my DOM controls. Any insight would be greatly appreciated! I have a feeling it my have something to do with my PHP setup as even the provided example doesn't work.
Additional Information:
Web server running through Intellij PHPStorm.
php version is 7.0.9
Your code looks valid and when I tried it it shows expected output from $_POST array:
So it looks like you got problems with environment you are testing it on.
BTW <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
is wrong. Aside from spaghetti code, you should not use htmlspecialchars() here but urlencode()
(yet I'd use nothing _SERVER['PHP_SELF'] cannot be spoofed by client).
Also as #CarlJan suggested you may want to use isset($_POST['submit']) to check if your form was submitted as this will condition will only be true if your submit button is sent via POST. For now you are checking if this is POST request (in general) but it is not the same as it can be post from other form, or triggered by hand.
Hello Every One i am new to coding and now i am learning php and html below i submited the code and i want to print Hello World in a new page if the given user name and password is correct but it is printing in the same page can any one help me Thanks in Advance
<!doctype html>
<html>
<body>
<form action="#" method="post">
<input type="text" name="username" placeholder="Enter The Username"><br>
<input type="password" name="password" placeholder="Enter Password"><br>
<input type="submit" name="submit" value="Login">
<input type="reset" value="Cancel">
</form>
<?php
$a = 123;
$b = 234;
$c = $_POST["username"];
$d = $_POST["password"];
$e = "Hello World!!";
$f = "Error 404 Page Not Found";
if(isset($_POST['submit'])){
if ($a == $c && $b == $d )
{
print "$e";
}
else
{
echo "$f";
}
}
?>
</body>
</html>
you could use the header function and it would look like this:
if ($a == $c && $b == $d )
{
header("location: newpage.php");
exit;
}
else
{
echo "$f";
}
or indeed as stated above me redirect the form to the new page
First of all this will be the html part in a separate part like login.html:-
<!doctype html>
<html>
<body>
<form action="login.php" method="post"><!-- if you will not give action then form will posted to the same page -->
<input type="text" name="username" placeholder="Enter The Username"><br>
<input type="password" name="password" placeholder="Enter Password"><br>
<input type="submit" name="submit" value="Login">
<input type="reset" value="Cancel"><!-- about this i cannot say anything -->
</form>
</body>
</html>
Now in login.php:-
<?php
$original_user_name = 123; // take variable name that are self descriptive
$original_user_password = 234;
$form_username = $_POST["username"];
$form_password = $_POST["password"];
// $e = "Hello World!!"; no need of extra variable
// $f = "Error 404 Page Not Found"; no need of extra variable
if(isset($_POST['username']) && isset($_POST['password'])){ // check with POSTED values not with button value
if ($original_user_name == $form_username && $original_user_password == $form_password){
echo "hello World!";
}else{
echo "Error 404 Page Not Found!";
}
}else{
echo "please fill both user name and password!";
}
?>
Note:- both files must be in the same working directory.
Create a new .php file where you can put your PHP code & in the html file, change form tag to < form action="path of that php file" method="post">
I have recently installed Apache 2.4.7 server, as well as, PHP 5.5.10. I'm just beginning to learn PHP. I'm currently working through the w3school's tutorial on form processing with PHP, but I can't get a particular example to work. Does anyone here see an error?
<!DOCTYPE html>
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
Website: <input type="text" name="website"><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male<br>
<input type="submit">
</form>
</body>
</html>
When I visit this website, I get a quote and a greater than sign before the input field name specifically: "> Name. When I submit the form, the URL shows as
http://127.0.0.1/%3C?php%20echo%20$_SERVER[
I can't enter the exact contents of the URL, because this website won't let me, but the %3C actually shows up as a less than sign. The %20 shows up as a space. So, the problem is that the php script inside the action tag does not run. The action variable is then filled with the php script instead of the location of the current page. Why is the PHP script not running inside my form tag?
Solution:
Thank you everyone for helping. Abhik Chakraborty your comment led me to the solution. No, I did not save my file with a .php extension. I changed the extension to .php and it worked perfectly. I would have posted this as a solution, but I have to wait eight hours because I don't have enough reputation points.
If you leave action tag undefined it will use current location.
somefile.php:
<form method="post">
will execute the same uri
Replace action="<?php echo $_SERVER["PHP_SELF"];?>" by action=""
Remove action tag in your form. bcoz action is not mandatory for current page.
if u given $_SERVER['PHP_SELF'] . concatinate to your full path.
Try this one, this should work
<?php echo "<form method='post' action='".$_SERVER["PHP_SELF"]."' >";
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"
try this one this is the method posted on w3school to refer to self page at till now faced no problems with it.
you are not processing the data you can try this
<!DOCTYPE html>
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
Website: <input type="text" name="website"><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male<br>
<input type="submit">
</form>
Name: <?php echo $name?> <br />
Email: <?php echo $email?> <br />
Gender: <?php echo $gender?> <br />
Comment: <?php echo $comment?> <br />
Website: <?php echo $website?> <br />
</body>
</html>
I've written a PHP script for user login and I validate it using 2 users namely "test" and "admin". When the username and password is matched I redirect the page to UploadFile.php and DownloadFile.php. Though my script validates test and admin users by displaying the echo stmt present in the block, redirect is not working. What mistake have i done or should i follow any other method?
<!DOCTYPE html>
<html lang="en" class="no-js"> <!--<![endif]-->
<head>
<meta charset="UTF-8" />
<title>Login Page</title>
</head>
<body>
<h1>PHP & MySQL File Upload & Download </h1>
<br><br><br>
<form autocomplete="on" method="post">
<h1>Log in</h1>
<p>
<label for="userName" class="uname" data-icon="u" > Your email or username </label>
<input id="userName" name="userName" required="required" type="text" placeholder="myusername or mymail#mail.com"/>
</p>
<p>
<label for="userPass" class="youpasswd" data-icon="p"> Your password </label>
<input id="userPass" name="userPass" required="required" type="password" placeholder="eg. X8df!90EO" />
</p>
<p class="keeplogin">
<input type="checkbox" name="loginkeeping" id="loginkeeping" value="loginkeeping" />
<label for="loginkeeping">Keep me logged in</label>
</p>
<p class="login button">
<input type="submit" value="Login" id="sign" name="sign"/>
</p>
<p class="change_link">
Not a member yet ?
Join us
</p>
</form>
</body>
</html>
<?php
if (isset($_POST['sign'])) {
$uname = test_input($_POST["userName"]);
$upass = test_input($_POST["userPass"]);
if ((strcmp($uname, "test") == 0) && (strcmp($upass, "test") == 0)) {
header("Location: UploadFile.php");
echo "test user";
} else if ((strcmp($uname, "admin") == 0) && (strcmp($upass, "admin") == 0)) {
header('Location: DownloadFile.php');
echo "admin user";
} else {
echo "<script>
alert('Login Failed');
</script>";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Put the PHP code in front of the HTML code.
Calls to header() have to be placed before outputting anything! You are outputting lots of html before.
See any of these results for further information: https://www.google.de/search?q=headers+already+sent
You can't output headers after starting the body of the response. Try moving your PHP block to before the HTML begins.
On a side note, the fact that PHP isn't telling you this suggests your error reporting isn't verbose enough - you should see a warning similar to the one in this question. Try putting error_reporting(-1); at the top of your code, or changing the setting in php.ini.
Generally speaking, I agree with the usage of header() as a proper redirection mechanism (and, with the exception of the javascript you're injecting, you could move the entire PHP code block above the HTML to get the desired effect)
However, if you'd like to display some content for a short period of time (let's say 2 seconds) before performing the redirect, consider using the "meta-refresh" method, described here:
http://www.w3.org/TR/WCAG20-TECHS/H76
For example, in your current code, try changing:
header("Location: UploadFile.php");
to:
echo "<meta http-equiv=\"refresh\" content=\"2;URL='UploadFile.php'\" />";
Although the W3C page says you should place this element inside the "head" element, practical experience shows that the vast majority of browsers will respect your intentions of showing content then redirecting after the specified time interval.
If you decide to use this "meta" element and move your PHP code to the top of the file, I suggest plugging values in accordingly instead of echoing them immediately:
<?php
$meta_element = '';
$login_message = '';
if (isset($_POST['sign'])) {
$uname = test_input($_POST["userName"]);
$upass = test_input($_POST["userPass"]);
if ((strcmp($uname, "test") == 0) && (strcmp($upass, "test") == 0)) {
$meta_element = "<meta http-equiv=\"refresh\" content=\"2;URL='UploadFile.php'\" />";
$login_message = "test user";
} else if ((strcmp($uname, "admin") == 0) && (strcmp($upass, "admin") == 0)) {
$meta_elementt = "<meta http-equiv=\"refresh\" content=\"2;URL='DownloadFile.php'\" />";
$login_message = "admin user";
} else {
$login_message = "<script>
alert('Login Failed');
</script>";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!DOCTYPE html>
<html lang="en" class="no-js"> <!--<![endif]-->
<head>
<meta charset="UTF-8" />
<title>Login Page</title>
<?php echo $meta_element; ?>
</head>
<body>
<h1>PHP & MySQL File Upload & Download </h1>
<br><br><br>
<form autocomplete="on" method="post">
<h1>Log in</h1>
<?php echo $login_message; ?>
<p>
<label for="userName" class="uname" data-icon="u" > Your email or username </label>
<input id="userName" name="userName" required="required" type="text" placeholder="myusername or mymail#mail.com"/>
</p>
<p>
<label for="userPass" class="youpasswd" data-icon="p"> Your password </label>
<input id="userPass" name="userPass" required="required" type="password" placeholder="eg. X8df!90EO" />
</p>
<p class="keeplogin">
<input type="checkbox" name="loginkeeping" id="loginkeeping" value="loginkeeping" />
<label for="loginkeeping">Keep me logged in</label>
</p>
<p class="login button">
<input type="submit" value="Login" id="sign" name="sign"/>
</p>
<p class="change_link">
Not a member yet ?
Join us
</p>
</form>
</body>
</html>
In order to work properly my form needs to be set up to first check the validation and then post the data if the validation passes. This is fine but I am not sure how to combine the validation code with the post code in the form action. Example if the action is: action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> the form validates correctly but does not send anywhere! If I change the form action to action="contact-engine.php"> then the form is posted but without validation! With this in mind I need to combine into the action both the validation and then (once passed validation) the contact-engine.php problem is I simply do not know how to do this? I really am a learner in php and this is complicated for me! Any help is really appreciated I have been working on this from now for a few days! (N.B. both pages are .php) Full code is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Help!</title>
<style type="text/css">
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = "";
$name = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//Name
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}}
//Email
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" id="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p><span class="error">* required field.</span></p><br />
<div class="contact-font" style=" margin-top: 20px;">
<span class="asterix">* </span>Name:<br />
<input type="text" name="name" class="border" size="25" value="<?php if(isset($_POST['name'])) {echo $_POST['name']; } ?>">
<span class="error"><?php echo $nameErr;?></span>
</div>
<div class="contact-font" style=" margin-top: 20px;">
<span class="asterix">* </span>Email: (please double check enty)<br />
<input type="text" name="email" class="border" size="25" value="<?php if(isset($_POST['email'])) {echo $_POST['email']; } ?>"><span class="error">
<?php echo $emailErr;?></span>
</div>
<div>
<input type="submit" value="Send" id="submit">
</div>
</form>
</body>
</html>
And below is the contact-engine code:
<html>
<head>
<title>Contact Engine</title>
</head>
<body>
<br />Name:<?php echo htmlspecialchars($_POST['name']); ?><br />
<br />Email:<?php echo htmlspecialchars($_POST['email']); ?><br />
</body>
</html>
You can try this. This is a simple code below through which you can achieve this:
//sample index.php file
<?php
include 'submitted.php';
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<input type="text" name="foo" />
<input type="submit" value="submit">
</form>
</body>
</html>
Here, I am submitting the form to the same page using post method. But, I have included another file which is include 'submitted.php'.
Here is the test script inside the submitted.php
//sample submitted.php
<?php
if(isset($_POST['foo']))
{
if(strlen($_POST['foo']) < 5){
echo "String length too small";
}
else
{
echo $_POST['foo'];
}
}
?>
For test, it simply checks if the length is more than five or not. If it is not, the error message is displayed on the same page where your page is present.
Test it yourself too.