I am making a user system on a website and I cannot get the form to post to the file.
Here is the form in the HTML file:
<form method="post" action="php/userlogin.php">
<p><input type="text" name="usernameL" value=""></p>
<p><input type="password" name="passwordL" value=""></p>
<p><input type="submit" name="submit" value="Login"></p>
</form>
And the userlogin.php in the php directory:
<?php
$username = $password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = test_input($_POST["usernameL"]);
$password = test_input($_POST["passwordL"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I'm new to forms and can't find an answer anywhere or even a question like this. How would I fix this?
You code is working fine.
The problem might be with the file structure. Please check that.
Ex: If your html file in the root folder of your project, Then the userlogin.php files should be there in project_root_folder/test/
So the file structure should be...
Root/
index.html
Test/
userlogin.php
Code is fine.
Just output the values of the variables.
echo $username.' '.$password;
You can see that the data is being posted.
Well your code seems to work perfectly fine, maybe the problem is with your testing enviroment, you need solution like XAMPP https://www.apachefriends.org/ to run php scripts on your computer. Other way is to run scripts remotely on some free webhosting that supports php.
If this is not the case then to check if actually data was sent, modify your code this way:
...
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = test_input($_POST["usernameL"]);
$password = test_input($_POST["passwordL"]);
echo $username."<br/>";
echo $password."<br/>";
}
...
Related
I'm having trouble submitting form data through VSCODE. So basically I have a nodejs program that runs on vscode and my goal is to submit some input data from that to a online form for example.
Run the program.js file in vscode
The file picks out a username field
Submits it to a online file through php
This is the HTML file & PHP file that writes input username data to data.txt
<!DOCTYPE html>
<html>
<BODY>
<form action = "submit.php" method="POST">
<p>
<input type = "text" name = "username" />
</p>
<input type = "submit" name="submit_btn" id = "submit" value = "Submit"/>
</form>
</BODY>
</html>
<?php
if(isset($_POST['submit_btn']))
{
$username = $_POST['username'];
$text = $username ."\n";
$fp = fopen('data.txt', 'a+');
if(fwrite($fp, $text)) {
echo 'saved';
}
fclose ($fp);
}
$lines = file("data.txt"); // Get the file as an array
$lines = array_unique($lines); // Merge all duplicate lines
// Save as a new file
$file = fopen("datacurated.txt", "w");
fwrite($file, implode("", $lines));
fclose($file);
?>
So the html file is not really important but I'm not so good at coding I was trying to send a post data request through vscode but didn't work.
I was wondering if it's possible to get rid of the html file and keep the php online and have it write the needed data. I need the delete duplicate text function in the php file as well.
Is this possible using AXIOS in vscode?
As the request package has been deprecated, install got instead.
Then your Node code:
(async () => {
const { body } = await got.post("https://www.website.com/submit.php", {
json: {
username: "Whatever..."
}
});
console.log(body);
})();
You don't care what www.website.com/submit.php is written in, but you have to be certain that that server will accept a Http Post request from your computer. It is trivial for them to obstruct what you are trying to do by filtering out your domain or by adding a Captcha.
I learning about programming, data transfer over the web and APIs. I created a simple model of a data transfer between two websites. I have three basic questions about the below process. In reviewing, assume both websites are setup with TLS.
Would the below simple process be a good secure architecture for data transfer between two websites?
Would this simple example be called an API?
In this example how could additional security be implemented (i.e. API Key etc..)?
Website 1 - A simple web form to capture and send data:
<!DOCTYPE HTML>
<html>
<head>
</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;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="include/redirect.php">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Website 1 Include file that runs on submissions of the form:
<?php
if (isset($_POST['name']) && $_POST['name']!="") {
$name = $_POST['name'];
$url = "https://localhost/api/api/".$name;
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($client);
$result = json_decode($response);
echo "<table>";
echo "<tr><td>Name:</td><td>$result->name</td></tr>";
echo "<tr><td>Amount:</td><td>$result->amount</td></tr>";
echo "<tr><td>Response Code:</td><td>$result->response_code</td></tr>";
echo "<tr><td>Response Desc:</td><td>$result->response_desc</td></tr>";
echo "</table>";
}
?>
Website 2 - Called in the include file: https://localhost/api/api/".$name;. Website 2 receives data and assigns an amount to it and returns the data.
<?php
header("Content-Type:application/json");
if (isset($_GET['name']) && $_GET['name']!="") {
$name = $_GET['name'];
}
else {
response(NULL, NULL, 400,"Can't process options now, visit local dealer");
}
if($name=="Joe"){
$amount = "700";
$response_code = "Good";
$response_desc = "Good";
response($name, $amount, $response_code,$response_desc);
}
else {
response(NULL, NULL, 200,"Can't process options now, visit local dealer");
}
function response($name,$amount,$response_code,$response_desc){
$response['name'] = $name;
$response['amount'] = $amount;
$response['response_code'] = $response_code;
$response['response_desc'] = $response_desc;
$json_response = json_encode($response);
echo $json_response;
}
?>
Would the below simple process be a good secure architecture for data transfer between two websites?
Yes, this can work. If you just want the two web servers to communicate with each other I would recommend limiting access to the script via a .htaccess file or a firewall though so it's not publicly accessible.
Of course, wherever possible calling methods via PHP instead of sending HTTP requests between scripts is more secure, faster and better in almost any way.
Would this simple example be called an API?
An application programming interface (API) is a connection between computers or between computer programs. It is a type of software interface, offering a service to other pieces of software.
From Wikipedia: API
Well yes, you have implemented an API. Your computer is able to communicate with the server to send and receive data and your two websites/servers can also communicate with and offer services to each other.
In this example how could additional security be implemented (i.e. API Key etc..)?
As I've mentioned earlier, depending on your requirements you can limit access to the API endpoint used for server to server communication ("https://localhost/api/api" in this case) to prevent someone other than your server from using it (Use a .htaccess file or check for the IP in the code)
Further, there are a few ways to prevent spoofing attacks in the server to server part of it, including (Source):
Using HTTP basic authentication (or OAuth if you want to go way further)
Using a shared secret (API Key)
Including a signature to verify the contents have not been changed (e.g. HMAC, see Is HMAC required when using TLS communication?)
This is by no means comprehensive, I hope it could povide some answers and points to research further.
I have a form inside the footer, I'm running the php file at the localhost 127.0.0.1/form.php, apparently if one uses php code inside HTML it will just be commented out. From what I understood at the PHP Documentation I need to run the php file directly.
The code is based on the W3Schools PHP Form Required tutorial:
<!DOCTYPE html>
<html>
<body>
<footer>
<form method="post" action="form.php">
<input type="text" name="name" placeholder="Name"><span class="form-error">*<?php echo $nameError;?></span><br>
<input type="submit" value="Send">
</form>
<?php
// define variables and set to empty values
$name = ""; // The variable is defined at the global scope
$nameError = ""; // The error variable is defined at the global scope
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($POST['name'])) {
$nameError = 'Name required'; }
else {
$name = test_input($_POST["name"]); }
}
// The function that will validate the form
function test_input($data) {
$data = trim($data); // The data is stripped of unnecesary characters
$data = stripslashes($data); // Backslashes '\' are removed
$data = htmlspecialchars($data); // Converts special characters into HTML entities
return $data
}
?>
If I left the text blank it wouldn't echo the error at the span, so I tried debugging it
<?php
// Debugging test_input($data)
echo $name;
echo "<br>";
echo $nameError;
echo "<br>";
?>
No matter what I submit at the input, the $name is always blank whereas the $nameError is always echoed.
So I thought that maybe the function isn't returning anything, and I did a little more debugging
// Debugging without the function
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
echo $name;
echo "<br>";
}
// Debugging after each iteration of whats inside the function (without return)
$data = trim($data); // The data is stripped of unnecesary characters
echo $name;
echo "<br>";
$data = stripslashes($data); // Backslashes '\' are removed
echo $name;
echo "<br>";
$data = htmlspecialchars($data); // Converts special characters into HTML entities
echo $name;
echo "<br>";
?>
If I introduce, for instance, & \ a my output is:
*a blank line*
Name required
& \ a
& \ a
& \ a
& \ a
Apparently the php built in functions aren't doing what they are supposed to do. stripslashes($data) did not remove the backslash and the & should look as & after going through htmlspecialchars($data).
I even commented everything inside test_input($data) so that it looked like this
function test_input($data) {
return $data }
And still would get nothing. Any ideas why? Also, why is the function test_input($data) defined later in the script instead of being defined before (tried to put it before defining my variables and still would not work). Thanks in advance.
"You have a typo: empty($POST['name']) should be empty($_POST['name'])" #Magnus Eriksson
"Because you define and set the variable $nameError after you're trying to echo it." #Magnus Eriksson
Recently I built a form using HTML, CSS, and JavaScript. I then entered the PHP required to send the data that is inputted in the form, to my database. After I finished, what I thought was necessary for it to work, I ended up with a blank page when I executed the code. The form and everything disappeared. This is my PHP code:
<?php
require("$_SERVER[DOCUMENT_ROOT]/connect.php");
$email = $username = $type = $question = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if(!empty($_POST))
{
if(isset($_POST["email"], $_POST["username"], $_POST["type"], $_POST["question"])
{
$email = test_input($_POST["email"]);
$username = test_input($_POST["username"]);
$type = test_input($_POST["type"]);
$question = test_input($_POST["question"]);
$premium = ($_POST["premium"]);
$member = $_POST["member"];
$terms = $_POST["terms"];
if ($member != "NO")
{
$member = "YES";
}
}
if(!empty($email) && !empty($username) && !empty($type) && !empty($question) && !empty($terms))
{
$insert = $db->prepare("INSERT INTO QuestionSubmission (Email, Username, Type, Question, Member, Premium, Date) VALUES (?, ?, ?, ?, ?, ?, NOW())");
$insert->bind_param("ssssss", $email, $username, $type, $question, $member, $premium);
if($insert->execute())
{
header("Location: landing.php");
die();
}
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
The "member" part is a check box where the user can optionally select to become a member. It is unchecked initially, and i've set a value of "NO" for that. Also, there is a hidden check box that is already checked with a value of NO...this is the "premium" check box. Lastly, there is a check box for agreeing to the terms. This is initially unchecked, but the user has to check it so it won't be empty and for the form to process.
Could you please explain what I have to do in order for my form to work properly?
Also, the " require("$_SERVER[DOCUMENT_ROOT]/connect.php"); " part is where my connection to the database code is located. This code and the form code is located in the same page.
Replace require("$_SERVER[DOCUMENT_ROOT]/connect.php"); with require_once $_SERVER[DOCUMENT_ROOT]."/connect.php");, you're not using a variable - the $_SERVER can't be used like you're using it. This is why you're getting a "blank page of death", if you check your error_log you'd see that it has a syntax-error because of it.
Furthermore, you're checking if(!empty($_POST)) - this could really be any POST-form. You should remove this code
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if(!empty($_POST))
{
as you're checking if the inputs are set just below the above code.
As a final note, when you're using die();, you should use exit; instead. They really do the same thing, but usage of die() is more for error-checking, like "Script can't run any further - die now!", while exit; is more like "I would like to stop the script from running now, I'm done - thanks!".
Normally it’s easier to include the processing code inside the form page. That way, if you encounter errors, you can:
allow the code to fall through to the form again
persist old values by using the value="…" attribute
Roughly it looks like this:
<?php
$email=$username=''; // etc
if(isset($_POST['submit'])) { // or whatever you name the submit button
// validate data
if(!$errors) {
// process
// new location
}
// retain values from above
}
?>
<form>
<label>Name: <input type="text" name="username" value="<?php print $username; ?>"></label>
<label>Email: <input type="text" name="email" value="<?php print $email; ?>"></label>
<!-- etc -->
<button type="submit" name="submit">Send Message</button>
</form>
For ease and management, you can put the PHP code above into a separate file to be included.
The problem your sample above is that although you do redirect to a new page on success, you don’t go anywhere otherwise.
If you want to do it with a separate processing script, you will need to conclude by redirecting back to the original form on failure. However, you will find that persisting old data is more difficult that way.
Can someone look over this code and tell me why I'm receiving "Undefined variable" messages from my debugger on lines 22-26? This code works fine on another server that runs php 5.2. My apache server, however, runs php5.5 and the same code won't write to the specified file. When I put a string value in for the parameters on lines 22-26, instead of referencing the empty form values, it works, so the problem is getting the input form values into the variables. I either get "undefined variable" or "undefined index". Here's my code:
<html>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Name: <input type="text" name="name"><br><br>
E-mail: <input type="text" name="email"><br><br>
Username(for ftp access): <input type="text" name="username"><br><br>
Password(for ftp access): <input type="password" name="password"><br><br>
Leave Your Feedback (Comments, Inquiries, Suggestions): <br>
<textarea rows="10" cols="50" name="text"></textarea>
<br><input type="submit" name="submit" value="Submit">
<?php
$file = fopen("data.html", "ab");
if(isset($_POST['name'])){ $name = $_POST['name']; }
if(isset($_POST['email'])){ $email = $_POST['email']; }
if(isset($_POST['username'])){ $username = $_POST['username']; }
if(isset($_POST['password'])){ $password = $_POST['password']; }
if(isset($_POST['text'])){ $text = $_POST['text']; }
echo fwrite($file, $name);
echo fwrite($file, $email);
echo fwrite($file, $username);
echo fwrite($file, $password);
echo fwrite($file, $text);
fclose($file);
?>
</form>
</html>
Everybody, thanks for your suggestions. Some of your solutions have solved the problem of getting rid of the annoying notices and warnings about undefined variables. However, the script still doesn't write to the file. When I used var_dump($_POST) it returns a full array of variables values that have been submitted with the form. However, the output from the script (number of bytes written to the file 00000) only shows up in the html when run from the console, debugger, or command line, but not when opened in a browser. I know the script is working properly when I can see it read so many bytes from the input form fields to the file in my browser, which isn't happening, so the script isn't working. It should work, I'm using xdebug and getting no errors.
Here's the output of the debugger:
<html>
<form method="post">
Name: <input type="text" name="name"></input><br><br>
E-mail: <input type="text" name="email"></input><br><br>
Username(for ftp access): <input type="text" name="username"></input><br><br>
Password(for ftp access): <input type="password" name="password"></input><br><br>
Leave Your Feedback (Comments, Inquiries, Suggestions): <br>
<textarea rows="10" cols="50" name="textx"></textarea>
<br><input type="submit" name="submit" value="Submit"></form>
//output of var_dump($_POST)
array(0) {
}
//output of fwrite()
00000</html>
The problem I'm having: the form is submitted with the values, but the variables I'm assigning in the script are not pointing to those values when the file is written. Btw, this script works fine on the php5.2 server and I can see the number of bytes written when I submit the form. Actually I've been using this script for quite a while on a number of different servers and it never gave me this problem until now. I usually hide the display of the script in the final html, but at least that way I know it's functioning properly.
The server where it works uses register_globals. Using it is bad practice (see the warning?)
Disable it, and fix the code. It works now because $_POST['name'] is accessible as $name.
$file = fopen("data.html", "ab");
$details = array('name', 'email', 'username', 'password', 'text');
foreach ($details as $var) {
if (!empty($_POST[$var])) {
fwrite($file, $_POST[$var]);
}
}
fclose($file);
On the 5.2 server, you might have warnings disabled.
You are only assigning values, if $_POST contains those keys, this is the problem.
The easiest way of checking and writing to file is using a foreach, like the code I pasted above.
If someone doesn't insert nothing into one of the post fields (like email) your related variable will never exists
Change your code as follows
$name = isset($_POST['name']) ? $_POST['name'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$username = isset($_POST['username']) ? $_POST['username'] : '';
$email = isset($_POST['password']) ? $_POST['password'] : '';
$text = isset($_POST['text']) ? $_POST['text'] : '';
This is a ternary operator: if the leftmost of the right operators is evaluated to True, it will assign to left operator the value after ?, otherwise the value after :
N.B.:
This is only one of the possible methods to avoid that kind of warning/error
you are not defining $name $email $username $password if appropriate post variables are not set, which consequently gives you undefined variable error
you might surpress that error with this:
if(isset($_POST['name'])){ $name = $_POST['name']; echo fwrite($file, $name);}
if(isset($_POST['email'])){ $email = $_POST['email']; echo fwrite($file, $email);}
if(isset($_POST['username'])){ $username = $_POST['username']; echo fwrite($file, $username);}
if(isset($_POST['password'])){ $password = $_POST['password'];
echo fwrite($file, $password);}
if(isset($_POST['text'])){ $text = $_POST['text']; echo fwrite($file, $text);}
if there is no $_POST['name'] there is no $name and you'll get the error.
you could use var_dump($_POST) to see if values are delivered correctly, also you could use
else { $name = ''; }
try this
<?php
$name = "";
$email= "";
$username= "";
$password= "";
$text = "";
$file = fopen("data.html", "ab");
if(isset($_POST['name'])){ $name = $_POST['name']; }
if(isset($_POST['email'])){ $email = $_POST['email']; }
if(isset($_POST['username'])){ $username = $_POST['username']; }
if(isset($_POST['password'])){ $password = $_POST['password']; }
if(isset($_POST['text'])){ $text = $_POST['text']; }
echo fwrite($file, $name);
echo fwrite($file, $email);
echo fwrite($file, $username);
echo fwrite($file, $password);
echo fwrite($file, $text);
fclose($file);
?>
Okay, thanks for the help everyone. I got rid of the annoying notices and warnings, and I solved my other problem while I was at it. The main problem was that I was running this server on Fedora for the first time and I hadn't set selinux settings to "permissive". I reconfigured my firewall after the change, and now I can see the script and it writes to the file.