Is it possible to save input data in php file without using any database?
Something like:
echo " inputted text.. ";
or
$text = "Text..";
Use fwrite, very easy :
<?php
$fp = fopen('myfile.txt', 'w');
fwrite($fp, 'this is my database without database :p ');
fclose($fp);
?>
If you want to work with a form, and extract some variables into a file you can use:
Your Form in form.html
<form action="recipient.php" method="POST">
INPUT1: <input type="text" name="text1" id="input1"><br/>
INPUT2: <input type="text" name="text2" id="input2"><br/>
FILENAME: <input type="text" name="filename" id="filename">
<button type="submit">Send now</button>
</form>
Your PHP recipient.php - without any validation checks:
<?php
$varA = "\$varA = ".$_POST['input1'].";"; // put your string into varible $varA
$varB = "\$varB = ".$_POST['input1'].";"; // put your string into varible $varA
$fileName = $_POST['filename']; // set a filename from form field
$text = $varA ." ". $varB; // add all together
$filepath = fopen('/var/www/html/'.$fileName.'.php', 'w+'); // set filepath and fopen to new PHP-file
fwrite($filepath, '<?php '. $text); // write text as PHP-file
fclose($filepath); // close file
?>
If you haven't read about them yet check HTML-Forms.
You might also want to look into arrays and serialisation.
But apart from that I highly recommend to have a look into Databases (PDO) - it safes you time and is much more secure.
Related
I am trying to modify the value of a variable $denumire produs=' '; from a php file _inc.config.php through a script by this code with form from file index.php and i have some errors.
The new value of the variable will become value entered from the keyboard via the form.
Anyone can help me, please?
<?php
if (isset($_POST['modify'])) {
$str_continut_post = $_POST['modify'];
if (strlen($_POST['search']) > 0 || 1==1) {
$fisier = "ask003/inc/_inc.config.php";
$fisier = fopen($fisier,"w") or die("Unable to open file!");
while(! feof($fisier)) {
$contents = file_get_contents($fisier);
$contents = str_replace("$denumire_produs =' ';", "$denumire_produs ='$str_continut_post';", $contents);
file_put_contents($fisier, $contents);
echo $contents;
}
fclose($fisier);
die("tests");
}
}
?>
<form method="POST" action="index.php" >
<label>Modifica denumire baza de date: </label>
<input type="text" name="den">
<button type="submit" name="modify"> <center>Modifica</center></button>
</div></div>
</form>
This is an XY problem (http://xyproblem.info/).
Instead of having some sort of system that starts rewriting its own files, why not have the file with the variable you want to change load a json config file?
{
"name": "Bob",
"job": "Tea Boy"
}
Then in the script:
$json = file_get_contents('/path/to/config.json');
$config = json_decode($json, true);
$name = $config['name'];
Changing the values in the config is as simple as encoding an array and putting the json into the file.
$config['denumireProdu'] = 'something';
$json = json_encode($config);
file_put_contents('/path/to/config.json', $json);
This is far saner than getting PHP to rewrite itself!
Docs for those commands:
http://php.net/manual/en/function.json-decode.php
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.file-get-contents.php
http://php.net/manual/en/function.file-put-contents.php
I am fairly new to PHP and am having trouble with an assignment. The assignment is to create a simple address book in PHP, and i would like my address book to display all addresses that are in it along with a submission box at the bottom to add more addresses. Currently, I can get the addresses to display, but the submission box gives me an error ") Notice: Undefined variable: addres_add in C:\wamp64\www\address_tmp\address.php on line 18"
This is my code thus far, I snagged the submission box code from another answer here on StackOverflow, but I don't know how to modify it to fit my needs.
<?php
//Open address book file and print to user
$fh = fopen("address_book.txt", "r+");
echo file_get_contents("address_book.txt");
//Perfom submit function
if(isset($_POST['Submit']))
fseek($fh, 0, SEEK_END);
fwrite($fh, "$addres_add") or die("Could not write to file");
fclose($fh);
print("Address added successfully. Updated book:<br /><br />");
echo file_get_contents("address_book.txt");
{
$var = $_POST['any_name'];
}
?>
<?php
//HTML for submission box?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="any_name">
<input type="submit" name="submit">
</form>
<p>
You never assigned the variable from the form input. You need:
$addres_add = $_POST['any_name'];
fwrite($fh, "$addres_add") or die("Could not write to file");
Also, if you're just adding to the file, you should open it in "a" mode, not "r+". Then you don't need to seek to the end, that happens automatically.
You probably should put a newline between each record of the file, so it should be:
fwrite($fh, "$addres_add\n") or die("Could not write to file");
Otherwise, all the addresses will be on the same line.
Here is a simpler version of your program.
<?php
$file_path ="address_book.txt";
// Extract the file contents as a string
$file_contents = file_get_contents($file_path);
if ($file_contents) // Check if the file opened correctly
echo($file_contents . " \n"); // Echo contents (added newline for readability)
else
echo("Error opening file. \n");
// Make sure both form fields are set
if(isset($_POST['submit']) && isset($_POST['any_name']))
{
// Append the new name (used the newline character to make it more readable)
$file_contents .= $_POST["any_name"] ."\n";
// Write the new content string to the file
file_put_contents($file_path, $file_contents);
print("Address added successfully. Updated book:<br /><br />");
echo($file_contents);
}
else
{
echo("Both form elements must be set. \n");
}
?>
//HTML for submission box?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="any_name">
<input type="submit" name="submit">
</form>
Even with no comments it should be self explanatory. I leave the proper error dealing to you.
To answer your question, the error was being caused because the $address_add variable wasn't previously declared. You also added quotes to it, making it a string.
How to make a textbox form redeem a promo code form a text file in php i cant seem to figure it out it's for my csgo gambling site i want them redeem to redeem codes that comes from a text file /promo/codes.txt and make it so they can just use any codes from the list in the text file but im to useless :(
It depends totally on the format of the file.
Example:
ZQC01
ZQR92
ZQA84
ZQD73
To check if a promotion code is in this file and remove it afterwards:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$myPromoCode = isset($_POST['promocode']) ? $_POST['promocode'] : false;
$contents = file_get_contents('/path/to/file.txt');
$promoCodes = explode("\n", $contents);
// Check if the promo code is present in the file
if ($myPromoCode && in_array($myPromoCode, $promoCodes)) {
// Find the corresponding key
$key = array_search($myPromoCode, $promoCodes);
// Remove the code
unset($promoCodes[$key]);
// Write coes back to file
$contents = implode("\n", $promoCodes);
file_put_contents('/path/to/file.txt', $contents);
} else {
die("Promotion code doesn't exist");
}
}
?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
<input type="text" name="promocode" />
<button type="submit">Redeem</button>
</form>
I have made a script with a form which is supposed to submit a persons email to a .txt file, only problem is that nothing happends to the .txt file, it is kept blank when the function is called. Both the html file and the php file is kept in the same folder and the .txt file is named formdata.txt .
Html code:
<form name="newsletter-form" action="process-form-data.php" method="post" id="newsletter-form">
<input type="email" name="newsletter-email" id="newsletter-email" class="form-control" placeholder="Enter Your Email" data-validate="validate(required, email)" />
<input type="submit" id="newsletter-submit" class="btn" value="Notify Me" />
</form>
Php code named process-form-data.php:
<?php
// Receive form Post data and Saving it in variables
$email = $_POST['newsletter-email'];
// Write the name of text file where data will be store
$filename = "formdata.txt";
// Marge all the variables with text in a single variable.
$f_data= '
Email : '.$email.'
=========================
';
echo 'Form data has been saved to '.$filename.' <br>
Click here to read ';
$file = fopen($filename, "a");
fwrite($file,$f_data);
fclose($file);
?>
Your code works for me.
Here's a variation using file_put_contents:
// Receive form Post data and Saving it in variables
$email = $_POST['newsletter-email'];
//$email = 'myhappymail#unhappy.com';
// Write the name of text file where data will be store
$filename = "formdata.txt";
// Marge all the variables with text in a single variable.
$f_data= '
Email2! : '.$email.'
=========================
';
file_put_contents( $filename, $f_data, FILE_APPEND | LOCK_EX );
// $file = fopen($filename, "a");
// fwrite($file,$f_data);
// fclose($file);
echo 'Form data has been saved to '.$filename.' <br>
Click here to read ';
Do a:
var_dump( $_POST );
die;
at the top of your script. I'm thinking you're missing your POST data.
I have this code that displays contents of a particular file. I would like to add a submit button that when clicked saves the changes in to a file. Can anyone help me or give some examples that i can use to create this button. i have tried couple of example that i found on the web but could get it to work. is the solution hidden somewhere with $_POST. her is the code.
<?php
$relPath = 'test_file_1.php';
$fileHandle = fopen($relPath, 'r') or die("Failed to open file $relPath go and make me a sandwich! "); ;
while(!feof($fileHandle)){
$line = fgets($fileHandle);
$lineArr = explode('=', $line);
if (count($lineArr) !=2){
continue;
}
$part1 = trim($lineArr[0]);
$part2 = trim($lineArr[1]);
$simbols = array("$", "[", "]", "'", ";");
//echo "<pre>$part1 $part2</pre>";
echo '<form>
<pre><input type="text" name="content_prt1" size="50" value="' .str_replace($simbols, "",$part1).'"> <input type="text" name="content_prt2" size="50" value="' .str_replace($simbols, "",$part2).'"></pre>
<form />';
}
echo '<input type="submit" value="Submit">';
fclose($fileHandle) or die ("Error closing file!");
?>
EDIT
code for the updatefile.php
<?php
if(isset($_REQUEST['submit1'])){
$handle = fopen("test_file_1.php", "a") or die ("Error opening file!");;
$file_contents = $_REQUEST["content_prt1" . "content_prt1"];
fwrite($handle, $file_contents);
fclose($handle);
}
?>
the code stops at error opening file
If you look at the at purely submitting point of view then put the submit button inside the <form> tags
Also, the closing form tags must be form and not from. The updatefile.php I refer to is the file that you post the input box type text to that will update the file of the database field. Remember to close the file before writing to it again. Hope this helps.
<?php
$relPath = 'test_file_1.php';
$fileHandle = fopen($relPath, 'r') or die("Failed to open file $relPath go and make me a sandwich! ");
echo '<form action="updatefile.php" method="POST">';
while(!feof($fileHandle))
{
$line = fgets($fileHandle);
$lineArr = explode('=', $line);
if (count($lineArr) !=2){
continue;
}
$part1 = trim($lineArr[0]);
$part2 = trim($lineArr[1]);
$vowels = array("$", "[", "]", "'", ";");
echo '<pre><input type="text" name="content_prt1" size="50" value="' .str_replace($vowels, "",$part1).'">
<input type="text" name="content_prt2" size="50" value="' .str_replace($vowels, "",$part2).'">
</pre>';
}
echo '<input type="submit" value="Submit">';
echo '<form>';
fclose($fileHandle) or die ("Error closing file!");
?>
You can't submit more than one form with a single submit button. You'll have to echo the <form> tags outside of the loop so that only one form gets created.
The other problem is you have multiple inputs that are named the same, so $_POST will contain only the value of the last input of each name. You probably mean to append [] to the names of the inputs, e.g. name="content_prt1[]". This way, PHP will create an array of those inputs' values in $_POST['content_prt1'].
Finally, note that what you have so far may pose an HTML injection risk (when displaying the page) unless you're certain that the text coming out of the file doesn't contain characters like < and >. To mitigate this, you can use htmlentities when echoing the text into the inputs.