Data not appending to file in php - 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

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 could I save on a file .txt with php?

<?php
$fp = fopen("users.txt", "w");
if(!$fp) die ("Errore nella creazione dell'utente");
$fp=fwrite($email $password);
fclose($fp);
$name="";
$surname="";
$email="";
$password="";
$nazionalita="";
$telefono="";
$errors= array();
if($_SERVER["REQUEST_METHOD"]=="POST"){
$name = htmlspecialchars($_POST["name"]);
$surname = htmlspecialchars($_POST["surname"]);
$email = htmlspecialchars($_POST["email"]);
$password = htmlspecialchars($_POST["password"]);
$nazionalita = htmlspecialchars($_POST["nazionalita"]);
$telefono = = htmlspecialchars($_POST["nazionalita"]);
}
if(empty($name)) {
$errors[] = "Name is required!";
}
if(empty($surname)) {
$errors[] = "Surname is required!";
}
if(empty($email)) {
$errors[] = "Email is required!";
}
if(empty($password)) {
$errors[] = "Password is required!";
}
header("location: index.php");
?>
But of course, this doesn't work.
How can I save to a specific location with PHP?
Then I'll have to do an explode which will only get my email and password. on the login.php page.
Thank you.
I'm not going to fix your code for you, but give you three tips:
Think like a computer. The computer is going to run your program one statement at a time, in the order you've written them; so if you have a line that writes a variable to a file, it needs to come after the line where you've put a value into that variable. It is also going to do exactly what you ask it, not guess what you meant, and not let you get away with typos; read your code back carefully.
Make use of the PHP manual. If you type in https://php.net/ followed by the name of a built-in function, like https://php.net/fwrite, you will get a page that explains what the input and output of that function is. Often, there are examples which show various ways of using the function, which you can use as inspiration for how to write your own code.
Turn on the display_errors setting, or learn where your log file is. Most of the mistakes in the code you show will result in errors or warnings, telling you exactly which line you need to look at. Read the messages carefully, and they'll often point out exactly what you've done wrong.
If you want to write to the file you could do $fpw = fwrite($fp,$email.' : '.$password);
you should pass the $fp to fwrite() method as follow
$fp = fopen('user.txt', 'w+') or die('Unable to open file!');
$fp=fwrite($fp, $email.'~'.$password.'\n'); // make sure to choose whatever seperator suits your need and be careful when choosing it
fclose($fp);
Thanks everyone, I fixed my code!!!
Following the correct code!
<?php
$name="";
$surname="";
$email="";
$password="";
$nazionalita="";
$telefono="";
$errors= array();
//$fp = fopen("users.txt", "w");
//$fpw = fwrite($fp,$dati $email.' : '.$password);
//fclose($fp);
if(isset($_POST["submitPut"])){
$name = htmlspecialchars($_POST["name"]);
$surname = htmlspecialchars($_POST["surname"]);
$email = htmlspecialchars($_POST["email"]);
$password = htmlspecialchars($_POST["password"]);
$nazionalita = htmlspecialchars($_POST["nazionalita"]);
$telefono = htmlspecialchars($_POST["telefono"]);
$dati= "\n". $name . ",". $surname .",".$email.",". $password . ",". $nazionalita. ",". $telefono;
$file= fopen("users.txt", "a+");
$credenziali=fwrite($file, $dati);
fclose($file);
if(empty($name)) {
$errors[] = "Name is required!";
}
if(empty($surname)) {
$errors[] = "Surname is required!";
}
if(empty($email)) {
$errors[] = "Email is required!";
}
if(empty($password)) {
$errors[] = "Password is required!";
}
}
//header("location: index.php");
?>
<!DOCTYPE html>
<html lang="en">
<?php include_once "views/head.php" ?>
<body>
<?php include_once "views/navbar.php" ?>
<main>
<div class="container my-5">
<h2>Registration user</h2>
<form action="registration.php" method="post">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name" >
</div>
<div class="form-group">
<label for="surname">surname:</label>
<input type="text" class="form-control" id="surname" name="surname" placeholder="Enter surname" >
</div>
<div class="form-group">
<label for="email">email:</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email" >
</div>
<div class="form-group">
<label for="password">password:</label>
<input type="text" class="form-control" id="password" name="password" placeholder="Enter password">
</div>
<div class="form-group">
<label for="nazionalita">nazionalita:</label>
<input type="text" class="form-control" id="nazionalita" name="nazionalita" placeholder="Enter nazionality" >
</div>
<div class="form-group">
<label for="telefono">telefono:</label>
<input type="text" class="form-control" id="telefono" name="telefono" placeholder="Enter phone" >
</div>
<button type="submit"name="submitPut" class="btn btn-primary">Submit</button>
</form>
</div>
</main>
<?php include_once "views/footer.php" ?>
<?php include_once "views/scripts.php" ?>
</body>
</html>

Set column as empty if no file is selected when submit

I am very new to PHP and was trying to do the file uploading. When I try to submit a form without having any files selected, the database will still insert a value to the attachments column.
My table picture:
Is there any way that I can set the attachments column as empty if there is not file selected for submission. Below is my code:
view_group.php
<form class="forms-sample" enctype='multipart/form-data' method="post">
<div class="modal-body">
<div class="form-group">
<textarea id="status_content" name="status_content" rows="30"></textarea>
</div>
<div class="form-group">
<label for="section_label">Add Attachments</label><br>
<input type="text" class="form-control" id="file" disabled placeholder="Select a file"><br>
<button type="button" class="file-upload-browse btn btn-primary" name="button" onclick="document.getElementById('fileName').click()">Select a file</button>
<input type="file" name="attachmentfile" id="fileName" style="display:none">
</div>
</div>
<div class="modal-footer">
<button class="btn btn-outline-secondary btn-fw">Cancel</button>
<input type="submit" class="btn btn-primary" name="postStatus" value="Post" />
</div>
</form>
GroupsController.php
function postStatus($std_id, $group_id){
$status = new ManageGroupsModel();
$status->std_id = $std_id;
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
$status->attachments = time() . $_FILES['attachmentfile']['name'];
$status->target_dir = "../../attachments/groupfiles/";
//target file to save in directory
$status->target_file = $status->target_dir . basename($_FILES["attachmentfile"]["name"]);
// select file type
$status->imageFileType = strtolower(pathinfo($status->target_file,PATHINFO_EXTENSION));
// valid file extensions
$status->extensions_arr = array("jpg","jpeg","png","gif","pdf", "doc", "pdf");
if($status->postStatus() > 0) {
$message = "Status posted!";
echo "<script type='text/javascript'>alert('$message');
window.location = '../ManageGroupsView/view_group.php?group_id=".$group_id."'</script>";
}
}
GroupsModel.php
function postStatus() {
$sql = "insert into status(std_id, group_id, status_content, attachments) values(:std_id, :group_id, :status_content, :attachments)";
$args = [':std_id'=> $this->std_id, ':group_id'=> $this->group_id, ':status_content'=> $this->status_content, 'attachments'=> $this->attachments];
move_uploaded_file($_FILES['attachmentfile']['tmp_name'],$this->target_dir.$this->attachments); $stmt = DB::run($sql, $args);
$count = $stmt->rowCount(); return $count; }
I'm sorry if the question sounded dumb. It would be really great if someone can help. Thank you!
UPDATE!
Thanks to the people in my comment section, I finally get to do it. Here are the code needed to add :
function postStatus($std_id, $group_id){
$status = new ManageGroupsModel();
$status->std_id = $std_id;
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($_FILES['attachmentfile']['name']) {
$status->attachments = time() . $_FILES['attachmentfile']['name'];
$status->target_dir = "../../attachments/groupfiles/";
//target file to save in directory
$status->target_file = $status->target_dir . basename($_FILES["attachmentfile"]["name"]);
// select file type
$status->imageFileType = strtolower(pathinfo($status->target_file,PATHINFO_EXTENSION));
// valid file extensions
$status->extensions_arr = array("jpg","jpeg","png","gif","pdf", "doc", "pdf");
} else {
$status->attachments = '';
}
if($status->postStatus() > 0) {
$message = "Status posted!";
echo "<script type='text/javascript'>alert('$message');
window.location = '../ManageGroupsView/view_group.php?group_id=".$group_id."'</script>";
}
}

How can I save my form data to a local text file using php? [duplicate]

This question already has answers here:
Syntax error - unexpected ":" [closed]
(4 answers)
Closed 4 years ago.
I have a form in which I want to capture the name and email of a user and store it in a text file. I'm not sure if it's my code or if I have to save my script in a specific place. When the submit button is clicked I get an error that says "404 file or directory not found". My client is uploading them through ftp so I have no way to check if it works locally. The PHP script(process-form-data.php) and text file (formdata.txt) are saved within the public HTML folder. I'm very new to PHP so sorry if this is a dumb question. Any help on what I'm doing wrong and the process of uploading the files would be greatly appreciated, thanks!
<form name=”web_form” id=”web_form” method=”post” action=”process-
form-data.php”>
<label for="exampleInputEmail1"><h3 style="color: #eee; margin: 0;
font-weight: 400;">Request Information</h3></label>
<input type="text" name=”name” class="form-control" id="name"
placeholder="Your Name">
<input type="text" class="form-control" name=”email” id=”email”
placeholder="youremail#domain.com">
<button type="submit" name=”s1″ id=”s1″ value="submit" class="btn
btn-primary btn2">Submit</button>
</form>
<?php
$name = $_POST[‘name’];
$email = $_POST[’email’];
$fp = fopen(”formdata.txt”, “a”);
$savestring = $name . “,” . $email . “n”;
fwrite($fp, $savestring);
fclose($fp);
echo “<h1>You data has been saved in a text file!</h1>”;
?>
You should mind about your double quotes ("") written in your html code
<form name='web_form' id='web_form' method='post' action=''>
<label for="exampleInputEmail1"><h3 style="color: #eee; margin: 0;
font-weight: 400;">Request Information</h3></label>
<input type='text' name='name' class="form-control" id="name"
placeholder="Your Name">
<input type="text" class="form-control" name='email' id='email'
placeholder="youremail#domain.com">
<button type="submit" name='s1' id='s1' value="submit" class="btn btn-
primary btn2">Submit</button>
</form>
this code writes email and name in a text file
<?php
if (isset($_POST['s1'])) {
echo $_POST['name'];
echo $_POST['email'];
$myfile = fopen("data.txt", "w") or die("Unable to open file");
$name = $_POST['name']."\n";
fwrite($myfile, $name);
$email = $_POST['email']."\n";
fwrite($myfile, $email);
fclose($myfile);
}
?>

Error when submitting input to a txt file in 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);
}
?>

Categories