Change values within PHP files from… PHP!
Posted: September 20th, 2008 | Author: Mihai Bojin | Filed under: PHP | Tags: form, heredoc, PHP, simple | No Comments »I was just thinking what new tutorial to write about PHP when I came upon this post on talkfreelance.
A user needed help, I needed to write something so why not combine the two needs and create something elegant and useful.
You can download the full project files here.
Basically the problem is this:
We have this PHP file:
codefile.php
<?php $value1='content1'; $value2='content2'; ?>
We need to be able to edit the two variables from within a form without using any databases.
The code to do this is very simple and you can see it below. Hope it helps !
index.php
<?php // name of file that you want to save the content in $fileName = 'codefile.php'; // Load code from filename $code = file_get_contents($fileName); // Extract PHP tags with str_replace $array_strip_tags = array(''); $array_strip_with = array('', '', ''); $code = str_replace( $array_strip_tags, $array_strip_with, $code ); // Execute code from file and import $value1 and $value2 into the GLOBAL namespace eval( $code ); // Load values sent from the form (and check if form was submitted) $submitted = isset($_POST['submitted'])?$_POST['submitted']:false; $strValue1 = isset($_POST['submitted'])?$_POST['value1']:$value1; $strValue2 = isset($_POST['submitted'])?$_POST['value2']:$value2; // If the form was submitted save the file with the new data if ($submitted) { // Create string in heredoc syntax $strToSave = <<<RTT; <?php \$value1='$strValue1'; \$value2='$strValue2'; ?> RTT; // Save string to file $return = @file_put_contents($fileName, $strToSave); // Set success or error message if ($return) { $errorMessage = 'File was saved sucesfully'; } else { $errorMessage = 'There was an error saving the file! Check file permissions.'; } } ?> <form method="post" action="<?=$PHP_SELF?>"> <fieldset> <legend>Change values from PHP - form</legend> < ?php if (isset($errorMessage) && strlen($errorMessage) > 0): ?><span>< ?=$errorMessage?></span> < ?php endif; ?> <input type="hidden" value="1" name="submitted" /> <label for="value1">Value 1:</label><input type="text" value="<?=$strValue1?/>" name="value1" /><br /> <label for="value2">Value 2:</label><input type="text" value="<?=$strValue2?/>" name="value2" /><br /> <input type="submit" value="Submit" /> </fieldset> </form>
As usual, code comments are included and will help you better understand what every part of it does.
You can download the full project files here.
If you have any other solutions to this problem feel free to post it in the comments.




