We help IT Professionals succeed at work.

Using PHP web interface to write out text files.

tsukraw
tsukraw used Ask the Experts™
on
I am wondering what the best language to do a project i have would be.  I am thinking PHP would work the best but am not sure and would like to know what others think and if what i am trying to do is possible.

What i got is a folder with multiple txt files.
Examples:
Don_printers.txt
Mike_printers.txt
Bill_printers.txt
What i need to be able to do is from a web interface be able to see a list of the files and be able to edit them and create new ones if needed.  
So say i needed a new file i click a button it asks for name i put "Joe"  It then creates a text file called Joe_printers.txt
The contents of these files is like this. Just 2 columns (IP, and Printer)with a comma separating the entries.
Example:
192.168.1.1, Joe Printer 1
192.168.10.2, Joe Printer 2

Any ideas on what the best way and best lang would be for this?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
PHP in my View here is some editor based code to get you started.


<?
//By default this script will allow you to edit all the files in $filedir that
//have extensions in the valid_ext array and are writable.  It also allows you
//to edit all the files that are writable and have valid extensions in the sub
//folders of $filedir.  In other words, it recursively searches for files you
//can edit in $filedir.  If you wish to change this behavior, so that it only
//stays in $filedir and doesn't drill down to any of its subdirs,--search for
//$filelist = directoryToArray($filedir, true); and change true to false.

//YOU MUST CHANGE THIS VARIABLE!! Specify the full path to the directory of
//files you wish to be able to edit. NO TRAILING SLASH.
$filedir = "/home/dustin/public_html";

//Valid Extension array.  
//The array below lists the extensions files must have in order to
//show up in the selection drop down box of fileed.php.  NOTE: In order for you
//to be able to edit a file it must have an extension in the array below and
//must be writable (chmoded 666). It must also be in the $filedir folder or
//in a subfolder in the $filedir folder.  All folders that the script must
//transverse in order to reach your file must be chmoded at least 555. To
//add a new extenstion to this array do the following:
//1. Copy the bottom valid_ext line. Insert a new line below it
//   (hit enter).  Paste the line you copied.
//2. Increase [x] by one.
//3. Change the text inside the quotes to the extension you want to allow.
//   Case must match exactly.
//4. Save your changes.
$valid_ext[0] = "TXT";
$valid_ext[1] = "txt";
$valid_ext[2] = "htm";
$valid_ext[3] = "HTM";
$valid_ext[4] = "html";
$valid_ext[5] = "HTML";
$valid_ext[6] = "shtm";
$valid_ext[7] = "SHTM";
$valid_ext[8] = "shtml";
$valid_ext[9] = "SHTML";
$valid_ext[10] = "pl";
$valid_ext[11] = "PL";
$valid_ext[12] = "cgi";
$valid_ext[13] = "CGI";
$valid_ext[14] = "CSS";
$valid_ext[15] = "css";
$valid_ext[16] = "conf";
$valid_ext[17] = "CONF";
$valid_ext[18] = "ASP";
$valid_ext[19] = "asp";
$valid_ext[20] = "JSP";
$valid_ext[21] = "jsp";
$valid_ext[22] = "js";
$valid_ext[23] = "JS";
$valid_ext[24] = "php";
$valid_ext[25] = "PHP";
$valid_ext[26] = "php3";
$valid_ext[27] = "PHP3";
$valid_ext[28] = "PHTML";
$valid_ext[29] = "phtml";
$valid_ext[30] = "ini";
$valid_ext[31] = "INI";
$valid_ext[32] = "cfm";
$valid_ext[33] = "CFM";
$valid_ext[34] = "inc";
$valid_ext[35] = "INC";
//That should cover what most people use!  I hope anyhow :)

//You should not have to change anything below this line.



//IF browser does not send a POST request (ie: if open/save has not been
//pressed) then display the form and the list of files.
if ($_SERVER['REQUEST_METHOD'] != 'POST'){
//If filedir is readable do...
if (is_readable($filedir)) {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<style type="text/css">
h2 {text-align: center}
</style>
<title>Simple File Editor</title>
</head>
<body>
<h2>Simple File Editor</h2>
<form action="<?=$PHP_SELF?>" method="post">
<table>
<tbody>
<tr>
<td>
<?

//Change into filedir
chdir($filedir);
//Print the directory we are in. Should match filedir.
echo "<p> We are in:  ";
echo "<br />";
echo getcwd();
echo "</p>";

//Continue page below.
//INFO for below: Select "name" is variable name.  Option value is variable
//"value".  
?>
<p> Please choose a file to open:</p>
<select name="the_file">
<?
//The below function will read directory contents into an array.
//Taken from http://www.bigbold.com/snippets/posts/show/155.
//Modified some. This will allow us to read all the contents of
//this directory and all sub-directories into an array.
//Once we have the array we will sort it alphabetically
//and print the filenames in the select box.
//The comments below the code snippets in the function
//are how I follow the code.  Since I did
//not write the original code they may not be entirely
//accurate.

function directoryToArray($directory, $recursive) {
//Start function.  Parse var1 as directory.  Parse var2
//as true or false indicating whether to use recursive
//routine or not.

//Create a variable that referees to this file itself.  That way it can be
//excluded from the editable file list, just in case its in the directory
//of files you want to edit.
$me = basename($_SERVER['PHP_SELF']);

$array_items = array();
//Define array for later use.
        if ($handle = opendir($directory)) {
                while (false !== ($file = readdir($handle))) {
//Don't add: this file itself ($me), unix hidden files (.files),
//the up directory link (..) and the current directory link (.)
//to the array.  This will stop the accidental editing of
//important files, and confusing listings.
             

if ($file != "." && $file != ".." && $file != $me && substr($file,0,1) != '.') {
//Open the directory specified in the function.
//For every file that meets the above terms do...
                                if (is_dir($directory. "/" . $file)) {
//If the 'file' in the directory opened is a directory do...
                                        if($recursive) {
//If recursive is set, rerun the function on that directory.
                                                $array_items = array_merge($array_items, directoryToArray($directory. "/" . $file, $recursive));
                                        }
//Add the contents of recursed directory to the array.

//Comment the below two lines out to prevent directories from showing up
//in the file editing list.
                                //        $file = $directory . "/" . $file;
                                  //      $array_items[] = preg_replace("/\/\//si", "/", $file);
                              
                              } else {
                                        $file = $directory . "/" . $file;
                                        $array_items[] = preg_replace("/\/\//si", "/", $file);
//Else if the "file" in the opened directory is a file (not a dir),
//replace // with / and add it to the array.
                                }
                        }
                }
                closedir($handle);
//Close the directory.
        asort($array_items);
//Sort the array alphabetically.
   }
        return $array_items;
//Return the array.
}

//End borrowed code.

//Create the array filelist by running the function
//on the filedir with recursing enabled.
//The true in this function enables recursion.  
//If you don't want the script to recursively
//search for files you can edit change the true to false.
$filelist = directoryToArray($filedir, true);

//Loop through the array. The value in each row should be called $file and
//the following code should be executed against it.
foreach ($filelist as $file)
{
//Get the extensions of the files.  
//Look at each filename at and use
//strrchr to find the last occurrence
//of "." in the filename.  This returns .jpg
//for example.  Then use substr to return
//+1 of .jpg.  Meaning everything after ".".
$ext = substr(strrchr($file, '.'), 1);
//If a file has an extension that
//is in the valid_ext array and that
//file is writable list it in
// the drop down box.
if (in_array($ext,$valid_ext) && is_writable($file)) {
//Add files to a select box.
echo "<option value=\"$file\">$file</option>";
}
}
//Continue page below.
?>
</select>
<br />
<input type="submit" name="open" value="Open" />
</td><td>
<textarea rows="30" cols="80" style="border: 1px solid #666666;" name="updatedfile"></textarea>
<br />
<!-- <div style="text-align: center;"><input type="submit" name="save" value="Save Changes" /></div> -->
</td></tr>
</tbody>
</table>
</form>
</body>
</html>
<?
}
else
{
//If directory can't be opened complain
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
<html>
<head>
<style type=\"text/css\">
h2 {text-align: center}
</style>
<title>Simple File Editor: ERROR!</title>
</head>
<body>
<h2>Simple File Editor: ERROR!</h2>
<p>Could not open directory!! <br /> Permissions Problem??</p>
</body>
</html>";
}
}
///////////////////////////////////////////////////////////////////
//If the open button has been pressed
////////////////////////////////////////////////////////////////////
else if (isset($_POST['open'])){

//If the file can be opened and is writable do....
//This should not be needed because files that aren't writable should
//have never been shown in the selection box.
if (is_writable($_POST["the_file"])) {

//Start page
//INFO for below: Since variable data is not saved across multiple
//form posts-- we must create a hidden input box with the same value as the
//select box on the previous form. That way the 3rd and final form (ie: the
//saving process) can use the same variable as the first form  (read: write to
//the file you choose in the select box.)      
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<style type="text/css">
h2 {text-align: center}
</style>
<title>Simple File Editor: File Opened</title>
</head>
<body>
<h2>Simple File Editor: File Opened</h2>
<form action="<?=$PHP_SELF?>" method="post">
<table>
<tbody>
<tr>
<td>
<input type="hidden" name="the_file2" value="<? echo $_POST["the_file"]; ?>" />
<?
echo "<p>We are working on:  ";
echo "<br />";
//Get previously posted select box data
echo $_POST["the_file"];
echo "</p>";
//Continue page below.
?>
</td><td>
<textarea rows="30" cols="80" style="border: 1px solid #666666;" name="updatedfile">
<?

//Open the file chosen in the select box in the previous form into the text
//area
$file2open = fopen($_POST["the_file"], "r");


//Read all the data that is currently in the selected file into the variable
//current_data.
$current_data = @fread($file2open, filesize($_POST["the_file"]));

/*Dirty hack to allow you to edit files that contain "</textarea>" in them.  If
this was not was not here and you tried to edit a file with </textarea> in it
all of your code up to </textarea> would be in this editing forms textarea and
everything after </textarea> would be executed/displayed.  This is very
confusing, but if you look at the code in this file and then think about it a
bit, you will understand what it does.*/

//Do a case insensitive search for </textarea> in the $current_data string.
//replace it with <END-TA-DO-NOT-EDIT>.
//This means when you are editing files that contain </textarea> the editing
//box will show <END-TA-DO-NOT-EDIT> instead of the </textarea> tag.  Do not be
//alarmed by this.  Do NOT change or remove this tag, it will be converted back
//to </textarea> in the saving process.  If for some reason this does not work
//for you, or if you know a better way to go about doing this please contact
//me.
$current_data = eregi_replace("</textarea>", "<END-TA-DO-NOT-EDIT>", $current_data);
//Echo the data from the file
echo $current_data;
//Close the file
fclose($file2open);
//Continue page below.
?>
</textarea>
<br />
<div style="text-align: center;"><input type="submit" name="save" value="Save Changes" /></div>
</td></tr>
</tbody>
</table>
</form>
</body>
</html>
<?
}
else
{
//If file can't be opened complain
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
<html>
<head>
<style type=\"text/css\">
h2 {text-align: center}
</style>
<title>Simple File Editor: ERROR!</title>
</head>
<body>
<h2>Simple File Editor: ERROR!</h2>
<p>Could not open file!! <br /> Permissions Problem??</p>
</body>
</html>";
}
}
///////////////////////////////////////////////////////
//If save button has been pushed....
//////////////////////////////////////////////////////
else if (isset($_POST['save'])){

//If the file can be opened and is writable do....
//This should not be needed because files that aren't writable should
//have never been shown in the selection box. And should not have been opened
//on the previous page.  
if (is_writable($_POST["the_file2"])) {

//Get variable data for the file we are working with from the hidden input box
//in the previous form.  Then open it.
$file2ed = fopen($_POST["the_file2"], "w+");
//Dirty </textarea> hack part 2.  Copy all of the data in the previous forms
//editing textarea to the variable $data_to_save.  
$data_to_save = $_POST["updatedfile"];
//Do the opposite of above.  This time convert the <END-TA-DO-NOT-EDIT> tag you
//see in the editing form back to its proper </textarea> tag so when your files
//are saved the forms on them will still look/work right.  
$data_to_save = eregi_replace("<END-TA-DO-NOT-EDIT>", "</textarea>", $data_to_save);
//Remove any slashes that may be added do to " ' " s.  Thats a single tick, btw.
$data_to_save = stripslashes($data_to_save);
//Get the data to write from the previously posted text area, plus all the
//processing we did on it above. Write the changes to the file.
if (fwrite($file2ed,$data_to_save)) {
//If write is successful show success page.  
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
<html>
<head>
<style type=\"text/css\">
h2 {text-align: center}
</style>
<title>Simple File Editor: File Saved</title>
</head>
<body>
<h2>Simple File Editor: File Saved</h2>
<p>File saved. <br /> Click <a href=\"\">here</a> to go back to the editor.</p>
</body>
</html>";
//Close file
fclose($file2ed);
}
else {
//If write fails show failure page
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
<html>
<head>
<style type=\"text/css\">
h2 {text-align: center}
</style>
<title>Simple File Editor: ERROR!</title>
</head>
<body>
<h2>Simple File Editor: ERROR!</h2>
<p>File NOT saved!! <br /> Permissions Problem?? <br />  Click <a href=\"\">here</a> to go back to the editor.</p>
</body>
</html>";
//Close file
fclose($file2ed);
}
}
else
{
//If file can't be opened complain
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
<html>
<head>
<style type=\"text/css\">
h2 {text-align: center}
</style>
<title>Simple File Editor: ERROR!</title>
</head>
<body>
<h2>Simple File Editor: ERROR!</h2>
<p>File NOT saved!! <br /> Permissions Problem??</p>
</body>
</html>";
}
}
?>

Commented:
something like, where $dir = "/path_to_the_directory"; is the full path to the folder with the files, and the files and that folder are writeable by the webserver
<?php
$dir = "/path_to_the_directory";

if($_GET['action']=="edit") {
	$id = $_GET['id'];
	$name =$dir."/".urldecode($id );
		$contents = file_get_contents($name);
	echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post">';
	if ($id=="") {
		echo 'Filename:<input name="file_name" type="text" "><br>';
	} else {
		echo '<input name="file_name" type="hidden" value="'.$id.'">';
	}
	
	echo 'contents <input name="file_contents" type="text" value="'.$contents.'"><input name="submit" type="submit" value="save"></form>';
	exit;

}

if(isset($_POST['submit'])) {
	$file_name = $_POST['file_name'];

	$path =$dir."/".$file_name;

	$handle = fopen($path,"w+");
	$contents = $_POST['file_contents'];
	fwrite($handle,$contents);
	fclose ($handle);
	

}


$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {

    if (is_file($dir."/".$filename)) {
            $files[] = $filename;
      }
}
sort($files);

foreach ($files as $file) {
echo '<a href="./'.$_SERVER['PHP_SELF'].'?action=edit&id='.urlencode($file).'">'.$file.'</a><BR>';
}
echo '<a href="./'.$_SERVER['PHP_SELF'].'?action=edit&id=">Create new File</a><BR>';
?>

Open in new window

Most Valuable Expert 2011
Top Expert 2016

Commented:
Wow, I hope the answers do not scare you away!  I have programmed in all kinds of languages and for general-purpose WWW app development, PHP is by far my favorite.  But you need to get some foundation in the language, and for that I would recommend this book:
http://www.sitepoint.com/books/phpmysql4/

It assumes that you know HTML and have some understanding of the principles of computer science.  If you don't, please do not waste your time - just hire a developer.  This is a simple task that you have described here.  The steps would be these...

1. Read the directory and collect all of the files named like XXX_printers.txt.  Display those.
2. Put up an HTML form to read the name for the new file.
3. Read the form input, create the new XXX_printers.txt.

You can add a lot of code for "sanity checks" and "security" and other non-value added overhead, but those are the essential moving parts.  Drop-dead easy.

Learn more about how to use PHP here:
http://us.php.net/tut.php

Learn about its popularity here:
http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html

Best regards, and good luck with your project, ~Ray
I would suggest a simpler solution.  Since this is a user's printer settings list, just keep a copy of them on your hard drive, and change the parameters as you need to, then upload each file from your hard drive to the web server when you change it.  It takes NO programming, it is logical and intuitive, and it takes all of 10 seconds to upload the new file to the server.  Problem solved, you get lunch and home in time for dinner.

Author

Commented:
I want to be able to edit it from the web.  Currently I do the upload method and I want to get awayfrom that.
Then the above coding is part of the solution.  You have to make a query page first in PHP to get the filename, then PHP will open that file on the server, and send back a page with all the contents, in the form of a big form, you edit that form, and it goes back to PHP on the server to change the file and resave it.  Personally, I think this is a LOT of programming to do.

Author

Commented:
Holy smokes!
What did i get myself into. Would this be very big of a project and cost a lot?  I am not looking for anything fancy just a simple web gui to edit these files.  If the cost wouldnt be much and anyone is interested email me: tsukraw@gmail.com

I am thinking this is going to be over my head to get it to do what i really want it to...

Commented:
my code posted earlier should do what you want.  have you tried it?

Author

Commented:
Sorry for the delay.  Yes dmgroom that is what i am looking for.  Is there anyway to get it so that that content isnt shown in one long line?  

Currently it looks like this:
192.168.1.1, Joe Printer 1  192.168.10.2, Joe Printer 2

Which will make it hard for editing and finding stuff.
Is there any way to get it to read it the way it appears in the document?
like:
192.168.1.1, Joe Printer 1
192.168.10.2, Joe Printer 2

Author

Commented:
Was this at all possible dmgroom?

Commented:
Sorry, missed your post of 16 July.  

I amfraid i dont understand your question.  Where is the long line?  In your very first post I got the impression that each file just consisted of one line line like

192.168.1.1, Joe Printer 1

Did I misunderstand?

Author

Commented:
each file consists of multiple lines like

192.168.1.1, Joe Printer 1
192.168.10.2, Joe Printer 2
192.168.2.10,Joe Printer 3
192.168.1.134,Joe Printer 4

Commented:
Ok,  
basically all you have to do is change the "text field" for the contents to a "textarea", then put each entry on  a new line

see modified code below
<?php
$dir = "/path_to_the_directory";


if($_GET['action']=="edit") {
	$id = $_GET['id'];
	$name =$dir."/".urldecode($id );
		$contents = file_get_contents($name);
	echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post">';
	if ($id=="") {
		echo 'Filename:<input name="file_name" type="text" "><br>';
	} else {
		echo '<input name="file_name" type="hidden" value="'.$id.'"><br>';
	}
	echo 'contents<br> <textarea name="file_contents" cols="40" rows = "9" >'.$contents.'</textarea><br><input name="submit" type="submit" value="save"></form>';
	exit;
}

if(isset($_POST['submit'])) {
	$file_name = $_POST['file_name'];
	$path =$dir."/".$file_name;
	$handle = fopen($path,"w+");
	$contents = $_POST['file_contents'];
	fwrite($handle,$contents);
	fclose ($handle);
}

$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    if (is_file($dir."/".$filename)) {
            $files[] = $filename;
      }
}
sort($files);

foreach ($files as $file) {
echo '<a href="./'.$_SERVER['PHP_SELF'].'?action=edit&id='.urlencode($file).'">'.$file.'</a><BR>';
}
echo '<a href="./'.$_SERVER['PHP_SELF'].'?action=edit&id=">Create new File</a><BR>';
?>

Open in new window

Author

Commented:
Perfect!

When i press the "Create new file"  I get
Warning: file_get_contents(C:\Program Files\Reports\Configs\Configs/) [function.file-get-contents]: failed to open stream: No such file or directory in C:\xampp\htdocs\test.php  on line 8

My Directory Line Looks like this
$dir = "C:\Program Files\Reports\Configs\Configs";

Any idea what would cause that?

Commented:
From looking at the line
Warning: file_get_contents(C:\Program Files\Reports\Configs\Configs/)  there is a "/" at the end

if you are on windows you might have to change the "/"  to "\" on lines 7, 21 & 30

Author

Commented:
As soon as i tired doing that the page cannot load at all.
Any other ideas where the / at the end of configs would be coming from?
Commented:
is this any better?
<?php
$dir = "/www/test/txts";

if($_GET['action']=="edit") {
	$id = $_GET['id'];
	$name =$dir."/".urldecode($id );
		$contents = file_get_contents($name);
	echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post">';
	if ($id=="") {
		echo 'Filename:<input name="file_name" type="text" "><br>';
	} else {
		echo '<input name="file_name" type="hidden" value="'.$id.'"><br>';
	}
	echo 'contents<br> <textarea name="file_contents" cols="40" rows = "9" >'.$contents.'</textarea><br><input name="submit" type="submit" value="save"></form>';
	exit;
}

if(isset($_POST['submit'])) {
	$file_name = $_POST['file_name'];
	$path =$dir."/".$file_name;
	$handle = fopen($path,"w+");
	$contents = $_POST['file_contents'];
	fwrite($handle,$contents);
	fclose ($handle);
}

$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    if (is_file($dir."/".$filename)) {
            $files[] = $filename;
      }
}
sort($files);

foreach ($files as $file) {
echo '<a href="./'.$_SERVER['PHP_SELF'].'?action=edit&id='.urlencode($file).'">'.$file.'</a><BR>';
}
echo '<a href="./'.$_SERVER['PHP_SELF'].'?action=edit">Create new File</a><BR>';
?>

Open in new window

Author

Commented:
same result with the error.
When you click the new file is it like trying to open some kind of template file?

Commented:
no, it should just bring up the same form as the editig form, but with a blank name and empty space to type file contents

Author

Commented:
Hmm any ideas then as to what is causing the issue?

Commented:
I'm afraid I can't at the moment understand what the problem might be

Author

Commented:
Did you ever figure out what the issue could be?

Commented:
No, I'm afraid I cant work it out.  Sorry

Author

Commented:
Worked good enough