I have an issue with a cms where code inside a textarea is executing when you try to save it. For example, lets say you have a textarea with the following html/php in it.
<div class="footer">
<?php include("assets/footer.php"); ?>
</div>
On most servers it works fine and just reads the code as text and saves it perfectly. However, on other servers, it actually parses the php and executes it when you click save. This causes an error and breaks the app. I have tried different methods of opening and reading the file such as fread and file_get_contents and all seem to behave the same. I also tried to wrap the data loaded into the block as CDATA but that did not help either.
Any other ideas what might be causing this and any way around this?
Thank you VERY much in advance for any help on the subject.
This is how the text is saved:
$fp = #fopen($fname, "w");
if ($fp) {
fwrite($fp, $block);
fclose($fp);
}
This is how the file is read:
if (file_exists($fname)) {
$fp = #fopen($fname, "r");
if (filesize($fname) !== 0) {
$loadblock = fread($fp, filesize($fname));
$loadblock = htmlspecialchars($loadblock);
fclose($fp);
}
}
Here is the form:
<form method = "post" action = "">
<textarea name = "text" ><?php echo $loadblock; ?></textarea>
</form>
Simple ways:
1) Adding & Stripping Slashes
$loadblock = addslashes($_POST['page']);
$loadblock = stripslashes($loadblock);
2) HTML Entities
$loadblock = htmlentities($loadblock);
Those are two simple ways you can do it, this is just so you can understand a basic way or two. :)
Related
I am trying to remove tags from a textarea.
I open a php page in a textarea successfully using the code bellow but I only want the code to be there and remove the <?php from the top of the page and ?> from the bottom of the page in the textarea.
this is my php code for loading the php page:
<?php
$fn = "phpPage.php";
if (isset($_POST['content']))
{
$content = stripslashes($_POST['content']);
$fp = fopen($fn,"w") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
}
?>
and this is how i load the page in the textarea:
<textarea id="code" style="width:450px;" rows="25" cols="50" name="content"><?php readfile($fn); ?></textarea>
I tried this and it didn't work without giving me any error:
strip_tags($fn, '<?php ?>');
could someone please advise on this?
Thanks
EDIT: I've tried all the suggestions and none worked so far.
see this for an inspiration
$string = "SO.ME.TE.XT";
$string = str_replace(".","",$string);
echo($string);
will return "SOMETEXT". Hence
$string = YOUR PHP CODE;
$string = str_replace("<?php","",$string);
$string = str_replace("?>","",$string);
echo($string);
Should work in your case.
Update 1:
Another approach would be using jquery and a simple replace script:
$(document).ready(function () {
var codeContents = $("#code").val();
$("#code").val(codeContents.replace("<?php","").replace("?>",""));
});
Its not possible to do it in php.
There are ways to read content of a .php file:-
-> highlight_string(file_get_contents($fn));
-> readfile($fn);
-> $Vdata = file_get_contents($fn);
$abc = var_dump($Vdata);
But these can only read the content and also these functions are not returning the output, so that we can assign them to any variable and can use them as per our wish.
We can just print/display the content of a .php file..
Well, the Jquery code shared by "JKurcik" can work for you but the issue you are facing becuase you are using that code in your .php file***(NOTE: In a .php file whenever or wherever we put "<?php", it starts considering the start of php code)*.
You can make this working by adding that code
$(document).ready(function () {
var codeContents = $("#code").val();
$("#code").val(codeContents.replace("<?php","").replace("?>",""));
});
in a seperate custom.js file and call that js file in your .php doc, then it'll work for sure.
Basically, I want to update static HTML files with code snippets input by users from a standard form. I understand how updating the files work, I'm just unsure as to how I go about including the code input from the form to my php file, which is shown below.
<?php
if($handle = opendir()) {
$search = '</body>';
replace = <<< EOF
<!-- I want to populate this with form field input.-->
EOF;
while(false !== ($entry = readdir($handle))) {
if(is_dir($entry)) continue;
$content = file_get_contents($entry);
$content = str_replace($search, $replace . '</body>', $content);
file_put_contents($entry, $content);
}
}
echo 'done';
?>
Any help greatly appreciated.
I would approach this a bit differently. I suggest having a template file aside from the one being modified. That way, you are always modifying a fresh copy instead of having to worry about what changed in the new version.
If your needs become more advanced beyond simply dropping in some markup, I might suggest using a DOM parser.
Finally, I'm sure you have a good reason for writing these static files... just remember the security implications of doing so. You're effectively letting someone do almost anything they want to your server.
Although I agreed it was in no way the best solution to the specific problem, for anyone that may find this useful in the future I used file_get and str_replace to achieve desired results. The code below will allow you to search a file for a specific term and replace with whatever you want based on form input.
<?php
//These are the variables the html file will post to the script.
$filename = $_POST['myFile'];;
$tofind = $_POST['myFind'];;
$toreplace = $_POST['myReplace'];;
$file = file_get_contents($filename);
$end = str_replace($tofind, $toreplace, $file);
$fp = fopen($filename, "w"); //Open the filename and set the mode to Write
if(fwrite($fp, $end)) ; //Write the New data to the opened file
fclose($fp); //Close the File
echo(" File name is $filename ... Finding $tofind .... Replacing with $toreplace ..... Done !");
?>
Though it's a horrible solution, mixed with your code this will do
$replace = array_key_exists('input',$_REQUEST) ? $_REQUEST['input'] : '';
//$replace = sanitize($replace); // there's so much bad with this string
//do the needfull
?>
<form method='GET' action='#'>
<input type='text' name='input' />
<input type='submit' />
</form>
I am saving and editing data in text files through a text area using CKeditor and everything is working smoothly. Everything except new lines ("<br />") that don't show when I try to edit/update the text file via my update.php. I really can't find out what is the issue, I have tried to replace tag after tag and did not manage to solve the problem.
Code for reading and writing on the text file:
$text1 = "../conteudos/start/text1.txt";
if (isset($_POST['body1'])) {
$newData = nl2br($_POST['body1']);
$handle = fopen($text1, "w");
fwrite($handle, $newData);
fclose($handle);
}
// ------------------------------------------------
if (file_exists($text1)) {
$myData1 = file_get_contents($text1);
$myData1 = strip_tags($myData1);
}
Code for editing the text contents:
<textarea class="ckeditor" name="body1" id="body1">
<?php echo str_replace("<br />","",$myData1); ?>
</textarea>
As mentioned before, the text shows up nicely on my index.php with no html tags whatsoever, but when I try to edit it via the text area above I still get no tags, but I get all the text into one single line. This really should be working because I am using "nl2br" function, but apparently something is canceling it.
What can I do?
I think what you are trying to do is:
$text1 = "../conteudos/start/text1.txt";
if (isset($_POST['body1'])) {
$newData = nl2br($_POST['body1']);
$handle = fopen($text1, "w");
fwrite($handle, $newData);
fclose($handle);
}
// ------------------------------------------------
if (file_exists($text1)) {
$myData1 = file_get_contents($text1);
//Change it here first
str_replace("<br />","\n",$myData1); //You also forgot the new line character I think.
$myData1 = strip_tags($myData1);
}
Then you can do this:
<textarea class="ckeditor" name="body1" id="body1">
<?php echo $myData1; ?>
</textarea>
You made a small logic error according to what I see. According to my understanding, you want to strip out the tags but preserve the new line. So change the "< br />" first before you strip out the tags. Hopefully that's what you want I guess.
You are stripping the tags from your file ($myData1 = strip_tags($myData1)). <br /> is a tag, so you're stripping it out too!
This makes your str_replace useless, since the tag has already been stripped. In any case, you shouldn't need that nl2br in the first place, since newline characters are perfectly valid inside text files...
Something very strange happened because according to the user Touch, his method was working on his computer. Unfortunately it wasn't working on mine! So after a while thinking I came to the conclusion that I was over doing some process of replacement of tags. In order to confirm or not this theory of mine I decided do "back-engineer" Touch's method by erasing line by line and seeing what the result was. In the end I saw that my conclusion was correct, I was over doing process of tag replacement because this code:
$text2 = "../conteudos/start/text2.txt";
if (isset($_POST['body2'])) {
$newData = nl2br($_POST['body2']);
$handle = fopen($text2, "w");
fwrite($handle, $newData);
fclose($handle);
}
// ------------------------------------------------
if (file_exists($text2)) {
$myData2 = file_get_contents($text2);
$myData2 = $myData2;
}
worked in perfection. I can only think that this was due to I was using KCEditor...
A big thanks to all that answered, maing me think and helping me this way to achieve my goal!
I am creating a slideshow editor. I have been able to parse a file and present it to the user in a form. Now I need to figure out how to write the saved information to the file. I want the user to be able to edit the information before and after the slideshow, so there is no specific set of information to be able to overwrite the whole file.
If there is a way to get all of the text before the div and copy it to the variable, add the new information, then get the rest of the information after the div and add that to the variable and then write all that information to the file, then that would work. Otherwise, here is what I have put together.
/* Set Variables */
$x = $_POST['x'];
$file = $_POST['file'];
$path = '../../yardworks/content_pages/' . $file;
$z=0;
while ($z<$x){
$title[$z] = $_POST['image-title'.$z];
$description[$z] = $_POST['image-desc'.$z];
$z++;
}
for ($y=0; $y<$x; $y++){
$contents .= '<li>
<a class="thumb" href="images/garages/'.$file[$y].'">
<img src="images/garages/'.$file[$y].'" alt="'.$title[$y].'" height="100px" width="130px" class="slideshow-img" />
</a>
<div class="caption">
<div class="image-title">'.$file[$y].'</div>
<div class="image-desc">'.$description[$y].'</div>
</div>
</li>';
}
/* Create string of contents */
$mydoc = new DOMDocument('1.0', 'UTF-8');
$mydoc->loadHTMLFile($path);
$mydoc->getElementById("replace")->nodeValue = $contents;
$mydoc->saveHTMLFile($path);
$file = file_get_contents($path);
$file = str_replace("<", "<", $file);
$file = str_replace(">", ">", $file);
file_put_contents($path, $file);
?>
Nothing throws out an error, but the file also remains unchanged. Is there anything I can change or fix to make it write to the file? This is all I have been able to find regarding this specific problem.
I would like to stick to one language, but if I find a way to write to the file using javascript, do the php variables pass on to the javascript section or do I have to stick with one language?
**Edit
Everything is working. ONE problem: is there a way to keep the special characters without converting them? I need the < and > to stay as they are and not convert to a string
I have decided to save the file as it is and use a separate code set to replace the string. I have edited my question above.
In a multilingual site i have two php files that contains php constants.
Like
define('EMAIL', 'Email');
define('GENDER', 'Gender');
.
.
.
I provide editing of these files from admin side using a textarea in form. print full file in textarea.
When ever admin Update the files it contribute redirection issue, means after inclusion of this file header() function fails reporting a non white space character above.
I checked the php file after editing, and it contain a lot of extra space between each php statment as follow,
define('EMAIL', 'Email');
define('GENDER', 'Gender');
define('NAME', 'name');
Also a long single line breaks into many lines like.
define('SENTENCE', 'this is a long sentence that
breaks into many lines according to width of text area as i noted');
So this also contribute error as it must be in single line
I am sure these extra spaces and line breaks are cause of all issues. I am using this code in printing between textarea:
<textarea style="width: 664px; height: 353px;" id="edit_file" name="edit_file"><?php
$file = fopen("../en.php", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file);
}
fclose($file);
?> </textarea>
and for saving file:
if(isset($_POST['btn']) && $_SERVER['REQUEST_METHOD']=='POST' && !empty($_POST['btn'])){
if (get_magic_quotes_gpc()) {
$filedata = stripslashes($_POST['edit_file']);
}
$filedata=str_replace(array("<br />'",'\n'),array("",''),$filedata);
$size=strlen($filedata);
$file = fopen("../en.php", "w") or exit("Unable to open file!");
fwrite($file,"$filedata",$size);
fclose($file);
}
There is 1 unexpected quote and \n cannot be put inside simple quotes :
$filedata=str_replace(array("<br />'",'\n'),array("",''),$filedata);
Replace by :
$filedata=str_replace(array("<br />","\n"),array("",''),$filedata);