Error when submitting input to a txt file in php - php

I am working on a input storer.
It does not write to the txt document with this code:
<?php
if (isset($_GET['test0'])) {
$file = 'content.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new line to the file
$current .= "\n" . "(TEST0)". $_GET['test0'] . "(TEST1)". $_GET['test1'];
// Write the contents back to the file
file_put_contents($file, $current);
}
?>
It is supposed to take the values from a <input> and store them. It isn't working, though. Here is the HTML:
<form action="" method="post" class="proceed maskable" name="login" autocomplete="off" novalidate>
<div id="passwordSection" class="clearfix">
<div class="textInput" id="login_emaildiv">
<div class="fieldWrapper"><label for="email" class="fieldLabel">Test0</label><input id="email" name="test0" type="email" class="hasHelp validateEmpty "
required="required" aria-required="true" value="" autocomplete="off" placeholder="Email" /></div>
<div class="errorMessage" id="emailErrorMessage">
<p class="emptyError hide">Blank</p>
<p class="invalidError hide">Blank</p>
</div>
</div>
<div class="textInput lastInputField" id="login_passworddiv">
<div class="fieldWrapper"><label for="password" class="fieldLabel">Test1</label><input id="password" name="Test0" type="password" class="hasHelp validateEmpty "
required="required" aria-required="true" value="" placeholder="Password" /></div>
<div class="errorMessage" id="passwordErrorMessage">
<p class="emptyError hide">Blank</p>
</div>
</div>
</div>
</form>
How can I solve this problem.
Thanks!

Try this :
<?php
if (isset($_GET['test0'])) {
$current = "\n" . "(TEST0)". $_GET['test0'] . "(TEST1)". $_GET['test1'];
$myfile = fopen("content.txt", "a") or die("Unable to open file!");
fwrite($myfile, $current);
fclose($myfile)
}
?>

Check the content.txt file permission
if (isset($_GET['test0'])) {
$file = __DIR__.'/content.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new line to the file
$current .= "\n" . "(TEST0)". $_GET['test0'] . "(TEST1)". $_GET['test1'];
// Write the contents back to the file
file_put_contents($file, $current);
}
?>

Related

html form will not write to file (php script)

I have an HTML file that contains the following form:
<form action="" class="contact-form">
<div class="input-group tm-mb-30">
<input name="username" type="text" class="form-control rounded-0 border-top-0 border-end-0 border-start-0" placeholder="Name">
</div>
<div class="input-group tm-mb-30">
<input name="email" type="text" class="form-control rounded-0 border-top-0 border-end-0 border-start-0" placeholder="Email">
</div>
<div class="input-group tm-mb-30">
<textarea rows="5" name="message" class="textarea form-control rounded-0 border-top-0 border-end-0 border-start-0" placeholder="Message"></textarea>
</div>
<div class="input-group justify-content-end">
<input type="submit" class="btn btn-primary tm-btn-pad-2" value="Save">
</div>
</form>
It seems fine to me. I also have a php script:
> <?php
extract($_REQUEST);
> $file=fopen("form.txt.", "a");
fwrite($file, "----");
fwrite($file," name :");
fwrite($file, $username ."\n");
fwrite($file," email :");
fwrite($file, $email ."\n");
frwite($file," message .:");
fwrite($file, $message ."\n");
fclose($file);
> ?>
Both are in the same file, the form in between html tags, the php script after the /html tag.
If will not execute. No matter what I do, form.txt remains empty. form.txt is in the same directory and has 777.
Since I cannot find any problem with the script (there are no error messages in the apache log file), I am wondering if there is something wrong with the php on this server (there are also no entries in syslog). phpinfo page displays fine, and php --version tells me 8.2.1 is running.
I then changed action in form to "form.php" and added method=POST to test with separate script. form.php was simply:
<?php
echo "NAME:";
echo $username;
echo "EMAIL:";
echo $email;
echo "MESSAGE:";
echo $message;
echo "POSTNAME:";
echo $_POST['username'];
echo "POSTEMAIL:";
echo $_POST['email'];
echo "POSTMESSAGE:";
echo $_POST['message'];
?>
I did not get any output for the first three entries. But I got output for the last three entries. I expected to get output for all - since the form, by sending the inputs, should automatically create/define those variables. Am I wrong?
I then added this to form.php (in front of the code mentioned above) in order to define the variables:
if(isset($_POST['submit']))
{
//fetch form data
$username = $_POST['username'];
$email = $_POST['email'];
$message = $_POST['message'];
}
because I thought defining them would solve the problem. It did not. When executing form.php (by sending the form in the html), apache.log now tells me that $username, $email and $message are not defined. But I just defined them.... ärx
Remove the last dot (.) from filename form.txt.
WRONG FILE NAME form.txt.
$file=fopen("form.txt.", "a");
CORRECT FILE NAME
$file=fopen("form.txt", "a");
Now all entries will go to form.txt file.
Full Code is shared here:
Add form method as POST and add name='submit' to submit button
<form action="" class="contact-form" method="post">
<div class="input-group tm-mb-30">
<input name="username" type="text" class="form-control rounded-0 border-top-0 border-end-0 border-start-0" placeholder="Name">
</div>
<div class="input-group tm-mb-30">
<input name="email" type="text" class="form-control rounded-0 border-top-0 border-end-0 border-start-0" placeholder="Email">
</div>
<div class="input-group tm-mb-30">
<textarea rows="5" name="message" class="textarea form-control rounded-0 border-top-0 border-end-0 border-start-0" placeholder="Message"></textarea>
</div>
<div class="input-group justify-content-end">
<input type="submit" class="btn btn-primary tm-btn-pad-2" value="Save" name="submit">
</div>
</form>
If form is submitted then write to file. Also you have typo mistake in frwite which is corrected too here.
if(isset($_POST['submit'])){
extract($_REQUEST);
$file=fopen("form.txt", "a");
fwrite($file, "----");
fwrite($file," name :");
fwrite($file, $username ."\n");
fwrite($file," email :");
fwrite($file, $email ."\n");
fwrite($file," message .:");
fwrite($file, $message ."\n");
fclose($file);
}
So this solved it for me:
I added "name=submit" to the submit input in HTML. The form posts to form.php, which now looks like this:
<html>
<body>
<?php
// turn on error reporting
ini_set('error_reporting', 'on');
error_reporting(E_ALL);
// Remove all illegal characters from email
// $email_address = filter_var($email_address, FILTER_SANITIZE_EMAIL);
// check if form has been submitted
if(isset($_POST['submit']))
{
//fetch form data
$username = $_POST['username'];
$email = $_POST['email'];
$message = $_POST['message'];
//write form data
$fp = fopen('form.txt', 'a');
fwrite($fp, "---");
fwrite($fp,"name :");
fwrite($fp, $username ."\n");
fwrite($fp," email :");
fwrite($fp, $email ."\n");
fwrite($fp," message :");
fwrite($fp, $message ."\n");
fclose ($fp);
}
//show submitted data
echo "NAME:";
echo $username;
echo "<br>";
echo "EMAIL:";
echo $email;
echo "<br>";
echo "MESSAGE:";
echo $message;
echo "<br>";
echo "POSTNAME:";
echo $_POST['username'];
echo "<br>";
echo "POSTEMAIL:";
echo $_POST['email'];
echo "<br>";
echo "POSTMESSAGE:";
echo $_POST['message'];
echo "<br>";
// extract($_REQUEST); might need to be added
?>
The data has been submitted - thanks
</body>
</html>
For some reason, the extract command seems unnecessary; it works fine without it, but I am not sure why. Anyhow, the data is now processed into the file. I got it. Thanks so much, everyone!

How to insert images with text data to database in php using mysql.?

I have a long-form with some images upload areas. I need to insert images with text data to MySQL database The form and query code as follows. If PHP codes are not correct, tell me how to do it correctly.?
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="form_main">
<h4 class="heading"><strong>Add</strong> Vehicle <span></span></h4>
<div class="form">
<form action="insert.php" method="POST" id="contactFrm" enctype="multipart/form-data" name="contactFrm">
<select class="form-control form-control-lg" name="brand">
<option value="TATA" >TATA</option>
<option value="TOYOTA">TOYOTA</option>
<option value="DAIHATSu">DAIHATSU</option>
</select>
<input type="text" required="" placeholder="Model" name="model" class="txt">
<div class="form-group">
<label for="exampleFormControlFile1">Front</label>
<input type="file" name="vehi_front" class="form-control-file" id="exampleFormControlFile1">
</div>
<div class="form-group">
<label for="exampleFormControlFile1">Left</label>
<input type="file" name="vehi_left" class="form-control-file" id="exampleFormControlFile1">
</div>
<div class="form-group">
<label for="exampleFormControlFile1">Right</label>
<input type="file" name="vehi_right" class="form-control-file" id="exampleFormControlFile1">
</div>
<div class="form-group">
<label for="exampleFormControlFile1">Rear</label>
<input type="file" name="vehi_back" class="form-control-file" id="exampleFormControlFile1">
</div>
<textarea placeholder="Other" name="other" type="text" class="txt_3"></textarea>
<input type="submit" value="submit" name="submit" class="txt2">
</form>
</div>
</div>
</div>
</div>
</div>
This is the insert query code.
<?php
include("../inc/conn.php");
$brand=$_POST['brand'];
$model=$_POST['model'];
$vehi_front=$_POST['vehi_front'];
$vehi_left=$_POST['vehi_left'];
$vehi_right=$_POST['vehi_right'];
$vehi_back=$_POST['vehi_back'];
$other=$_POST['other'];
{
$sql = "INSERT INTO vehicle(brand,model,vehi_front,vehi_left,vehi_right,vehi_back,other) VALUES ('{$brand}','{$model}','{$vehi_front}','{$vehi_left}','{$vehi_right}','{$vehi_back}','{$other}')";
if(mysqli_query($con,$sql))
{
header("location:add_vehicle.php?msg=Successfully Saved !");
}
}
?>
you must create image uploader function
in php $_POST['image_input_name'] return you null
you must use $_FILE
function uploadPic($file_input_name, $path)
{
if (isset($_FILES[$file_input_name])) {
$file = $_FILES[$file_input_name];
// for bin2hex and random_bytes you must use php > 7
$new_name = (string)bin2hex(random_bytes(32));
$extension = ".jpg";
$final_name = $new_name . $extension;
move_uploaded_file($file['tmp_name'], $path . $final_name);
return $path . $final_name;
}
}
first line check for image
2 get the file and put in into $file
3 change the name for security
4 change the extension for more security
// user upload a shel.php. in function we change the name and extension
// for exp shel.php converted to hs7f4w8r5c1f4s5d9t6g3s149748654asdasd.jpg
5 add name and extension in var
6 we move uploaded pic to path
7 we return the address and name of pic
and in your new code here
<?php
include("../inc/conn.php");
$brand = $_POST['brand'];
$model = $_POST['model'];
// in if we check for image exist
if ($_FILES['vehi_front']['tmp_name'] != "") {
$vehi_front = $this->uploadPic("vehi_front", "/path/to/save/image");
}
if ($_FILES['vehi_left']['tmp_name'] != "") {
$vehi_left = $this->uploadPic("vehi_left", "/path/to/save/image");
}
if ($_FILES['vehi_right']['tmp_name'] != "") {
$vehi_right = $this->uploadPic("vehi_right", "/path/to/save/image");
}
if ($_FILES['vehi_back']['tmp_name'] != "") {
$vehi_right = $this->uploadPic("vehi_back", "/path/to/save/image");
}
$other = $_POST['other'];
{
$sql = "INSERT INTO vehicle(brand,model,vehi_front,vehi_left,vehi_right,vehi_back,other) VALUES ('{$brand}','{$model}','{$vehi_front}','{$vehi_left}','{$vehi_right}','{$vehi_back}','{$other}')";
if (mysqli_query($con, $sql)) {
header("location:add_vehicle.php?msg=Successfully Saved !");
}
}
?>
You can do this using $_FILES variable
see reference here: https://www.php.net/manual/en/reserved.variables.files.php

Data not appending to file in php

I am trying to appending emails that have signup'd to a csv file, but it shows success, whereas there is nothing in the file, nothing is appending and when i print_r the fwrite it says 15
This is my code
<form action="send.php" method="post" name="newsletter" class="">
<label class="sr-only">Email:</label>
<div class="input-group mb-2">
<input type="email" name="email" class="form-control rounded-right bg-transparent" placeholder="johndoe#example.com" aria-label="Username" aria-describedby="basic-addon1" style="border: 1px solid #bdbdbd;">
<button type="submit" class="home-signup-email-btn btn btn-blue btn-lg ml-3 rounded py-0">Sign Up</button>
</div>
</form>
$email = $_POST['email'];
//$filename = 'suscribers.txt';
//$somecontent = "$email\n";
// Let's make sure the file exists and is writable first.
$txt = '/n'.$_POST['email'].'/n';
$file = fopen('mailing_list.csv','a');
if (fwrite($file,$txt)){
// fwrite($file,$txt);
$message= "Success!. You have been added to our email list.";
$status = "success";
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);}
else
echo "fail";
Try using:
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
Use a+ mode:
Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist
<form action="send.php" method="post" name="newsletter" class="">
<label class="sr-only">Email:</label>
<div class="input-group mb-2">
<input type="email" name="email" class="form-control rounded-right bg-transparent" placeholder="johndoe#example.com" aria-label="Username" aria-describedby="basic-addon1" style="border: 1px solid #bdbdbd;">
<button type="submit" class="home-signup-email-btn btn btn-blue btn-lg ml-3 rounded py-0">Sign Up</button>
</div>
</form>
$email = $_POST['email'];
// Let's make sure the file exists and is writable first.
$txt = '/n'.$_POST['email'].'/n';
$file = fopen('mailing_list.txt','a+');
if (fwrite($file,$txt)){
$message= "Success!. You have been added to our email list.";
$status = "success";
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
fclose($file);
chmod($file, 0777);
}else {
echo "fail";
}
I found a solution it wasn't writing to the file because i didn't add an fclose to close the fopen

PHP text input to .txt file

I tried to make a simple PHP program that writes text from an input field and puts it in a .txt file. What is wrong with my code? It doesn't leave spaces between items and copies the previous item and doubles it. The file is called email.txt . Here is the code:
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$file = fopen("email.txt", "r+") or die("<h1>Eroarea 1</h1>"); //In caz ca fisierul nu este gasit
$s = fread($file, filesize("email.txt"));
$s = $name . "\n";
fputs($file, $s) or die("<h1>Eroarea 2</h1>"); //In caz ca server-ul nu poate fi contactat
fclose($file);
echo "<h1></h1>";
} ?>
<section id="five" class="wrapper style2 special fade">
<div class="container">
<header>
<h2>Writer</h2>
<p>Put text here</p>
</header>
<form method="post" action="#" class="container 50%" onSubmit="post">
<div class="row uniform 50%">
<div class="8u 12u$(xsmall)"><input type="text" name="name" placeholder="Email" /></div>
<div class="4u$ 12u$(xsmall)"><input type="submit" name="submit" value="Send" class="fit special" /></div>
</div>
</form>
</div>
</section>
A much easier way to append content to a file would be to use file_put_contents():
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
file_put_contents('email.txt', $name . PHP_EOL, FILE_APPEND);
}
?>
That will create the file if it doesn't exist and append to it if it does.

PHP auto commented out/redirecting to php script page in webserver

Currently I'm working with forms, trying to send a form submission to a text file. However, when I set the form action to my PHP script: action="saveScript.php, it redirects me to the PHP script's page in html.
HTML
<!DOCTYPE html>
<head>
<meta charset="UTF-8" lang="en">
<link rel="stylesheet" type="text/css" href="style/form.css">
</head>
<body>
<form method="POST" action="saveScript.php" id="twitterCardTest">
<ul>
<label for="fName">First Name: </label>
<li><input type="text" id="fName" name="fName" size="5" maxlength="15"></li>
<label for="lName">Last Name: </label>
<li><input type="text" id="lName" name="lName" size="5" maxlength="15"></li>
<label for="message">Message: </label>
<li><input type="text" class="message" id="message" name="message" size="5" maxlength="140"></li>
</ul>
<input type="submit" name="submit" value="Submit Info" />
</form>
</body>
</html>
PHP
<?php
$file= fopen('test.txt', "a");
//retrieve existing file
$retrieve = file_get_contents($file);
$current = $_POST['fName'] . ' ' . $_POST['lName'] . "\n" . $_POST['message'] . "\n";
//record information inputted by user
$write = fwrite($file, $current);
$fileSize = filesize('test.txt');
$saveFile = file_put_contents( '/htdocs/', $current, FILE_APPEND | LOCK_EX);
if($file === FALSE) {
die('Error writing file');
}
else if ($file != FALSE) {
echo "Information written to file";
}
else {
die('no post data to process');
}
fclose($file);
?>
Alternatively, I tried placing the PHP code into the html file after the body end tag. This resulted in the browser auto commenting the whole script out. I recently updated php using brew and I've configured my local web server to accommodate PHP. My question is how would I go about fixing this issue so my script is being read as php? In addition, why does this issue occur?

Categories