Elarcrex
Elarcrex

Reputation: 13

Make PHP code editable from within a textarea

I'm currently working on my custom CMS, and I want the administrator to be able to edit the php files and stylesheets in the public area. I have no problem getting to files, and have tried several ideas based on my findings as a result of Google-ing, and my, somewhat thorough, search of this site. Here's where I am so far:

Getting the files:

 <?php
    $dir = "./";
    function get_files($directory = "") {
    $dir = $directory;
    if(is_dir($dir)) {
            $dir_array = scandir($dir);
        $filtered = array();
        foreach($dir_array as $file) :
        if(stripos($file, '.') > 0)
                array_push($filtered, $file);
        endforeach;
        return $filtered;
    } else {
        //Do something else
           }
    }

Using jQuery to output the content of each file inside the textarea:

$(document).ready(function() {
    $('.file').each(function(){
    var file_link = this;
    var HTML_FILE_URL = './' + file_link.id;
    var file_id = file_link.id;
    $(file_link).bind('click', function(){
        $('#filename').text(" - " + file_id);
    $.get(HTML_FILE_URL, function(data){
                var htmlData = htmlEntities(data);
        $('textarea').text(htmlData);
        });
    });
    });
});


function htmlEntities(str) {
    //This is a function which I found on this site.
    //It gave me a good result on the html part
    //However, the PHP codes were already executed. 
}

I would very much appreciate it if any one could point me in the right direction. Is there any particular PHP method that I'm completely overlooking? Is there a solution I can refer to?

Thanks.

Upvotes: 1

Views: 115

Answers (1)

Steve
Steve

Reputation: 20469

You can not directly load the source code from php files via javascript - as you have found the php is always executed.

What you need to do is call a php script that will load and return the source code:

//getsource.php
$editable_files = array('edit1.php', 'mybooks.php');

if(isset($_GET['file']) && in_array($_GET['file'], $editable_files)){
    echo file_get_contents($_GET['file']);
}

Then you would call this file in your js.

As others have mentioned, this could open up a number of security vulnerabilities, but that is beyond the scope of this question

Upvotes: 1

Related Questions