Cannot $_POST data to php file from a form - php

I am very new to html and php and need a little help. This is actually my first post on stackoverflow so I apologize if the content isn't done right.
I am asking for a username and password from a user and then I want to take that information and use it in a script that is run on the server via PHP.
The problem I'm having is that the first time a user goes to the html and fills out the form, the $_POST in the php file doesn't receive anything. I know that because I echoed the variables in the php file. But after the user presses the 'Back' button on the php page and returns back to the html, when going through it again, everything works fine.
So the code works, it just doesn't work the first time. Any ideas?
HTML:
<body>
<div class="loader" id="container" style="visibility:hidden;"></div>
<form method="post" action="Login_Page.php">
<b>Username:</b><input type="text" placeholder="University ID" name="userid" autofocus/>
<b>Password:</b><input type="password" placeholder="Password" name="pswrd"/>
<input type="submit" class="button" value="Submit" onclick="showDiv()"/>
</form>
</div>
</body>
CSS:
.loader {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url('https://cdn.shopify.com/s/files/1/1247/2733/t/4/assets/loading.gif?11916921113420493983') 50% 50% no-repeat rgba(255, 255, 255, 0.3);
filter: alpha(opacity=60);
}
Script:
<script type="text/javascript">
showDiv = function() {
document.getElementById("container").style.visibility="visible";
}
</script>
PHP:
<?php
$username = $_POST["userid"];
$pswrd = $_POST["pswrd"];
echo $username;
echo $pswrd;
$cmd = "path/to/script.sh $username $pswrd";
exec($cmd, $output, $return);
if ($return != "0") {
echo '<h1><b>Login was unsuccessful. Please try again.</b></h1>';
echo '<form>';
echo '<input type="button" value="Back" onClick="history.go(-1);return true;"/>';
echo '</form>';
} else {
echo '<h1><b>Login was Successful.</b></h1>';
}
?>

Could be the same problem as there: Onclick javascript stops form submit in Chrome.
It's caused by your onclick function at form submit.

So it ended up being a security certificate issue. I was trying to open up my website on an iPad and I didn't have the correct security certificate download on the iPad. This might sound weird but it has been consistently working after I did that. Thank you, everyone, for all of your helpful comments and assistance.

Related

Update mySQL - Wordpress HTML Form

How can I integrate an HTML form with a PHP script to update a value in mySQL?
How should I place the scripts for them to work together? Any guidelines for best practice?
I am failing to integrate the work. I tried everything I could think of but I am not able to make it work here is a list of what I tried so far:
Writing the script in functions.php which caused a fatal error.
Creating a new file named index1.php, still not integrating with the HTML form.
Putting index1.php in the form action, but still didn't work.
Something weird, as shown in the image, but still didn't work.
Form:
<div style="width:100%; margin:0 auto;background-color: #f8f8f8;">
<form action="index1.php" method="post">
<fieldset>
<div style="padding 10px;text-align:left;"> <textarea name="value" value="12"
placeholder="meow" style="padding: 5px;background-color: #f8f8f8"></textarea></div>
<div style="padding: 10px; text-align: right;">
<input type="submit" name="ins" value="Update" style="padding: 8px; background-color: #328269">
</div>
</fieldset>
</form>
</div>
PHP Script:
<?php
if (isset($_POST['ins'])) {
global $wpdb;
$data_array = array(
'value' => $_POST['value']
);
$table_name = 'P100';
$rowResult = $wpdb->update($table_name, $data_array);
if ($rowResult > 0) {
echo "Data Added Successfully!";
} else {
echo 'Error Occurred. Please try again.';
}
$wpdb->flush();
}
?>
My aim is to embed the form in a popup so that I can allow quick editing of the front end from the Popup when I display all my text in shortcodes retrieved from the database.

why is there a need to echo "recaptcha_get_html"?

all. I've been trying to integrate Google's reCAPTCHA, and seem to be failing when trying to echo recaptcha_get_html. It comes up with an undefined function error. I've looked everywhere and can't seem to get a straight answer. I'm semi-good with PHP, and don't fully understand everything. Can someone please explain how I can find the missing function. So my question is, is there a need to echo this function?. Here's my code:
<form class="" action="verify.php" method="post">
<input type="text" name="email" value=" enter email address" onFocus="if(this.value==' enter email address')this.value='';" style="height:18px; width:218px; color: #cccccc; border: 1 solid #000000; background-color: #5e5e5e; font: xx-small Verdana">
<br><br>
<?php
require_once('recaptchalib.php');
$publickey = "// Public Key";
echo recaptcha_get_html($publickey);
?>
<br>
<input type="submit" id="sendform" name='send' value=" send " style="cursor: hand; height:18px; border: 1 solid #000000; background-color:#5e5e5e; color: #cccccc; font: xx-small Verdana; font-weight:bold">
</form>
Thanks in advance.
Ok, first of all, no you do not need to echo that function!
As J-H meantioned, you might first want to update to the lastest version of recaptcha.
Here is how I implemented google recaptcha in php
$secret = "Your secret key";
$reCaptcha = new ReCaptcha($secret);
if ($_POST["g-recaptcha-response"]) {
$response = $reCaptcha->verifyResponse (
$_SERVER["REMOTE_ADDR"], $_POST["g-recaptcha-response"]);
}
if(!($response != null && $response->success)) ...
//it was successfully
Notice how I do not echo anything. Also, the public key should be in the html, the private key should be in the PHP. The public key should not be in the PHP, I do not know if that was a typo but that could also be another problem. Finally, it looks as though you are not using the html correctly for the google recaptcha api, atleast the new one.
Include <script src='https://www.google.com/recaptcha/api.js'></script>
in your header and <div style="margin:10px auto 0 auto; width:330px" class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
where you want the recaptcha to appear. Then you will have it all working. Cheers
It seems that you are working with the Version 1.0 which is no longer supported:
https://developers.google.com/recaptcha/old/docs/php

How to write a variable value in a text file with php

I have a problem with a php code. It's a simple web page hosted on my computer with two buttons and a text box. When I click + or - button the number in text box increase or decrease. Everything works as is suppose to, except when I want to write the textBox.value into a text file using php code. The result is something like "value = textBox.value" when it should be something like "value = 0". Thank you.
The code is below:
<!DOCTYPE html>
<html>
<body>
<input id="increaseNumber" type="button" value="+" style="font-size:24pt; width: 50px; height: 50px;"><br>
<input id="textBox" type="text" value="0" style="font-size:24pt; width: 40px; height: 40px;">
<label style="font-size:24pt;">℃</label><br>
<input id="decreaseNumber" type="button" value="-" style="font-size:24pt; width: 50px; height: 50px;"><br>
<script>
decreaseNumber.onclick = function() {
textBox.value = parseInt(textBox.value) -1
}
increaseNumber.onclick = function() {
textBox.value = parseInt(textBox.value) + 1
}
</script>
<?php
$myfile = fopen("/home/pi/test/test.txt", "w") or die("Unable to open file!");
$txt = "value = ";
fwrite($myfile, $txt);
$v = textBox.value;
fwrite($myfile, $v);
fclose($myfile);
?>
</body>
</html>
Brief Explanation:
You are trying to combine two separate languages as if both were client-side "as needed" scripting languages.
Javascript is client-side, and as such, will run based on event listeners or any other defined parameters. PHP is server-side, and as such, will run when the file is parsed. This means that your PHP is already processed and out of the picture by the time the Javascript even comes into the picture.
What is happening in your script presently:
The file is parsed, PHP is identified, and runs first. Immediately upon running, the file gets written to. PHP defaults to the text-value of "textBox.value" as it is not an actual variable (which would be preceded with $ if it were). In all honesty, it should be returning an error that "textBox.value" means nothing, essentially (PHP is not strict, so it makes a lot of assumptions). It's not, however, because it's assuming you are referencing a Constant. After the PHP is processed, the DOM is processed and sent to the browser. The PHP does not even exist at this point and has been stripped away from the DOM (rightfully so - you'd NEVER want PHP to be visible to a client).
What to do:
You cannot run this PHP snippet every time you want to increment/decrement the value with the PHP being inside of the same file (at least not without a form submit, or something to "catch" the request -- my response will be based on the fact that you simply want it to write when clicking, instead of submitting a form every time). You must change your code. One thing I'd suggest is placing the PHP inside of its own file. Then, upon incrementing/decrementing the value, you use AJAX to actually hit that file (thus triggering a file write).
Example:
index.html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<input id="increaseNumber" type="button" value="+" style="font-size:24pt; width: 50px; height: 50px;"><br>
<input id="textBox" type="text" value="0" style="font-size:24pt; width: 40px; height: 40px;">
<label style="font-size:24pt;">℃</label><br>
<input id="decreaseNumber" type="button" value="-" style="font-size:24pt; width: 50px; height: 50px;"><br>
<script>
$("#decreaseNumber").on("click", function() {
$("#textBox").val(parseInt($("#textBox").val()) -1);
writeToFile($("#textBox").val());
})
$("#increaseNumber").on("click", function() {
$("#textBox").val(parseInt($("#textBox").val()) +1);
writeToFile($("#textBox").val());
})
function writeToFile(value){
$.ajax({
url: 'write.php?v=' + value,
type: 'GET',
dataType: 'json',
success: function(ret){
alert('Success!');
},
error: function(ret){
alert('Error!');
}
});
}
</script>
</body>
</html>
write.php:
<?php
$myfile = fopen("/home/pi/test/test.txt", "w") or die("Unable to open file!");
$txt = "value = " . $_GET['v'];
fwrite($myfile, $txt);
fclose($myfile);
?>
Note the Changes:
I am using JQuery in my example. I apologize if you wanted strictly native Javascript.
Also please note, I changed the PHP. You had two writes, which was unnecessary and would take more time. File Input/Output is costly, and should be used minimally. In fact, in this example, I'd personally have just written to a database. However, you did not ask for a separate solution, so I simply provided an example similar to what you had written.
Random Thoughts
You can use decrement/increment instead of what you're doing as well. Like so:
<script>
decreaseNumber.onclick = function() {
textBox.value--;
alert(textBox.value);
}
increaseNumber.onclick = function() {
textBox.value++;
alert(textBox.value);
}
</script>
Here, you are getting value in javascript easily and in php if you want to get values then you have to post the form or send through parameters in URL.Here are some ways to passing data in php :
- Passing PHP variables with $_POST
- Passing PHP variables in links with $_GET
- Passing PHP variables without POST or GET | $_SESSION
- Passing PHP variables arrays from one page to another
- Passing PHP COOKIE variables
<!DOCTYPE html>
<html>
<body>
<form action="" method="post">
<input id="increaseNumber" type="button" value="+" style="font-size:24pt; width: 50px; height: 50px;"><br>
<input id="textBox" type="text" value="0" name="textBox" style="font-size:24pt; width: 40px; height: 40px;">
<label style="font-size:24pt;">℃</label><br>
<input id="decreaseNumber" type="button" value="-" style="font-size:24pt; width: 50px; height: 50px;"><br>
<input type="submit" name="submit" value="Write To File">
</form>
<script>
decreaseNumber.onclick = function() {
textBox.value = parseInt(textBox.value) -1
}
increaseNumber.onclick = function() {
textBox.value = parseInt(textBox.value) + 1
}
</script>
<?php
if(isset($_POST['submit'])){
$myfile = fopen("/home/pi/test/test.txt", "w") or die("Unable to open file!");
$txt = "value = ";
fwrite($myfile, $txt);
$v = $_POST['textBox'];
fwrite($myfile, $v);
fclose($myfile);
}
?>
</body>
</html>
To make php do this, you would need to submit the form. You can either do this via ajax or a normal post submit.
I've modified your code to work on a basic post submit.
Please read up on what a post method is.
I've had to make tiny changes in your HTML as well, and php.
I've commented them for ease.
You cannot combine two different languages to work together, not in this case at least. You could assign values from PHP to JAVASCRIPT variables, but not the other way around.
PHP has the ability to read values of input fields as long as they are submitted.
If you would like for PHP to write to the file every time the number is increased or decreased, you will have to do an ajax request to a php script on those particular events to get this done.(onClick)
<!DOCTYPE html>
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
$myfile = fopen("/home/pi/test/test.txt", "w") or die("Unable to open file!");
//You dont need to write twice, you can use both values in one single variable and write once
//added whitespce \r\n for line break
$v = $_POST['textbox'];
$txt = "value = $v";
fwrite($myfile, $txt);
fclose($myfile);
echo "written to file";
}
?>
<html>
<body>
<!--Made this a form so it can be submit to php-->
<!--Read about POST method-->
<form method="POST" action="">
<input id="increaseNumber" type="button" value="+" style="font-size:24pt; width: 50px; height: 50px;"><br>
<!-- Add the name attribute so php can read the value -->
<input name ='textbox' id="textBox" type="text" value="0" style="font-size:24pt; width: 40px; height: 40px;">
<label style="font-size:24pt;">℃</label><br>
<input id="decreaseNumber" type="button" value="-" style="font-size:24pt; width: 50px; height: 50px;"><br>
<input type='submit' value='Submit'/>
</form>
<script>
decreaseNumber.onclick = function() {
textBox.value = parseInt(textBox.value) -1
}
increaseNumber.onclick = function() {
textBox.value = parseInt(textBox.value) + 1
}
</script>
</body>
</html>
LINKS THAT WILL BE USEFUL TO YOU
$_POST - http://php.net/manual/en/reserved.variables.post.php
PHP FORM HANDLING - http://www.w3schools.com/php/php_forms.asp
AJAX REQUESTS - http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
You're mixing things up and it won't work like this.
First off, enclose your input boxes inside a <form> pointing to the PHP file that will handle the increase / decrease function, and write it to the test.txt file:
<form id="handler" method="post" action="handler.php">
<!-- Your input elements here -->
</form>
Also, you'll need to add the attribute name to your textBox element, you may call it nvalue, in example.
Second, your click event listeners are invalid. The correct to set them is:
document.getElementById("decreaseNumber").addEventListener("click", function() {
document.getElementById("textBox.value").value--;
document.getElementById("handler").submit();
});
The same goes for increaseeNumber
Third, put your php in your new handler.php file. Get the increase/decrease value with $_POST['nvalue']. Write this value to the file.
Note: You may also use AJAX for this, but it's a little more advanced and you'll also probably need a JS library like jQuery.
Note 2: You can redirect back from handler.php to your form page after updating test.txt file by using php header() function.
Note 3: You can make your <input id="textBox"> to show the current value in the file test.txt by loading it above and echoing value = "<?php echo $nvalue; ?>", of course, $nvalue is gotten using fread() or similar.

Trouble with form validation using PHP

I have a relatively simple sounding question that hopefully entails a simple answer. I am currently developing a website that is a scroll-down type; everything is on one page, you know the one. My 'contact' section is at the very bottom of the page, and I am of course doing form validation with PHP. The validation part works, I have no trouble with that. However, if validation fails, the browser takes me back all the way back to the top of the page; this is inconvenient for obvious reasons.
I am aware of the 'header()' function, which I can use to keep me at the bottom of the page if an error occurs. As an example, at the top of my HTML page before the DOCTYPE, I can write:
if ($errors) {
header(Location: 'somelocation.php#contact');
}
This works, but for some reason it prevents my PHP embedded in my html to work. If some errors occur, I want to display them using PHP on the page:
<h2>Contact</h2>
<?php if($errors) { ?>
<p class="warning">Please fix the errors</p>
<?php } ?>
'Please fix the errors' does not appear. It does appear however, if I remove the header function from the page, so I know the problem is related. So basically, if I remove the header() function, the page goes back to the top, and the errors show; if I keep the header() function, the page correctly stays where it is, but no errors show.
Alternatively, this question also can be asked in the case of, what happens when the form is validated correctly, the 'header' function is called, and I want to stay at the bottom of the page and display some HTML saying 'Thanks, your form has been submitted'? (I don't want to go to a 'thank-you' page or anything, just stay in the same spot and give a 'thanks' on the page) I assume I'd run into the same problem. Is there a solution to this?
Thanks in advance!
Specifying a location in the header will cause the browser to redirect to that URI. This is being called before any output is sent to the browser.
When the page is reset, $errors == false, so the paragraph isn't displayed.
It sounds like you need to integrate AJAX, or a mixture of server- and client-side code here.
A very simple and efficient way to validation of a form is using jquery, A perfect example of this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<style type="text/css">
* { font-family: Verdana; font-size: 96%; }
label { width: 10em; float: left; }
label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
p { clear: both; }
.submit { margin-left: 12em; }
em { font-weight: bold; padding-right: 1em; vertical-align: top; }
</style>
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
</script>
</head>
<body>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>A simple comment form with submit validation and default messages</legend>
<p>
<label for="cname">Name</label>
<em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />
</p>
<p>
<label for="cemail">E-Mail</label>
<em>*</em><input id="cemail" name="email" size="25" class="required email" />
</p>
<p>
<label for="curl">URL</label>
<em> </em><input id="curl" name="url" size="25" class="url" value="" />
</p>
<p>
<label for="ccomment">Your comment</label>
<em>*</em><textarea id="ccomment" name="comment" cols="22" class="required"></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit"/>
</p>
</fieldset>
</form>
</body>
</html>
Happy Coding.!!!

Invisible CAPTCHA not working, most likely incorrect PHP?

I am trying to incorporate an invisible CAPTCHA into my contact form, however I am not sure if it works.
My code is as follows...
HTML
<span class="test-field"><label for="test">Please leave blank</label>
<input type="text" name="test" id="test"/></span>
CSS
.test-field {Display: none}
PHP
<?php
if($_POST["test"]!=""){
header("Location: {$_SERVER[HTTP_REFERER]}");exit;
}
// Get Data
$f_name = strip_tags($_POST['f_name']);
$f_email = strip_tags($_POST['f_email']);
$f_message = strip_tags($_POST['f_msg']);
// Send Message
mail( "me#website.com", "Website Contact",
"Name: $f_name\nEmail: $f_email\nMessage: $f_message\n",
"From: My Website" );
?>
To test it, I did a few tests changing the...
f($_POST["test"]!="")
...to...
f($_POST["test"]="")
My PHP is not very good, but I am guessing this should not send the form through if the field is blank, but it does come through. Is there anything wrong with my PHP?
Thanks in advance.
As far as your specific question it doesn't make any sense. A user CAPTCHA is absolutely useless if it's hidden.
The term CAPTCHA stands for ...
Completely Automatic Public Turing Test to Tell Computers and Humans Apart
Notice it says humans ...
How can we test for human interaction if they can't see the CAPTCHA challenge? You Can't. Never-the-less .... here's a quick mock up of your code ... the CAPTCHA I left out since it make no sense. Take it from here ...
<?php
if ($_POST['test'] == "") {
header("Location: {$_SERVER['HTTP_REFERER']}");
} else {
// Get Data
$f_name = strip_tags($_POST['f_name']);
$f_email = strip_tags($_POST['f_email']);
$f_message = strip_tags($_POST['f_msg']);
}
?>
<html>
<head>
<style type="text/css">
#demo {
width: 250px;
height: 250px;
}
.test-field {
display: none;
width: 200px;
height: 200px;
}
#form label {
width: 50px;
float: left;
}
#form input {
width: 150px;
float: right;
}
</style>
</head>
<body>
<div id="demo">
<form name="form" id="form" action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<label for="test">Empty </label><input type="text" name="test" id="test"/><br/>
<label for="f_name">Name</label><input type="text" name="f_name" id="f_name"/><br/>
<label for="f_email">Email</label><input type="text" name="f_email" id="f_email"/><br/>
<label for="f_msg">Message</label><textarea rows="15" cols="30" name="f_msg" id="f_msg"></textarea>
<input type="submit" id="submit">
<div class="test-field"></div>
</form>
</div>
</body>
</html>
<?php var_dump($_POST) ?>
Try changing
if($_POST["test"]!=""){
to
if(isset($_POST["test"]) && $_POST["test"]){

Categories