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);
Related
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 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. :)
I have created new .php file through php file system and now I am trying to write html code into file. Here is the code
$file = 'django unchained.php';
if($handle = fopen($file , 'a'))
{
$text = htmlentities("Just link");
echo $text; // here it shows up fine in webpage.
file_put_contents($file , $text); // after writing to file it doesnot appear the same in .php file
fclose($handle);
}
As mentioned in comment above when I echo it in webpage it shows up fine but doesnot appear the same when same string is written to file.
Thanks in advance.
If you open the source code of your HTML page, you'll see the same text, you see in django unchained.php:
<a href="index.php">Just link</a>
This text is generated by htmlentities function, that converts special HTML characters to their entity equivalents. This behaviour is absolutely predictable and correct.
If you want to output to file the unquoted text, do this:
<?php
$file = 'django unchained.php';
$text = "Just link";
echo htmlentities($text); // here it shows up fine in webpage.
file_put_contents($file , $text) or die('Error opening file');
Looks like you have problems with locks, try this code:
$file = 'django unchained.php';
$text = "Just link";
file_put_contents($file , $text) or die('Cannot open file for writing');
note: you do not need fopen, fclose, htmlspecialchars here
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'm trying to open a text file and output its contents with the code below. The text file includes line breaks but when I echo the file its unformatted. How do I fix this?
Thanks.
<html>
<head>
</head>
<body>
$fh = fopen("filename.txt", 'r');
$pageText = fread($fh, 25000);
echo $pageText;
</body>
</html>
To convert the plain text line breaks to html line breaks, try this:
$fh = fopen("filename.txt", 'r');
$pageText = fread($fh, 25000);
echo nl2br($pageText);
Note the nl2br function wrapping the text.
One line of code:
echo nl2br( file_get_contents('file.txt') );
If you just want to show the output of the file within the HTML code formatted the same way it is in the text file you can wrap your echo statement with a pair of pre tags:
echo "<pre>" . $pageText . "</pre>;
Some of the other answers look promising depending on what you are trying todo.
For simple reads like this, I'd do something like this:
$fileContent = file_get_contents("filename.txt");
echo str_replace("\n","<br>",$fileContent);
This will take care of carriage return and output the text. Unless I'm writing to a file, I don't use fopen and related functions.
Hope this helps.
Before the echo, be sure to include
header('Content-Type: text/plain');
Are you outputting to HTML or plain text? If HTML try adding a <br> at the end of each line. e.g.
while (!feof($handle)) {
$buffer = fgets($handle, 4096); // Read a line.
echo "$buffer<br/>";
}
Trying to get line breaks to work reading a .txt file on Apache2 and PHP 5.3.3 with MacOSX 10.6.6 and Camino, the echo nl2br( $text); didn't work right until I printed the file size first too.
BTW it doesn't seem to matter if the .txt file has Linux/MacOSX LF or Windows CRLF line breaks or the text encoding is UTF-8 or Windows Latin1, Camino gets it out OK.
<?php
$filename = "/Users/Shared/Copies/refrain.txt";
$file_ptr = fopen ( $filename, "r" );
$file_size = filesize ( $filename );
$text = fread ( $file_ptr, $file_size );
fclose ( $file_ptr );
echo ( "File size : $file_size bytes<br> <br>" );
echo nl2br ( $text );
?>
You need to wrap your PHP code into <?php <YOU CODE HERE >?>, and save it as .php or .php5 (depends on your apache set up).
Say you have an index.php file hosted by the web server. You want to insert some multi-line text file contents into it. That's how you do it:
<body>
<div>Some multi-line message below:</div>
<div><?= nl2br(file_get_contents('message.txt.asc')); ?></div>
</body>
This <?= ... ?> part is just a shorthand, which instructs the web server, that it needs to be treated as a PHP echo argument.