Page 1 of 1

Advanced file editor. CMS-like with great comments! Rate Topic: ****- 3 Votes

#1 creativecoding  Icon User is online

  • Hash != Encryption
  • member icon


Reputation: 928
  • View blog
  • Posts: 3,212
  • Joined: 19-January 10

Posted 20 September 2010 - 09:02 PM

Well, this is my first tutorial, so, I'm sorry for any mistakes. Oh yeah, and if you see a link with puu.sh, it's an image link. Click it to see the image. Now, lets get started...

First of all, you should probably make a new directory for this. I named mine CMS. (yeah, I know it's not a full out CMS, but its just short. And I like short.)

Secondly, we need a few files. Create these files with 0755 perms:
http://puu.sh/dfx

index.php
Lets open up index.php now. Put this code in it:
<?
// This is where your files go. Make sure a '/' is at the end.
$userDir = "thisisthedirwiththefiles/";
//This little bit handles the deletion of files. As you can see, it uses GET to determine if the user wants to delete a file.
$del = $_GET['del'];
if($del){
$del = $userDir . $del;
// Quick little thing to prevent ../ hacks
$del = str_replace("..", "", $del);
// Makes sure we can delete the file.
chmod($del, 0777);
// Runs the unlink (delete) script inside the if statement. Notice how I put a @ before the unlink. This prevents the script from showing any ugly errors on that line. Although, this is more of a feature for once you release it.
if(@unlink($del)){
// Delete success! Celebrate by using a javascript message box inside of an echo.
echo "<script language=\"javascript\" type=\"text/javascript\">
alert('File deleted.');
</script>";
}
else{
// Delete failed! Mourn by using a javascript message box inside of an echo.
echo "<script language=\"javascript\" type=\"text/javascript\">
alert('Error deleting file. Are you sure it's not a directory?');
</script>";
}
}
// $l is something I do to make line breaks easy
$l = "<br />";
// Your title.
echo "<h1>CMS - Content Management System</h1> $l";
// Link to open a new file window.
echo "[<a href=\"newFile.php\" target=\"_blank\">New file</a>]";
// Credits go to http://www.liamdelahunty.com/tips/php_list_a_directory.php for this content listing script
// open this directory 
$myDirectory = opendir($userDir);

// get each entry
while($entryName = readdir($myDirectory)) {
    $dirArray[] = $entryName;
}

// close directory
closedir($myDirectory);

//    count elements in array
$indexCount    = count($dirArray);

// sort 'em
sort($dirArray);

// This is where it really starts to get crazy!
// print 'em
print("<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n");
// Create our tables
print("<TR><TH>File <font size=2>(click the view)</font></TH><TH>Edit</TH><TH>Delete</TH></TR>\n");
// loop through the array of files and print them all
for($index=0; $index < $indexCount; $index++) {
        if (substr("$dirArray[$index]", 0, 1) != "."){ // don't list hidden files
        print("<TR><TD><a href=\"$userDir/$dirArray[$index]\">$dirArray[$index]</a></td>");    
        print("<TD><a href=\"editor.php?file=$dirArray[$index]\">Edit</a></TD>");
        print("<TD><a href=\"index.php?del=$dirArray[$index]\">Delete</TD>");
        print("</TR>\n");
    }
}
print("</TABLE>\n");
echo "<br /><br /> Copyright mumbo jumbo";
?>


Oh god, time for explaining....



$userDir = "thisisthedirwiththefiles/";

You will find this in the other files. It's just a variable that tells the script where to find the files.

$del = $_GET['del'];
if($del){

This part checks to see if the deletion of a file has been activated.

$del = $userDir . $del;
// Quick little thing to prevent ../ hacks
$del = str_replace("..", "", $del);
// Makes sure we can delete the file.
chmod($del, 0777);

This part composes the file to delete and then chmod's (changes permissions) to 0777 (basically, god powers :P). This is important because improper permissions will not allow the deletion of the file.

// Runs the unlink (delete) script inside the if statement. Notice how I put a @ before the unlink. This prevents the script from showing any ugly errors on that line. Although, this is more of a feature for once you release it.
if(@unlink($del)){
// Delete success! Celebrate by using a javascript message box inside of an echo.
echo "<script language=\"javascript\" type=\"text/javascript\">
alert('File deleted.');
</script>";
}
else{
// Delete failed! Mourn by using a javascript message box inside of an echo.
echo "<script language=\"javascript\" type=\"text/javascript\">
alert('Error deleting file. Are you sure it's not a directory?');
</script>";
}
}

Rather big part here. As you can see, the unlink is inside of the if statement. This will run it and return whether it succeeded or failed to unlink the file. Notice how I put the @ in front of it. This stops the file from showing an error if there is a problem. I also put a javascript popup box script inside of the echo to report if the file was deleted or not.

// $l is something I do to make line breaks easy
$l = "<br />";
// Your title.
echo "<h1>CMS - Content Management System</h1> $l";
// Link to open a new file window.
echo "[<a href=\"newFile.php\" target=\"_blank\">New file</a>]";

Show the title and button to create a new file.

// Credits go to http://www.liamdelahunty.com/tips/php_list_a_directory.php for this content listing script
// open this directory 
$myDirectory = opendir($userDir);

// get each entry
while($entryName = readdir($myDirectory)) {
    $dirArray[] = $entryName;
}

// close directory
closedir($myDirectory);

//    count elements in array
$indexCount    = count($dirArray);

// sort 'em
sort($dirArray);

// This is where it really starts to get crazy!
// print 'em
print("<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n");
// Create our tables
print("<TR><TH>File <font size=2>(click the view)</font></TH><TH>Edit</TH><TH>Delete</TH></TR>\n");
// loop through the array of files and print them all
for($index=0; $index < $indexCount; $index++) {
        if (substr("$dirArray[$index]", 0, 1) != "."){ // don't list hidden files
        print("<TR><TD><a href=\"$userDir/$dirArray[$index]\">$dirArray[$index]</a></td>");    
        print("<TD><a href=\"editor.php?file=$dirArray[$index]\">Edit</a></TD>");
        print("<TD><a href=\"index.php?del=$dirArray[$index]\">Delete</TD>");
        print("</TR>\n");
    }
}
print("</TABLE>\n");
echo "<br /><br /> Copyright mumbo jumbo";

Big, but simple. This shows the files in a table. It also puts down links for the option to view the file, edit it, or delete it.



newFile.php
Time for some more! Let's work on newFile.php now. Put this code in it:
<?
// Your files directory
$userDir = "wootmoredirstuff";
// Check if the submit button has been pressed.
$sub = $_GET['Submit'];
if($sub){
// Retrieve file's name
$name = $_GET['file'];
// Replace those rude Hax0rs
$name = str_replace("../", "", $name);
$name = $userDir . $name;
// Create file using fopen
$ourFileHandle = fopen($name, 'w') or die("Creation failed!");
fclose($ourFileHandle);

echo "File created. You may now close this window.";
}
else{
// Because GET has detected that the submit button has not been pressed, else will show the form.
?>

<form name="input" action="<? $_SERVER['php_self']; ?>" method="get">
Filename: <input type="text" name="file" />
<input type="submit" value="Submit" name="Submit" />
</form>

<?
// And now close the else statement.
}
?>

Remember, it looks short and small because it will be opened in a new window.

$userDir = "wootmoredirstuff";

Remember? Put in the correct directory.

// Check if the submit button has been pressed.
$sub = $_GET['Submit'];
if($sub){

This uses the same technique from the deletion process in index. It checks if submit has been pressed and then runs the if statement.

// Retrieve file's name
$name = $_GET['file'];
// Replace those rude Hax0rs
$name = str_replace("..", "", $name);
$name = $userDir . $name;

Now, here we have the replacement of .. with nothing (it just removes them). This prevents hax0rs from using .. to gain access to lower directories. Then it composes the full directory.

// Create file using fopen
$ourFileHandle = fopen($name, 'w') or die("Creation failed!");
fclose($ourFileHandle);
echo "File created. You may now close this window.";

This part basically creates the file using fopen. Nothing more to it.

}
else{
// Because GET has detected that the submit button has not been pressed, else will show the form.
?>

<form name="input" action="<? $_SERVER['php_self']; ?>" method="get">
Filename: <input type="text" name="file" />
<input type="submit" value="Submit" name="Submit" />
</form>

<?
// And now close the else statement.
}
?>

And this is the final part of the script. Basically, the else will trigger the first time the user has entered the window. This is because submit has not been pressed yet. So now, it will display the form instead of running the creation scripts. $_SERVER['php_self']; is sorta like a refresh, only it puts the forms variables into the URL, so then it's accessible by the script. This means less files, but less security.


editor.php
Time for the ability to edit files.
<?php 
// Yet again, define the userDir
$userDir = "ohlookadir/";
$filename = $userDir . $_GET['file'];
if (file_exists($filename)) {
    // File exist, continue
// Change perms for the ability to edit. It's just a little safety feature.
    chmod($filename, 0777);
// Mumbo jumbo from v1
$loadcontent = $filename; 
$save_file = $_POST['save_file'];
$savecontent = $_POST['savecontent'];
    // Opens up our content so that we can view the file's source            
    $fp = @fopen($loadcontent, "r");
        $loadcontent = @fread($fp, filesize($loadcontent));
        $loadcontent = htmlspecialchars($loadcontent);
        fclose($fp);
?>
// Display title
<h2>Editing <? echo $_GET['file']; ?></h2>
// Here you will see that the action is save.php, a file that we created awhile back
<form method=post action="save.php?file=<? echo $filename ?>">
// Inserts loadcontent, displaying what's already in the file.
<textarea name="savecontent" cols="100%" rows="25"><?=$loadcontent?></textarea>
<br>
<input type="submit" name="save_file" value="Save">  
</form>

<?
} else {
// File does not exist
echo "Error, file does not exist.";
}
?>



$userDir = "ohlookadir/";

You know what to do...

$filename = $userDir . $_GET['file'];
$filename = str_replace("..", "", $filename);
if (file_exists($filename)) {

Retrieves the file and puts it together. Replace also removes the .. from the hax0rs. It then checks if the file exist. If we tried to open a file that didn't exist, it would return an error or create it (I can't remember which).

// File exist, continue
// Change perms for the ability to edit. It's just a little safety feature.
    chmod($filename, 0777);
// Mumbo jumbo from v1
$loadcontent = $filename; 
$save_file = $_POST['save_file'];
$savecontent = $_POST['savecontent'];

We chmod (change perms) of the file to 0777 (god mode) to make sure that the users work can be opened and saved.

// Opens up our content so that we can view the file's source            
    $fp = @fopen($loadcontent, "r");
        $loadcontent = @fread($fp, filesize($loadcontent));
        $loadcontent = htmlspecialchars($loadcontent);
        fclose($fp);
?>

This part will open our file using fopen and fread. It will then read the source and copy it into $loadcontent. We then close our PHP brackets (or whatever they are called) so that our html form can begin. Notice how I put a @ in front of fread. This is to prevent a common error from being display (if the file is empty, it will return an error).

// Display title
<h2>Editing <? echo $_GET['file']; ?></h2>
// Here you will see that the action is save.php, a file that we created awhile back
<form method=post action="save.php?file=<? echo $filename ?>">
// Inserts loadcontent, displaying what's already in the file.
<textarea name="savecontent" cols="100%" rows="25"><?=$loadcontent?></textarea>
<br>
<input type="submit" name="save_file" value="Save">  
</form>

This is the main part to it all. This will display the text area preloaded with whatever source is already in the file we are editing. Then the form will go to save.php?file=ourfilename.

<?
} else {
// File does not exist
echo "Error, file does not exist.";
}
?>

And now we close up our first if statement with else to display that the file is not legit.



save.php
Sweet, we are almost done! Time for saving the file (which is fairly simple).
<?
// Retrieve file's name 
$filename = $_GET['file'];
// Make sure the perms are still set.
chmod($filename, 0777);
$loadcontent = $filename; 
$save_file = $_POST['save_file'];
$savecontent = $_POST['savecontent'];

// A little safety feature that replaces <? and ?>, thus, preventing your users from entering any php (if you don't allow it). Of course, if you don't want it, you can comment both lines out. 
$savecontent = str_replace("<?", "", $savecontent);

$savecontent = str_replace("?>", "", $savecontent);

// And now we save the file using fopen and fwrite. Then display if the save was successful or a failure.
$savecontent = stripslashes($savecontent);
$l = "<br />";
        $fp = @fopen($loadcontent, "w");
        if ($fp) {
            if(fwrite($fp, $savecontent)){
            echo "<div align=\"center\"><h1>Save Successful!</h1></div>";
            }
            else{
            echo "<div align=\"center\"><h1>Save Failed!</h1></div>";
            }
            fclose($fp);
            }
// Automatically redirect to the main page.
echo "<meta http-equiv=\"REFRESH\" content=\"2;url=index.php\">";
?>


// Retrieve file's name 
$filename = $_GET['file'];

Get's the files name.

// Make sure the perms are still set.
chmod($filename, 0777);

Again makes sure the perms are set to prevent any access denied errors.

$loadcontent = $filename; 
$save_file = $_POST['save_file'];
$savecontent = $_POST['savecontent'];

Loads some of the variables from the POST. Remember, because we used POST to a file, and not php_self, we are using $_POST instead of $_GET.

// A little safety feature that replaces <? and ?>, thus, preventing your users from entering any php (if you don't allow it). Of course, if you don't want it, you can comment both lines out. 
$savecontent = str_replace("<?", "", $savecontent);

$savecontent = str_replace("?>", "", $savecontent);

Just something I threw in. I didn't want any of my users to start tinkering around with php, and end up wiping my whole server. Of course, you can ignore/delete these lines if you wish.

// And now we save the file using fopen and fwrite. Then display if the save was successful or a failure.
$savecontent = stripslashes($savecontent);
$l = "<br />";
        $fp = @fopen($loadcontent, "w");
        if ($fp) {
            if(fwrite($fp, $savecontent)){
            echo "<div align=\"center\"><h1>Save Successful!</h1></div>";
            }
            else{
            echo "<div align=\"center\"><h1>Save Failed!</h1></div>";
            }
            fclose($fp);
            }

And now we use fwrite and fopen to write the new data into the file. Then it will return if the save was successful or if it failed.

// Automatically redirect to the main page.
echo "<meta http-equiv=\"REFRESH\" content=\"2;url=index.php\">";
?>

And now we redirect to the home page. That 2 after content is how long it will take for the command to start. 2 = 2 seconds.



And that is the end of my very first tutorial. Please leave feedback.

Is This A Good Question/Topic? 0
  • +

Replies To: Advanced file editor.

#2 northern  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 19-March 11

Posted 20 March 2011 - 08:39 AM

First of all, this is a wonderful peace of work, and thank you for sharing it.
It would be nice if after editing the file we could put the permissions back, you know for safety reasons. :winkiss:
Now I worked off what you supplied and made it simple.

Just a thought though, and not meant to step on any ones toes... in the save.php file...

look for:

fclose($fp);


now add this just before it.

 // Make sure the perms are set back.
            chmod($filename, 0644);



so you should have something that looks like this.

// Make sure the perms are set back.
            chmod($filename, 0644);
            fclose($fp);


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1