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
Related
First, forgive me if this is an overly pedantic question. I have searched trying to find answers but perhaps I'm using the wrong search terms.
Trying to use an INI file for a simple PHP application, where there is an admin page to allow application options to be easily changed. I'm able to read in the ini file with no issue, problem I'm coming across is on the write - if any boolean values are false, they won't get put into the _POST and as such don't get written back into the ini file. Here's my sample:
settings.ini file:
[Site options]
bRequireLegal['Require NDA before badge print'] = true ;
bCollectVehicleInfo['Collect vehicle information'] = false;
bShowAdditionalMessageBeforeBadgePrint['Show badge printing message'] = true;
[Company info]
companyname['Company Name'] = 'The Company, Inc.' ;
Code to read in the ini file (settings.php):
$filepath = 'settings.ini'; //location of settings file
$settings = parse_ini_file($filepath, true, $scanner_mode = INI_SCANNER_TYPED);
//pull everything in ini file in as variable
foreach($settings as $section=>$options){
foreach($options as $option=>$values){
foreach($values as $descriptor=>$value){
if(is_bool($value) === true) {
${htmlspecialchars($option)} = +$value;
}
else ${htmlspecialchars($option)} = $value;
}
}
}
And finally, the options setting page:
<?php
include 'settings.php';
//after the form submit
if($_POST){
$data = $_POST;
update_ini_file($data, $filepath);
}
function update_ini_file($data, $filepath) {
$content = "";
//parse the ini file to get the sections
foreach($data as $section=>$options){
//append the section
$content .= "[".$section."]\r\n";
//append the values
foreach($options as $option=>$values){
$content .= $option;
foreach($values as $descriptor=>$value){
$content .= "['".$descriptor."'] = '".$value."';\r\n";
}
}
$content .= "\r\n";
}
if (!$handle = fopen($filepath, 'w')) {
return false;
}
$success = fwrite($handle, $content);
fclose($handle);
return $success;
}
?>
<html>
<body>
<?php
?>
<div class="container-fluid">
<form action="" method="post">
<?php
foreach($settings as $section=>$options){
echo "<h3>$section</h3>";
//keep the section as hidden text so we can update once the form submitted
echo "<input type='hidden' value='$section' name='$section' />";
//print all other values as input fields, so can edit.
foreach($options as $option=>$values){
foreach($values as $descriptor=>$value){
if(is_bool($value) === true) {
echo "<p>".$descriptor.": <input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." /></p>";
} else
echo "<p>".$descriptor.": <input type='text' name='{$section}[$option][$descriptor]' value='$value' />"."</p>";
}
}
echo "<br>";
}
?>
<input type="submit" value="Update INI" />
</form>
</div>
</body>
</html>
Any help would be greatly appreciated!
In your update_ini_file() function, replace this:
$content .= "['".$descriptor."'] = '".$value."';\r\n";
with
$content .= "['".$descriptor."'] = '".($value ? 'true' : 'false')."';\r\n";
This will cause it to write the strings 'true' and 'false' instead of literal Boolean values. See How to Convert Boolean to String
Edit to add:
I think you're generating your checkboxes incorrectly:
<input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." />
This will cause the 'true' boxes to be checked, but they will still lack a value (and thus will not be transmitted to the server when the form is submitted). You should change that code to:
<input type='checkbox' name='{$section}[$option][$descriptor]' value='1'".(($value===true)?" checked":"")." />
In other words, all checkboxes should have a value of '1', but the way the browser works, only those which are checked will be submitted.
Edit to add:
Checkboxes that are not checked will not get submitted. That explains why you are not seeing any output for values that are 'false': they simply don't get submitted. When you loop through $data (which comes from $_POST), it is missing those unchecked (and thus 'false') checkboxes.
Using a solution found here: POST unchecked HTML checkboxes
Change this:
echo "<p>".$descriptor.": <input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." /></p>";
to this, which includes a hidden field that has the value '0', which will get submitted even if the corresponding checkbox is unchecked:
echo "<p>".$descriptor.": <input type='hidden' name='{$section}[$option][$descriptor]' value='0'><input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." /></p>";
However, this has its own set of potential problems, specifically when a checkbox is checked, you will send two identically named fields: one with a '0' value and the other with a '1' value. This is explained in the link above, and is left as an exercise for you to solve (or ask for further details on) if my answer doesn't work.
The file has a 2 texboxes submit button when it is tapped the data is put into the newly created file.Each new created file
I have file j.php that creates a texfile question.$myDate.txt creates a new txt file with a unique name and $question1 represents the question and it is put in the textfile data as the first element the sign "," splits $question1 and $question2. The variable $question2 represents the answer. And is put the second element in the text file.
The second file questions.php opens instntly after the button is submitted the file is supposed the read adn split the data of the text file and read it and dispay it once the texfile is split into two elements since the text files contains two elements. The first one shows up as a question and the texbox in should be written an answer and the form would be submitted.
But the problem on file 2 it it dosen't read the textfile data. when the text box pops up.
<?php
if(isset($_POST['submit'])) {
$number =$number +1;
$myDate = round(10*microtime(TRUE));
$result ="question".$myDate.".txt";
$question1 = $_POST['name'];
$question2 = $_POST['age'];
$file = fopen( $result, "w+" ) or die( "file not open" );
$s = $question1 . "," . $question2 . "\n";
fputs($file, $s)or die("Data not written");
// Here - redirect to questions.php to display the contents.
header('Location: questions.php');
die;
}
else{
echo
'<center>
<form action = "j.php" method = "post">
<br>Question you want ask the person <input type = "text" name="name"> <br>
<br>Answer<input type = "text" name = "age"><br>
<input type = "submit" name = "submit" value = "Make Question">
</form>
</center>';}
?>
<?php
$myDate = glob("*.txt");
$myFile = "question".$myDate."txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
$arr =explode(",",$theData);
$x=$arr[0];
$y = $arr[1];
$text = $_POST["name"];
$text = true;
if($_POST['submit']) {
$text = $_POST["name"];
if ( $text ==$y) {
echo "<font color = 'red'>Your answer is incorrect</font>";
} else {
echo "answer not correct";
}
}
?>
<center>
<form method = "post">
<?php echo $x ?> <input type = "text" name="name"> <br>
<input type = "submit" name = "submit" value = "Submit answer">
</form>
</center>
\\expected output the texfile being read and next to the text box the question popped upp\\
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.
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.
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.