Can I make my post.php save the data permanantly? - php

For my website you can visit here at http://desire.site88.net at the very bottom you will see my form. When you finish with the form and press submit the form submits the data to desire.site88.net/post.php . What I'm curious is how do I make it permanent? When the user submits data to post.php I want it to stay there. Not looking for anything secure or unhackable, just something I can use to recruit members. Here is my code
<?php
$username = $_POST['username'];
$email = $_POST['email'];
$message = $_POST['message'];
// what it will say down below
echo $username. ' has an email of </br>';
echo $email. ' and wants to join because </br>';
echo $message. '</br></br>';
<form method="post" action="test.php">
<div class="row 50%">
<div class="6u 12u(mobile)"><input type="text" name="username" placeholder="Username" /></div>
<div class="6u 12u(mobile)"><input type="email" name="email" placeholder="Email" /></div>
</div>
<div class="row 50%">
<div class="12u"><textarea name="message" placeholder="Application" rows="6"></textarea></div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li><input type="submit" value="submit" /></li>
</ul>
</div>
</div>
</form>

So reading your previous comment about looking for a simple way to collect data without the need for security, I recommend saving it in a text file for now, and maybe later using XML, which you can investigate into later.
code to save into a text file:
$filePath = $username."-".time().".txt";
$myFile = fopen($filePath, "w");
fwrite($myFile, ("username: ".$username."\n"));
fwrite($myFile, ("email: ".$email."\n"));
fwrite($myFile, ("message: ".$message."\n"));
fclose($myFile);
that code will save a file with a unique name each time it is saved, and it would be located in the same directory as your php page.
let me know if that worked for you or if you have any doubts :)
Edited:
Explaining first how the function fopen() works. Placing "w" in the second parameter means the function will create a new file with the information you give it, and if the file already existed, it will re-write it, meaning any previous information that existed in the file will be gone. For this reason, I made the $filePath unique, so that no overwriting happens. I will now go a bit further and include the logs in a new separate file that is outside the root folder for added security:
//++++ path obtained to your root folder
$root_directory_path = $_SERVER['DOCUMENT_ROOT'];
//++++ creating the path for the logs in a new folder outside
//++++ the root director
$filePath = $root_directory."/../my_logs/".$username."-".time().".txt";
//++++ starting the creation of the file
$myFile = fopen($filePath, "w");
//++++ inputing information into the file
$inputString = "username: ".$username."\n";
fwrite($myFile, $inputString);
$inputString = "email: ".$email."\n";
fwrite($myFile, $inputString);
$inputString = "message: ".$message."\n";
fwrite($myFile, $inputString);
//++++ closing the file / finalizing the creation of the file
fclose($myFile);
I visited your site and it seems you are having issues with the permissions that the site gives you. If you still wish to user text files inside the root directory, you can follow the code below, however be informed that anyone can view the users that are registered since the information is being saved in a subfolder of the rood directory, so I do recommend transitioning to a database that is secure:
$filePath = "/myLogs/".$username."-".time().".txt";
$myFile = fopen($filePath, "w");
fwrite($myFile, ("username: ".$username."\n"));
fwrite($myFile, ("email: ".$email."\n"));
fwrite($myFile, ("message: ".$message."\n"));
fclose($myFile);

Related

Empty POST method

I am totally new in PHP and i have problem with posting data. I try to post data and write it in txt file. I already increase my post max size in php.ini. I use XAMPP
<form action="forms/save_news.php" method="post" role="form">
<div class="form-group">
<input type="text" name="date" class="form-control" id="date" placeholder="Дата" data-rule="minlen:10" data-msg="Моля въведете дата" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="title" id="title" placeholder="Заглавние"/>
<div class="validate"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="data" rows="5" data-rule="required" data-msg="Моля въведете съдържание" placeholder="Новина"></textarea>
<div class="validate"></div>
</div>
<div class="text-center"><button type="submit">Запиши</button></div>
</form>
And my PHP code is:
<?php
if(isset($_POST['date'])) {
$date = $_POST['date'];
$fp = fopen('data.txt', 'a');
fwrite($fp, $date);
fclose($fp);
}
?>
My first guess would be a permission issue. What I would do to troubleshoot this is to turn on error reporting in your PHP script. Try the following code:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if (isset($_POST('date')) {
$date = filter_var($$_POST['date'], FILTER_SANITIZE_STRING);
$fp = fopen('data.txt', 'a');
fwrite($fp, $date);
fclose($fp);
}
?>
Post another request from your form and see what appears in the browser. The errors that are reported should tell you where the problem is, but if you aren't positive how to fix the errors.
Now, all that said, be sure to never trust data sent from a web form. For simply testing purposes, you can do what you are doing, but I would not recommend getting into the habit since it can breed complacency. Note the change I made to the line that assigns the value of the form field to the $date variable. It uses a filter_var function to sanitize the string. There are plenty of combinations, and it is best to understand exactly how you are going to use the data, eventually to choose the correct filter(s).
You may consider an extra check. For example, if $_POST['date'] contained an empty string, it would pass isset() and would still append this to the Text file.
PHP Version is also a consideration here.
Try:
<?php
if(isset($_POST['date']) && !empty($_POST['date'])) {
$date = $_POST['date'];
if (is_writable('date.txt'){
$fp = fopen('date.txt', 'a');
if(fwrite($fp, $date) === FALSE){
echo "Cannot write to file";
exit;
}
fclose($fp);
} else {
echo "The file is not writable.";
}
}
?>
Also, this script assumes that date.txt and save_news.php reside in the same folder path. Is date.txt in forms folder? If it is not you will want to ensure that the script can reach the file and there are proper permissions for XAMPP and PHP to Read, Write to this file.
If date.txt is elsewhere, maybe in the parent, use:
$fp = fopen('../date.txt', 'a');
If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled open_basedir further restrictions may apply.
https://www.php.net/manual/en/function.fopen.php

PHP: Editing a file using a dynamic filename

I have a PHP script that I am trying to edit some text files that have a dynamic file name. I think I am about 90% there, but am having an issue where the resulting output filename is incorrect.
The files in question I am trying to edit are for VoIP phones nad have a ormat of MAC.cfg, where MAC is the MAC address of the phone in question.
I have an HTML page that is just a very simple form where the MAC address is entered, and the form calls a PHP script that using that MAC address and brings up the contents of the appropriate MAC.cfg file. When I edit what I want to edit, however, the resulting filename becomes MAC.cfg.cfg (i.e., it adds an extra ".cfg" to it), and I do not know why.
The code for the page where the MAC address of the phone gets entered is:
<form method="post" action="edit-imaccfg.php">
<input type="text" name="macaddress" value="">
<input type="submit">
</form>
and the contents of 'edit-imaccfg.php' is this:
<?php
// set file to read
$filename = $_POST['macaddress'].=".cfg";
$newdata = $_POST['newd'];
if ($newdata != '') {
// open file
$fw = fopen($filename, 'w') or die('Could not open file!');
// write to file
// added stripslashes to $newdata
$fb = fwrite($fw,stripslashes($newdata)) or die('Could not write to file');
// close file
fclose($fw);
}
// open file
$fh = fopen($filename, "r") or die("Could not open file!");
// read file contents
$data = fread($fh, filesize($filename)) or die("Could not read file!");
// close file
fclose($fh);
// print file contents
?>
<html>
<body>
<form action="<?= $_SERVER[php_self] ?>" method="POST" >
<textarea name="newd" cols="100%" rows="100"> <?= $data ?> </textarea>
<input type="hidden" name="macaddress" value="<?= $_POST['macaddress'] ?>" />
<input type="submit" value="Change">
</form>
</body>
</html>
I don't know what, in the above code, is adding the extra '.cfg' to the outputted filename, rather than overwriting the intended MAC.CFG file.
Your insight is greatly appreciated Thanks! :-)

Converting text to file and save it to in a folder

I have been trying to save input contact as a file in a folder but i don't know how to go about this using php.
<php
if(isset($_POST['s'])){
$neexe = $_POST['nameextention'];
$filecont = $_POST['fileBody'];
$folderpath = 'Files';
// I wan to save this as page.php with the body content inside so users can download it
}
?>
<form method="post">
<input type="text" name="nameextention" value="page.php"/>
<textarea name="fileBody"><?php if(isset($_HELP['please'])){echo 'i really need to get this done!!';}?></textarea>
<input type="submit" name="s" value="Save">
</form>
Easy. use fopen built-in function as below:
$myfile = fopen($neexe, "w") or die("Failed to open file!");
fwrite($myfile, $filecont);
fclose($myfile);

HTML forms, fwrite and PHP

I want to use fwrite to save data into a .txt file. The action method seems to be working, as it can show HTML tags when being transfered when pressing submit, but i wont run the PHP.
<HTML lang="da">
<style>
</style>
<header>
<title>Tilføj</title>
<meta charset="ISO-8859-1">
</header>
<body>
<form method="post" action="eksamen_save_data.php" enctype='multipart/form-data'>
<fieldset>
<legend>Filmoplysninger</legend>
<div><label>Titel: <input type="text" name="titel" id="titel" required="required" size="60" maxlength="100"></label></div>
<div><label>Hovedskuespiller: <input type="text" name="hovedskuespiller" id="hovedskuespiller" required="required" size="30" maxlength="100"></label></div>
<div><label>Genre: <input type="text" name="genre" id="genre" required="required" size="60" maxlength="100"></label></div>
<div><label>Format: <input type="text" name="format" id="format" required="required" size="60" maxlength="100"></label></div>
<div><label>Billede: <input type="file" name="billede" id="billede" required="required"></label></div>
</fieldset>
<div><input type="submit" id="ok" value="OK"></div>
</form>
</body>
This sends it to the "eksamen_save_data.php" that looks like this:
<?php
$Titel = $_POST["titel"];
$Hovedskuespiller = $_POST["hovedskuespiller"];
$Genre = $_POST["genre"];
$Format = $_POST["format"];
//$Billede = $_FILES["billede"]["navn"];
//if($_FILES){
// move_uploaded_file($_FILES["billed"]["navn"], $_FILES["billed"]["navn"]);
//}
$user_data = "$Titel, $Hovedskuespiller, $Genre, $Format, $Billede \r\n";
$fh = fopen("data.txt", "a") or die("Fejl i åbning af fil!");
fwrite($fh, $user_data) or die ("Fejl i skrivning til fil!");
fclose($fh);
?>
If i write some HTML in the "eksamen_save_data.php" i can show this, but it wont run the PHP. I'm using XAMPP.
The problem is that it wont save to the "data.txt" file as i tell the PHP to do.
Another question; is there also a way, I can make the PHP run in the same file as where I have my fieldset?
LAST EDIT:
Most of the time it's the little mistakes that proves to be the biggest problem. For me i personally forgot to use: localhost/eksamen_tilføj.php in the browser.
So it was me making a mistake in XAMPP.
Use file_put_contents
file_put_contents("data.txt", $user_data, FILE_APPEND);
It does all the jobs like file open, write and close. Advantage is if the file does not exist then it will create.
Find full working code
<?php
$Titel = $_POST["titel"];
$Hovedskuespiller = $_POST["hovedskuespiller"];
$Genre = $_POST["genre"];
$Format = $_POST["format"];
$Billede = $_FILES["billede"]["name"];
// Example of accessing data for a newly uploaded file
$fileName = $_FILES["billede"]["name"];
$fileTmpLoc = $_FILES["billede"]["tmp_name"];
// Path and file name
$pathAndName = "upload/".$fileName;
// Run the move_uploaded_file() function here
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
// Evaluate the value returned from the function if needed
if ($moveResult == true) {
echo "File has been moved from " . $fileTmpLoc . " to" . $pathAndName;
} else {
echo "ERROR: File not moved correctly";
}
$user_data = "$Titel, $Hovedskuespiller, $Genre, $Format, $Billede \r\n";
file_put_contents("data.txt", $user_data, FILE_APPEND);
?>
you'll have to remove the third parameter $test (because it specifies the length of the content to be written). But $test is not defined in your PHP file, so it won't write anything..
So change this
fwrite($fh, $user_data, $test) or die ("Fejl i skrivning til fil!");
into this
fwrite($fh, $user_data) or die ("Fejl i skrivning til fil!");
and have a look at this :)
As for your second question: sure you can merge your form and submit scripts:
<?php
if(count($_POST) > 0) { //
/** Form submit function, file write **/
} else {
?>
<html>
<form action="#" method="POST">
<!-- Enter HTMLform here -->
</form>
</html>
<?php } ?>
This pseudocode is not pretty, but will do in terms of explaining stuff. The # in the form action means that the same script is to be called upon submission. The if(count($_POST) > 0) checks whether data has been submitted. If so, the file will be written. Otherwise, the form will be displayed.
Good luck.

PHP not writing to file even though there are no errors

I have the following script that is supposed to take the input from two forms and then rewrite two different files with the input from the forms. When I put in text into the forms and run it I get no errors but neither of the files were changed at all. I have all the proper permissions set and correct file paths. I changed the paths in the code below so as not to show sensitive information to my server. I'm really scratching my head at this one since php is a fairly new language to me so any help is greatly appreciated.
HTML Code
<form name="editfront" action="save.php" method="post">
<div class="editareasmall">
<textarea rows="1" cols="150" id="title" name="title"></textarea>
<script>$('#title').load('../content/front/Title');</script>
</div>
<div class="contentheader">Content</div>
<div class="editareabig">
<textarea rows="30" cols="150" id="content" name="content"></textarea>
<script>$('#content').load('../content/front/Content');</script>
</div>
<input type="submit" value=" Save " class="save">
</form>
PHP Code
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
$title = $_POST['title'];
$content = $_POST['content'];
$filenametitle = "../content/front/Title";
$filenamecontent = "../content/front/Content";
echo 'Form data has been saved';
$filetitle = fopen($filenametitle, "w") or die("can't open file");
$filecontent = fopen($filenamecontent, "w") or die("can't open file");
fwrite($filetitle,$title);
fwrite($filecontent,$content);
fclose($filetitle);
fclose($filecontent);
?>
When you submit the form, do you get your output message?
"Form data has been saved"
Are you sure that in php multi file opening is available?
Change your error reporting to -1. You will be informed about notice error.

Categories