Click here to Skip to main content
15,892,161 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
Hello Everyone, I’m having a page php have function list content of directory in computer such as c:/folder after that I can open, write and save any file I want in list file. Now I have complete to list content of directory, now I want to click any file in list file of derectory to open in a textarea under list content of drictory to view and edit file, then I have a button submit to save it. I don’t know how to do it so please fix my code I give under introduce me some example demo code or document to reference. Please help me. Thank very much.
Here is my code:
https://www.mediafire.com/?19123qkmgmf7toj
Example picture about page equivalent and similar:
In this picture it have list file.
http://i1095.photobucket.com/albums/i472/OLAKEN91/f1_zpsd8327c90.jpg

Now we can click to open 1 file such as “extensions.conf” to read, write and save it by button submit (update)
http://i1095.photobucket.com/albums/i472/OLAKEN91/f2_zpsf48caae7.jpg




EDIT: code originally entered by Emily Alice as a solution. - enhflep

HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<style type="text/css">
	table
	{
		width: 100%;
		padding: 5px 5px 0px 5px;
		text-decoration:none;
	}
	a
	{
		text-decoration:none;
	}
	h3
	{
		padding: 5px 0px 5px 0px;
		color:#000;
	}
	tr
	{
		height: 20px;
	}
</style>
</head>
 
<body>
<!--code show file cua thu muc-->
		echo "<h3>LIST FILE OF FOLDER</h3>";
		// directory
		$dir = "";
		
        // Opens directory
        $myDirectory=opendir(".");
        
        // Gets each entry
        while($entryName=readdir($myDirectory))
		{
			$dirArray[]=$entryName;
        }
		
		// Finds extensions of files
        function findexts ($filename) 
		{
			$filename=strtolower($filename);//chuyen sang chu thuong
          	$exts=split("[/\\.]", $filename);//cat chuoi
          	$n=count($exts)-1;
          	$exts=$exts[$n];
          	return $exts;
		}
		 
		// Closes directory
        closedir($myDirectory);
        
        // Counts elements in array
        $indexCount=count($dirArray);
        
        // Sorts files
        sort($dirArray);
        
		// Print list content directory
		print("<table border="1" cellpadding="5" cellspacing="0" class="whitelinks">\n");
		print("<tr><th>Name</th><th>Type</th><th>Size</th><th>Date Modified</th></tr>\n");
		// Loops through the array of files
        for($index=0; $index < $indexCount; $index++)
		{
			if (substr("$dirArray[$index]", 0, 1) != ".")
			{		
				//File name
				$name=$dirArray[$index];
				$namehref=$dirArray[$index];
				
				// Gets File Extensions 
          		$extn=findexts($dirArray[$index]);
				
				// File type
				switch ($extn)
				{
					case "png": $extn="PNG Image"; break;
					case "jpg": $extn="JPEG Image"; break;
					case "bmp": $extn="BITMAP Image"; break;
					case "gif": $extn="GIF Image"; break;
					case "ico": $extn="Windows Icon"; break;
					case "txt": $extn="Text File"; break;
					case "log": $extn="Log File"; break;
					case "htm": $extn="HTML File"; break;
					case "php": $extn="PHP Script"; break;
					case "js": $extn="Javascript"; break;
					case "css": $extn="Stylesheet"; break;
					case "pdf": $extn="PDF Document"; break;
					case "zip": $extn="ZIP Archive"; break;
					case "docx": $extn="Microsoft Word Document"; break;
					case "mp3": $extn="MP# Format Sound"; break;
					default: $extn=strtoupper($extn)." File"; break;
          		}
          
          		// Gets file size 
          		$size=number_format(filesize($dirArray[$index]))." "."KB";
          
          		// Gets Date Modified Data
          		$modtime=date("M j Y g:i A", filemtime($dirArray[$index]));
          		$timekey=date("YmdHis", filemtime($dirArray[$index]));
				
				print("
          		<tr>
            	<td><a href="./$namehref">$name</a></td>
            	<td><a href="./$namehref">$extn</a></td>
           	 	<td><a href="./$namehref">$size</a></td>
            	<td sorttable_customkey="$timekey"><a href="./$namehref">$modtime</a></td>
          		</tr>");
				/*print("<tr><td><a href="\"$dirArray[$index]\"">$dirArray[$index]</a></td>");
				print("<td>");
				print(findexts($dirArray[$index]));
				//print(filetype($dirArray[$index]));
				print("</td>");
				print("<td>");
				print(filesize($dirArray[$index]));
				print("</td>");
				print("<td>");
				print($modtime);
				print("</td>");				
				print("</tr>\n");*/
			}
		}
		print("</table>\n");
?>
<!--code doc sua va luu 1 file bat ky-->
		<br />
		<h3>OPEN, EDIT AND SAVE ANY FILE IN LIST FILE OF FOLDER</h3>
		<br />
        <form name="read_form" method="post" action="">
        <textarea name="read_file" cols="110" rows="35" wrap="off">
        </textarea>
        <br />
        <input type="submit" name="update" value="UPDATE" />
        </form>
</body>
</html>
Posted
Updated 28-Aug-17 8:13am
v3
Comments
enhzflep 7-Dec-13 12:59pm    
That's my 1 vote. I'd be happy to (and would like to) improve it if the question was edited in a way that warranted it.

1) You ask for people to fix your code, before asking for a demo or a document. You don't give me the impression of being interested in how it works, merely the solution. I'm often wrong.
2) The code you've uploaded is a 1.1 MB rar file. That's just crazy. It's really quite a simple task. There is absolutely no need for such a large dump of code for this task.
3) You haven't even said where you're stuck, what you've done. Do you really expect people to go through your zip file just to try to deduce what problem you're having?
4) Relating to (3) - Theres 1.1MB of images and 25kb of code, in addition to 275kb of un-minimized jQuery o_O

You should construct the minimal example to demonstrate the problem you're having and ask questions that relate to that.

An alternative may be to describe what you understand to be the rough steps need to accomplish this task, along with the step(s) you're having trouble with.

Look, we were all new to this gig once, but your current approach is better suited to a different site than this one.

Of course, you could just send $50 to my paypal and I will do 60 minutes of detective-work on your uploaded .rar file - you could then ignore points 1 - 4 of this comment.

EDIT: See here for suggestions on how to make posts more likely to be solved for you by others: Short, Self Contained, Correct (Compilable), Example
Sergey Alexandrovich Kryukov 8-Dec-13 1:58am    
Great reply. And excellent, most useful link.
—SA
enhzflep 8-Dec-13 5:36am    
Thank-you and you're most welcome. :)

Practise makes perfect - it's ever-so hard to practise an unknown process. That link must've helped 100s of thousands over the past decade.

S.
enhzflep 8-Dec-13 19:23pm    
A couple of quick points Emily Alice:
1) In future, you should edit your original question to provide updates - do NOT add updates as a 'Solution'
2) You should definitely NOT mark such a 'solution' as 'accepted' (or whatever the word is) This causes your problem to appear as solved, which it clearly isn't.
3) Please, delete your 'solution' - I've updated your original post to include the code.

Oh.My.Goodness!

I don't really know where to begin with this solution. There are so many issues with the code. But, we don't learn unless we try. I reckon effort has been shown and should be rewarded with some advice that hopefully should help in the future.

First, a couple of points that need pointing out.

1. While they may seem the same at first glance, PHP treats single quotes (') and double quotes (") quite differently. If a string is wrapped in double quotes, variable names are substituted with the value that the variable holds. In the event that the string contains quotes, you may either escape the quotes by preceding them with a back-slash or by using the other sort of quote. E.g $someVar = "This is 'easy'."; or $someVar = 'This is \'easy\'.';

echo '$someVar' will produce a very different result to echo "$someVar";
The first one will show $someVar, while the second will show This is 'easy'.

- I made changes that takes these rules into account on lines 64 & 65, also 108-111 of your code

2. You seem to have forgotten the opening tag for the php code
- I added it to line 31 of your code


3. All of the TD cells in your table were links - probably not really the best way to do it. I've removed the link from the type, size and modified columns. I've also made the name column _appear_ to be a link, through the use of css. This is done because otherwise, you will actually navigate away from your editor and end up setting the filename to the address-bar of the browser.
Again, not really what you want. - I've added the css rules .fileLink and .fileLink:hover to manage the first column

4. I've left your file-type code as-is. You may wish to change this further - you probably don't want the user to click on a PNG file, only to have its contents appear in the text-area. You can solve that as required.

5. I've added 2 spans above the text area for the purpose of holding the name of the file currently being edited.

6. I've added some javascript to handle mouse clicks on the name of files in the table. This will use ajax to request the contents of the chosen file, paste it into the text-area, set the fileName indicator to the name of the file that was clicked and finally, set the page's scroll position to the fileName indicator, ready for editing.

7a. I haven't bothered at all with the UPDATE button, you'll need to tackle that problem yourself. It is a perfect opportunity to become more familiar with either an ordinary POST-based form submission or an AJAX-based one. It's up to you to decide. You will also need to send the name of the file that is being transmitted in order to save (update) it on the server. You could do that with an input element with the type set to hidden, which was inside the form. I've put one in the appropriate spot and commented it out.

7b. You'll need to have something to submit the updated data and the filename to. Just make another PHP file that saves the data recieved via $_POST to the file specified by the hidden input.

Anyway, you can read more on the xmlHTTPRequest object here: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp[^]

Finally, the code. Please ask questions if you have them. Questions that seek understanding on how to create a solution - requests for the solution will not be welcomed by me.

HTML
<!DOCTYPE html>
<head>
<style>
table
{
    width: 100%;
    padding: 5px 5px 0px 5px;
    text-decoration:none;
}

a
{
    text-decoration:none;
}

h3
{
    padding: 5px 0px 5px 0px;
    color:#000;
}

tr
{
    height: 20px;
}

/*
    make elements with this class appear like a link
    we need to request the filename that these elements contain with ajax, so we _dont_ want a real link.
*/
.fileLink
{
    color: blue;
    cursor: pointer;
}

.fileLink:hover
{
    text-decoration: underline;
}

/* rule for the name of the file currently being edited */
#editingFilename
{
    color: #f90;   /* CP-orange text */
    font-weight: bold;
}
</style>

<script>

function requestUrlWithAjax(url)
{
    var xmlhttp;

    //1. create the xmlhttp object

    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    //2. assign the handler for the onchange event of the object
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            // we arrive here when we have successfully retrieved  the url we asked for
            //1. Set the response text to the text area's value
            document.getElementById('ajaxResultTarget').value = xmlhttp.responseText;

            //2. copy the name of the file retrieved directly above the text-area
            document.getElementById('editingFilename').innerHTML = url;

            //3. set the filename to the hidden input - see line 199
//          document.getElementById('frmFileName').value = url;


            //4. scroll the document down to editingFilename - just above the text-area
            var xPos, yPos, tgtElem;
            tgtElem = document.getElementById('editingFilename');
            xPos = 0;
            yPos = tgtElem.offsetTop;
            window.scrollTo(xPos, yPos);
        }
    }

    //3. specify a GET request for the indicated filename,
    //   set asynchronous to true (dont wait for the send method to complete before continuing)
    xmlhttp.open("GET",url,true);

    //4. make the request
    xmlhttp.send();
}

</script>


</head>

<body>
<!--code show file cua thu muc-->

        <?php echo "<h3>LIST FILE OF FOLDER</h3>";
        // directory
        $dir = "";

        // Opens directory
        $myDirectory=opendir(".");

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

        // Finds extensions of files
        function findexts ($filename)
        {
            $filename=strtolower($filename);//chuyen sang chu thuong
            $exts=split("[/\\.]", $filename);//cat chuoi
            $n=count($exts)-1;
            $exts=$exts[$n];
            return $exts;
        }

        // Closes directory
        closedir($myDirectory);

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

        // Sorts files
        sort($dirArray);

        // Print list content directory
        print("<table border='1' cellpadding='5' cellspacing='0' class='whitelinks'>\n");
        print("<tr><th>Name</th><th>Type</th><th>Size</th><th>Date Modified</th></tr>\n");
        // Loops through the array of files
        for($index=0; $index < $indexCount; $index++)
        {
            if (substr("$dirArray[$index]", 0, 1) != ".")
            {
                //File name
                $name=$dirArray[$index];
                $namehref=$dirArray[$index];

                // Gets File Extensions
                $extn=findexts($dirArray[$index]);

                // File type
                switch ($extn)
                {
                    case "png": $extn="PNG Image"; break;
                    case "jpg": $extn="JPEG Image"; break;
                    case "bmp": $extn="BITMAP Image"; break;
                    case "gif": $extn="GIF Image"; break;
                    case "ico": $extn="Windows Icon"; break;
                    case "txt": $extn="Text File"; break;
                    case "log": $extn="Log File"; break;
                    case "htm": $extn="HTML File"; break;
                    case "php": $extn="PHP Script"; break;
                    case "js": $extn="Javascript"; break;
                    case "css": $extn="Stylesheet"; break;
                    case "pdf": $extn="PDF Document"; break;
                    case "zip": $extn="ZIP Archive"; break;
                    case "docx": $extn="Microsoft Word Document"; break;
                    case "mp3": $extn="MP# Format Sound"; break;
                    default: $extn=strtoupper($extn)." File"; break;
                }

                // Gets file size
                $size=number_format(filesize($dirArray[$index]))."&nbsp"."KB";

                // Gets Date Modified Data
                $modtime=date("M j Y g:i A", filemtime($dirArray[$index]));
                $timekey=date("YmdHis", filemtime($dirArray[$index]));

                print("
                <tr>
                <td class='fileLink' onclick='requestUrlWithAjax(this.innerHTML)'>$name</td>
                <td>$extn</td>
                <td>$size</td>
                <td>$modtime</td>
                </tr>");
            }
        }
        print("</table>\n");
?>
        <br />
        <h3>OPEN, EDIT AND SAVE ANY FILE IN LIST FILE OF FOLDER</h3>
        <span>Current File: </span><span id='editingFilename'></span><br>
        <form name="read_form" method="post" action="">
<!--        <input type='hidden' name='fileName' id='frmFileName'/> -->
        <textarea id='ajaxResultTarget' name="read_file" cols="110" rows="35" wrap="off">
        </textarea>
        <br />
        <input type="submit" name="update" value="UPDATE" />
        </form>
</body>
</html>
 
Share this answer
 
v2
Good debugging. But you code is unable to open folders. It only opens files.
 
Share this answer
 
Comments
Richard Deeming 29-Aug-17 13:27pm    
If you want to reply to a solution, use the "Have a Question or Comment?" button under that solution.

DO NOT post your comment as a new "solution"!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900