$_POST is empty when submitting a form - php

<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.

Related

result shows up without validation

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)){.

Response must contain the AMP-Access-Control-Allow-Source-Origin header?

I am getting these errors in the browser
"Response must contain the AMP-Access-Control-Allow-Source-Origin
header"
and
"Form submission failed: Error: Response must contain the
AMP-Access-Control-Allow-Source-Origin header​​​"
php
<?php
if (isset($_POST['iletisimg'])) {
$status = 0;
$ip = $_SERVER['REMOTE_ADDR'];
$time = time();
if (empty($post->isim) || empty($post->mesaj) || empty($post->email)) {
$yorumcevap = "Lütfen tüm alanları eksiksiz doldurunuz!";
} else {
$yorumekle = $db->query("insert into iletisim (isim,mesaj,email,konu,durum,tarih,ip) values ('$post->isim', '$post->mesaj', '$post->email', '$post->konu', 0, '$time', '$ip')");
if ($yorumekle) {
$yorumcevapok = "Teşekkürler. Talebiniz alındı.";
} else {
$yorumcevap = "Hata! Lütfen tekrar deneyin.";
}
}
}
html
<html amp lang="tr">
<head>
<script async src="https://cdn.ampproject.org/v0.js"></script>
<script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script>
</head>
<body>
<form method="post" action-xhr="#" autocomplete="off">
<?PHP echo '<p>' . $yorumcevap . '</p>'; ?>
<input type="text" class="isim" name="isim" autofocus required>
<input type="text" class="isim" name="konu" required>
<input type="text" class="isim" name="email" required>
<textarea name="mesaj" cols="80" rows="8" required></textarea>
<input type="submit" value="Gönder" name="iletisimg">
</form>
</body>
</html>
How can I edit it this to avoid those errors ?
You need to ensure that your CORS settings meet the AMP requirements as documented here
There's also a similar question which provides the code on how to set the response headers properly:
AMP Access Control Allow Source Origin header Issue

How can I change an array value with a click?

I've seen references to Ajax for this, but I'm not entirely sure how I could integrate that with the arrays and still have a functioning system. I want to change the value of $place and $title each time a user presses the button, and I know that I'll need an if statement and some way of processing a form (no clicks in PHP), but I don't know anything else beyond that. I've pasted my PHP and the HTML button below:
<!DOCTYPE html>
<html>
<head>
<title>StatsCalc V1</title>
<link rel="stylesheet" type="text/css" href="sheen.css">
<link rel="script" type="text/javascript" href="slide.js">
<link rel="icon" type="image/png" href="favicon.ico">
<link href='http://fonts.googleapis.com/css?family=Raleway:500' rel='stylesheet' type='text/css'>
</head>
<body>
<?php
$place = 0;
$title = 0;
echo '<div class="boxes"><h1>Statistics Calculator: Version 1</h1></div>';
$links = array('<div class="fancyBoxes"><img class="mainPic" src="normalDist.svg" alt="a normal distribution, courtesy openclipart.org"></div>', "", "");
echo $links[$place];
/*if($_GET){
if(isset($_GET['clickies'])){
$place = 1;
$title = 1;
}
}*/
if($_POST['clickies'] and $_SERVER['REQUEST_METHOD'] == "POST"){
$place = 1;
$title = 1;
}
$subtitle = array('<div class="boxes"><h1>Standardised Score</h1></div>', '<div class="boxes"><h1>Standard Deviation</h1></div>', '<div class="boxes"><h1>Averages</h1></div>');
echo $subtitle[$title];
?>
<input type="submit" id="clickies" name="clickies" value="" />
<script src="move.js"></script>
<script src="slide.js"></script>
<script src="jquery-1.11.2.js"></script>
<!--The calculator must be able to field standardised score, standard deviation, and averages (mean/median/mode)-->
<!--Headings will be assigned with an array; slides will be navigated with tabs on either side of the window-->
<!--Credit to https://openclipart.org/detail/171055/normal-distn-shaded-outside-1s-by-oderwald-171055 for the Standardised Score image/label thingy-->
</body>
</html>
maybe this could give you idea on how to do it.
if($_SERVER['REQUEST_METHOD'] == "POST") {
if (isset($_POST['clickies'])) {
$count = intval($_POST['count']);
$count++;
$place = $count;
$title = $count;
}
} else {
$place = 0;
$title = 0;
}
echo '<div class="boxes"><h1>Statistics Calculator: Version 1</h1></div>';
$links = array('<div class="fancyBoxes"><img class="mainPic" src="normalDist.svg" alt="a normal distribution, courtesy openclipart.org"></div>', "", "");
echo $links[$place];
echo $place; echo "<br/>";
$subtitle = array('<div class="boxes"><h1>Standardised Score</h1></div>', '<div class="boxes"><h1>Standard Deviation</h1></div>', '<div class="boxes"><h1>Averages</h1></div>');
echo $subtitle[$title];
?>
<form action="" method="POST">
<input type="submit" id="clickies" name="clickies" value="" />
<input type="hidden" id="count" name="count" value="<?php echo $place;?>" />
</form>
what I did is need to put the button inside a form and put a method= post
and make it submit it to the same page
i also store the count in a hidden input and pass it always when the form is submitted and update its value on the form,
try to modify according to your need
<?php
$_SESSION["place"] = 0;
$place = 0;
$title = 0;
session_start();
echo '<div class="boxes"><h1>Statistics Calculator: Version 1</h1></div>';
$links = array('<div class="fancyBoxes"><img class="mainPic" src="normalDist.svg" alt="a normal distribution, courtesy openclipart.org"> </div>', "", "");
if($_POST['clickies'] and $_SERVER['REQUEST_METHOD'] == "POST"){
$_SESSION["place"] = $_SESSION["place"] + 1;
$title = 1;
}
echo $links[$_SESSION["place"]];
$subtitle = array('<div class="boxes"><h1>Standardised Score</h1></div>', '<div class="boxes"><h1>Standard Deviation</h1></div>', '<div class="boxes"><h1>Averages</h1></div>');
echo $subtitle[$title];
?>
<form method="post" action="">
<input type="submit" id="clickies" name="clickies" value="submit" />
</form>
you can use session of php.

PHP script not running inside a form tag

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>

PHP url Redirect

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>

Categories