Open php file, change value for one variable, save - php

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

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.

Can't perform simple array search from array

I have a program that is failing because it's not finding the $post in the search of the array, so it's continuing to add each time. I have used the other suggested method of using a foreach loop, with strpos, such as:
if (strpos($data, $posts) !== false), and this will work find the $post, but it will also find the rest and run against everything in the data/array. hence why I would just like it to search the array, if it's not there add it, if it is, just say it's there or checking in... I've spent 3 days using in_array, array_search, etc, now I'm asking for help...
<html>
<body>
<?php
$post = $_POST['name'];
$data = file("data.txt");
if (in_array($post, $data)) {
echo "$post is checking in...";
}
else {
echo "Adding to $data...";
$data = fopen("data.txt", "a+");
fwrite($data, $post.PHP_EOL);
fclose($data);
}
$data = file("data.txt");
foreach ($data as $d) {
echo $d;
}
?>
</body>
</html>
tclient.html
<html>
<body>
<form action="test4.php" method="POST">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
data.txt
Names
John
Doe
The value in $post probably doesn't have a new line at the end. You can specify not to include new lines when you use file().
file("data.txt", FILE_IGNORE_NEW_LINES);

php reading custom config file and allowing edits via html form

I have a "config" file that lists some configs of another program, and I have a need for my PHP backend application to be able to read and write to this file, hopefully via html forms.
The config file is in the format:
something: 4
something_else: false
then_this: 68000
and_then_this: false
finally_this: true
There is one config parameter per line, and each config parameter is in the format: parameter: value. Ideally I would need the function to read all the parameters and values in this file, stuff them in an array and then iterate through them and allow them to be edited via forms:
$configArray = array(); // The config array would contain the key/value pairs of the parameter: value mentioned above
<form action="edit.php" method="post">
<?php foreach($configArray as $p=>$v) { ?>
<strong><?php echo $p; ?></strong> <input type="text" name="<?php echo $p; ?>" value="<?php echo $v; ?>" />
<?php } ?>
<input type="submit">Save changes!</input>
</form>
Using the above example of how I wish the array to be laid out, I would expect to use var_dump($configArray); and produce the following results:
array(5) {
["something"]=>
int(4)
["something_else"]=>
bool(false)
["then_this"]=>
int(68000)
["and_then_this"]=>
bool(false)
["finally_this"]=>
bool(true)
}
This would produce a list of forms from the config file parameter: value and allow the user to edit them and then save them back to the same file.
Is something like this even possible with PHP?
This might help you. Please change the path and name of the config file instead of "config.txt" in the example below:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 0);
// Read the file content
$content = file('config.txt', FILE_SKIP_EMPTY_LINES);
if ( $content === FALSE ) {
die('Could not read the config file.');
}
// Parse content to create array
$configArray = array();
foreach($content as $config_line) {
list($key, $val) = explode(':', $config_line);
// Remove white space
$val = trim($val);
// Check type of $val
switch(strtolower($val)) {
case 'true':
case 'false':
$type = 'boolean';
break;
case (preg_match('/^[0-9]/', $val) ? true : false) :
$type = 'integer';
break;
default:
$type = 'string';
break;
}
// And set it dynamically
settype($val, $type);
$configArray[$key] = $val;
}
var_dump($configArray);
?>

Merge 2 php scripts

I need some help with some php scripting. I wrote a script that parses an xml and reports the error lines in a txt file.
Code is something like this.
<?php
function print_array($aArray)
{
echo '<pre>';
print_r($aArray);
echo '</pre>';
}
libxml_use_internal_errors(true);
$doc = new DOMDocument('1.0', 'utf-8');
$xml = file_get_contents('file.xml');
$doc->loadXML($xml);
$errors = libxml_get_errors();
print_array($errors);
$lines = file('file.xml');
$output = fopen('errors.txt', 'w');
$distinctErrors = array();
foreach ($errors as $error)
{
if (!array_key_exists($error->line, $distinctErrors))
{
$distinctErrors[$error->line] = $error->message;
fwrite($output, "Error on line #{$error->line} {$lines[$error->line-1]}\n");
}
}
fclose($output);
?>
The print array is only to see the errors, its only optional.
Now my employer found a piece of code on the net
<?php
// test if the form has been submitted
if(isset($_POST['SubmitCheck'])) {
// The form has been submited
// Check the values!
$directory = $_POST['Path'];
if ( ! is_dir($directory)) {
exit('Invalid diretory path');
}
else
{
echo "The dir is: $directory". '<br />';
chdir($directory);
foreach (glob("*.xml") as $filename) {
echo $filename."<br />";
}
}
}
else {
// The form has not been posted
// Show the form
?>
<form id="Form1" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Path: <input type="text" name="Path"><br>
<input type="hidden" name="SubmitCheck" value="sent">
<input type="Submit" name="Form1_Submit" value="Path">
</form>
<?php
}
?>
That basically finds all xmls in a given directory and told me to combine the 2 scripts.
That i give the input directory, and the script should run on all xmls in that directory and give reports in txt files.
And i don't know how to do that, i'm a beginner in PHP took me about 2-3 days to write the simplest script. Can someone help me with this problem?
Thanks
Make a function aout of your code and replace all 'file.xml' to a parameter e.g. $filename.
In the second script where the "echo $filename" is located, call your function.

Categories