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>
Related
I was trying to have a form create a page to display information. I was using fwrite() to create the page, but the way I set it up was very ugly and hard to manage, especially when I make the page more complex. I was wondering if there was a different way (I can't imagine that there isn't). Below is the code I have:
$student_name = $_POST["student_name"];
$text = "<!DOCTYPE html><head><title>" . $student_name . "'s Project</title></head><html><body><center><h1><u>" . $_POST["project_title"] . "</u></h1><i>By " . $student_name . "</i></center><br>" . $_POST["student_essay"] . "</body></html>";
$student_page = fopen('./projects/' . $file_count - 1 . '.html', 'w');
fwrite($student_page, $text);
Thanks!
You can do the following
Write a small blank html file and save it somewhere; e.g. "template.html"
1) in PHP you can read it with
$newcontent = file_get_contents("template.html");
2) Open a new file with fopen, write new content, close the file. Done.
if (!file_exists('newname.html')) {
$handle = fopen('path/to/new/file/newname.html', 'w+');
fwrite($handle, $newcontent);
fclose($handle);
}
However, what's the purpose of having a form create a new file everytime the form is submitted? Let me know what your objective is and I'll edit my answer accordingly.
You can see more answers and the original answer here: Create .html file with php
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 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.
UPDATE
Hello again. I found myself with a new problem. The php code worked perfectly on my PC (wamp server) but i've now uploaded it on a free webhost server and while the php part runs perfectly (it produces the array) the javascript function itself doesn't work cause there are no photos in the website when it's loaded. I tried to test it by putting in the function's first line an alert to see if it runs but never showed up. I think that the server for some reason doesn't realise that it is a javascript function because i also had in the getphotos.php this:
window.onload = photos();
which appart from starting the photos function, shows a text. When i moved that line in js file and put the show text line first, it run showing the text but still no photos. What do you think????
END OF UPDATE
Hello to everyone. I am building a website that shows some photos. I want the site to automatically generate the html code that shows the photos by reading the file names in the photo folder, but i need also to use javascript. So I found through the web a solution with php generating javascript which than generates the html code I want and I think this is what I need. But... it doesn't work X_X. So I need someone's help!
Firstly, here is the php/javascript(in getPhotos.php):
<?
header("content-type: text/javascript");
//This function gets the file names of all images in the current directory
//and ouputs them as a JavaScript array
function returnImages() {
$pattern="(*.jpg)|(*.png)|(*.jpeg)|(*.gif)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir('/photos/')) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryArray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
//here starts the javascript function
echo 'window.onload = photos;
function photos(){
var i;
var text1 = "";
var text2 = "";
var text3 = "";
var galleryArray=new Array();'; //Define array in JavaScript
returnImages(); //Output the array elements containing the image file names
//short the images in three sets depending on their names and produce the code
echo 'for(i=0; i<galleryArray.length; i++){
if(galleryArray[i].indexOf("set1_")!=-1){
text1+= "<a rel=\"gallery\" title=\"\" href=\"photos/"+galleryArray[i]+"\">\n<img alt=\"\" src=\"photos/"+galleryArray[i]+"\" />\n</a>\n" ;
}else if(galleryArray[i].indexOf("set2_")!=-1){
text2+= "<a rel=\"gallery\" title=\"\" href=\"photos/"+galleryArray[i]+"\">\n<img alt=\"\" src=\"photos/"+galleryArray[i]+"\" />\n</a>\n" ;
}else if(galleryArray[i].indexOf("set3_")!=-1){
text3+= "<a rel=\"gallery\" title=\"\" href=\"photos/"+galleryArray[i]+"\">\n<img alt=\"\" src=\"photos/"+galleryArray[i]+"\" />\n</a>\n" ;
}
}';
//create text nodes and put them in the correct div
echo 'var code1 = document.createTextNode(text1);
var code2 = document.createTextNode(text2);
var code3 = document.createTextNode(text3);
document.getElementById("galleryBox1").appendChild(code1);
document.getElementById("galleryBox2").appendChild(code2);
document.getElementById("galleryBox3").appendChild(code3);
}';
?>
And this is the code in the mane page index.html:
<script type="text/javascript" src="getPhotos.php"></script><!--get photos from dir-->
This is it, and it doesn't work! I know I ask to much by just giving all the code and asking for help but i can't even think what's wrong, let alone how to fix it.... So please, if you have any idea it would be great.
; after returnImages() is missing.
This function (readdir) may return Boolean
FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "". Please read
the section on Booleans for more
information. Use the === operator for
testing the return value of this
function.
http://php.net/manual/en/function.readdir.php
So try to use while(false != ($file = readdir($handle))){
or while(FALSE !== ($file = readdir($handle))){
Your regular expression is wrong, for one. You need to look at a regex tutorial, like this one.