saving to text file with submit button - php

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.

Related

Save input data in php file (No DB)

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.

PHP: "Submit" box

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.

write checkmarked data to json with PHP

I have a bunch of urls I am echoing from a json file with a foreach loop. I then select some of those with a form checkbox, which I then want to write to another json file. But when I write to the second json file, it just grabs the last checked url, not all the checked ones.
form:
<?php
if(!empty($user_array)){
foreach($user_array as $image){
echo
<input type="checkbox" name="photo_url" value="'. $image['url'] . '">;
}
}
grab_urls.php
$new_json = fopen("new-order.json", "w") or die("Unable to open file!");
$txt[] = array(
'photo_url'=> $_POST['photo_url'],
);
fwrite($new_json, json_encode($txt, JSON_FORCE_OBJECT));
fclose($new_json);
How can I get all the checked URLs?
You need to create multiple checkbox array.something like below:
<?php
if(!empty($user_array)){
foreach($user_array as $image){
echo
<input type="checkbox" name="photo_url[]" value="'. $image['url'] . '">;
}
}
?>

my script is not reading *.txt file

I have a form which takes two values. One takes a .txt file, the file at which some links are hard coded and a text field which takes a url. When I press submit it takes that url and checks on every link that is on *.txt file. Hope you understand what I am saying if not then please comment I will clarify it. Now I have problems. My code does not work until the file at which links are, is not at my server. I don't how to handle this problem. I have done my search, I also try mysql but that is not ok for me. My script is this:
Enter your file :<input type="file" name="ufile" />
Enter your site name :<input type="text" name="utext" />
<input type="submit" value="Check" />
Now, my php script is this:
$needle = $_POST['utext'];
$file = $_FILES['ufile'];
$new = file($file, FILE_IGNORE_EMPTY_LINES | FILE_SKIP_EMPTY_LINES);
$new = array_map('trim', $new);
echo 'Total entries are: '.count($new).'<br />';
$found = array();
$notfound = array();
foreach ($new as $check) {
echo "<table border='1'><tr>";
echo "<td>Processing</td> <td>", $check,"</td></tr>";
$a = file_get_contents($check);
if (strpos($a, $needle)) {
echo "<td><font color='green'>Found:</font></td>";
$found[] = $check;
} else {
echo "<td><font color='red'>Not Found</font></td>";
$notfound[] = $check;
}
echo "</tr></table>";
}
echo "Matches ".count($found)."<br />";
echo "Not Matched ".count($notfound);
Is there any reason you never read the documentation about how PHP handles uploads in first place? That would make clear that $_FILES['ufile'] is array, so your code cannot work. If you really want to continue writing code without understanding it first, then replace:
$file = $_FILES['ufile'];
with
$file = $_FILES['ufile']['tmp_name'];

php string replace without finding a word

I have a form field its give below.
`<form method='post'>
<input type='hidden' name='var'/>
<input type='hidden' name='en_word' value='HOME'/>
<input type='text' name='new_word'/>
<input type='hidden' name='en_word' value='REWARD'/>
<input type='text' name='new_word'/>
<input type='hidden' name='en_word' value='LEADERBOARDS'/>
<input type='text' name='new_word'/>
<input type='submit'>
</form>`
When I entered something and click the submit button it will perform a file write function(fwrite).if i entered the first input field then i click submit button i will get "home" and "whatever i entered". now i want to replace in translation.php for НАЧАЛО with new entered word("Home"=>"НАЧАЛО").I doesn't have НАЧАЛО. Now I want to replace the input word if not exist in translation.php.
$var = $_POST['var'];
$new_words = $_POST['new_words'];
$en_word = $_POST['en_word'];
for($i=0; $i<count($var); $i++)
{
$file = '/www/translation.php';
$handle = fopen($file, "r");
$input = fread($handle, filesize($file));
$stringData = html_entity_decode($new_words[$i], ENT_COMPAT, 'UTF-8');
$first_str = "\"$en_word[$i]\""."=>";
$string="\"$stringData\"".",\n";
fclose($handle);
if(!eregi($first_str,$input) && !eregi($string,$input))
{
$myFile = "/www/translation.php";
//echo $en_word[$i];
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "\"$en_word[$i]\""."=>";
fwrite($fh, $stringData);
$stringData = html_entity_decode($new_words[$i], ENT_COMPAT, 'UTF-8');
fwrite($fh, "\"$stringData\"".",\n");
fclose($fh);
}
elseif (eregi($first_str,$input) && !eregi($string,$input))
{
// here I want to replace the input word if not exist in translation.php.
}`
}
Here is the translation.php
translation.php contain a string.
"HOME" => "НАЧАЛО",
"REWARDS" => "НАГРАДИ",
"LEADERBOARDS" => "КЛАСАЦИИ",
"LOGIN | SIGN UP" => "ВХОД / РЕГИСТРАЦИЯ",
"STORE" => "МАГАЗИН",
"LOGOUT" => "ИЗХОД",
"SET" => "ПОТВЪРДИ",
Now I want to replace the input word if not exist in translation.php. how do I do this?
Is It possible to do? please help me.
Sorry! if question is not understandable please tell me I will explain clearly.
Please change your html to this:
`<form method='post'>
<input type='hidden' name='var'/>
<input type='hidden' name='en_word[]' value='HOME'/>
<input type='text' name='new_word'/>
<input type='hidden' name='en_word[]' value='REWARD'/>
<input type='text' name='new_word'/>
<input type='hidden' name='en_word[]' value='LEADERBOARDS'/>
<input type='text' name='new_word'/>
<input type='submit'>
`
If not, the post will only havethe last en_word value. Please check if it works now and comeback.
Thanks
So you have a php-file that includes translations for certain keywords like "HOME" and "REWARDS". you then have a form to change the translation for those keywords. on submit you want to replace the old translations with new ones.
Maybe this code can help you solve your problem. i first load the whole translation.php into $contents, then perform a preg_replace search&replace on it.
<?php
// prepare $find and $replace for preg_replace.
$find = array("HOME", "REWARD");
$replace = array("whatever", "foobar");
// convert $find into regular expressions for the whole line
foreach ($find as $i => $key)
$find[$i] = '~("'.$key.'"\s*=>\s*")[^"]*(",\r?\n?)~u';
// convert $replace to use the first and second part of any match
// and put the new translation in between
foreach ($replace as $i => $translation)
$replace[$i] = '$1'.$translation.'$2';
// read translation.php
$contents = file_get_contents("translation.php");
// do the replacements
$contents = preg_replace($find, $replace, $contents);
// debug output, just delete later
var_dump($find, $replace, $contents);
// you want to save your changes into translation.php
// file_put_contents("translation.php", $contents);
?>
if you have to manage more than a few values in your translation.php, consider using a database like mysql to do this. changing the values and even having multiple language support is way easier with mysql.
there also is a special library for handling translations of text: http://php.net/manual/de/book.gettext.php

Categories