PHP

Post data from Actionscript 3 to PHP

If you need to send some data to a PHP script and don’t want to use services like Zend_AMF you can try posting that data directly to the PHP script.
With the code bellow I’ll actually send an email.

// ActionScript 3 Code
// PostToPHP.as

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package
{
        import flash.events.Event;
    import flash.events.HTTPStatusEvent;
        import flash.net.URLLoader;
    import flash.net.URLLoaderDataFormat;
    import flash.net.URLRequest;
    import flash.net.URLRequestMethod;
    import flash.net.URLVariables;

    public class PostToPHP
    {
        // url to post
        private var postToURL:String = "http://www.yourdomain.tld/post_receiver.php";

        public function PostToPHP()
        {
            // create request
            var request:URLRequest = new URLRequest( postToURL );

        // set post variables
            var requestVars:URLVariables = new URLVariables();
            requestVars.emailTo      = 'email.address@mailservice.tld';
            requestVars.subject      = 'This is a test email';
            requestVars.message = 'An this is the content of the message.';
       
            // assign variables to the request and set request method type 
            request.data     = requestVars;
            request.method = URLRequestMethod.POST;
   
            // load the request and listen for a response from the PHP script
            var urlLoader:URLLoader = new URLLoader();
            urlLoader.dataFormat = "text";
            urlLoader.addEventListener(Event.COMPLETE, urlLoader_handler, false, 0, true);
            urlLoader.load(request);
    }
       
    private function urlLoader_handler(e:Object):void
    {
           // the response given from the PHP script will be traced here
       trace(e.target.data);
    }

// PHP code
// post_receiver.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// assign POST variables and clean them
// filter_var() is available from PHP 5.2.0
$emailTo    = filter_var($_POST['emailTo'], FILTER_SANITIZE_EMAIL);
$subject    = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$message   = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// send mail and remember function response
// boolean response
$mailSent = mail($emailTo, $subject, $message);

// the echoed response will be traced in actionscript
if($mailSent == true)
{
    echo 'mail sent';
}
else
{
    echo 'mail NOT sent';
}

Simple.

Popularity: 4% [?]

CKEditor 3.0 Send and Receive data with AJAX

Attention: This is a quick tutorial and no in depth information will be provided. Use Google or whatever you want to learn more about PHP, Javascript and AJAX calls. Also on the CKEditor site you can find more info about the editor itself.

The old FCKEditor is now called CKEditor 3.0 and it’s:

CKEditor is a text editor to be used inside web pages. It’s a WYSIWYG editor, which means that the text being edited on it looks as similar as possible to the results users have when publishing it. It brings to the web common editing features found on desktop editing applications like Microsoft Word and OpenOffice.

You can download it from here: http://ckeditor.com.

OK.. so I wanted to edit some HTML template files from an Admin area module and the new CKEditor looks pretty nice so I gave it a try.
First I install the CKEditor and this is pretty easy to do, just download the editor and copy the files to the server.

Create a link to the editor:

1
<script type="text/javascript" src="/ckeditor/ckeditor.js"></script>

and then creat a text field area:

1
<textarea name="template_body" id="template_body" >page content here</textarea>

and add the javascript code to load the editor:

1
2
3
<script type="text/javascript">
            CKEDITOR.replace( 'template_body' );
        </script>

I added also a div to hold the received messages from the AJAX calls:

1
<div id="saveButton" style="font-weight:bold"></div>

Then I generated a tree/file view of all the template files(for sake of simplicity I will not show you how to do that).
The links are generated like this:

1
<a href="" onclick="getFile('test.html'); return false;" id="file" >test.html</a>

The return false is so than I won’t need to use the stupid # on the href=”" so that the page won’t refresh.

And the two Javascript functions that make the Ajax calls are:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<script type="text/javascript">
function getFile(file)
{      
    var httpRequest = (!window.XMLHttpRequest)? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
    httpRequest.onreadystatechange = function()
    {
        if(httpRequest.readyState == 4)
        {
            // send info to editor
            CKEDITOR.instances.template_body.setData(httpRequest.responseText);
            document.getElementById('saveButton').innerHTML = '<a href="" onclick="saveFile(\'' + file + '\'); return false;" >SAVE TEMPLATE</a>';
        }
    }
    httpRequest.open("GET","/ajax/get_file.php?file="+file,true);
    httpRequest.send(null);      
}

function saveFile(filename)
{    
    // get info from editor
    var editordata = CKEDITOR.instances.template_body.getData();

    var httpRequest = (!window.XMLHttpRequest)? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
    httpRequest.onreadystatechange = function()
    {
        if(httpRequest.readyState == 4)
        {
            if(httpRequest.responseText == "success")
            {
                document.getElementById('saveButton').innerHTML = '<span style="color:red">Template saved</span>';
            }
            else
            {
                document.getElementById('saveButton').innerHTML = httpRequest.responseText;
            }
        }
    }
    var passingData = "file="+filename+"&template_body="+ escape(editordata)
    httpRequest.open("POST", "/ajax/save_file.php?"+passingData, true);
    httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");        
    httpRequest.send(passingData);
}
</script>

The first function getFile(), gets the name of the file to load and send the response text from the PHP script to the editor.
The PHP script gets the name of the file and with file_get_contents function I retrieve that template’s contents.

1
echo file_get_contents('/templates/'.$_GET['file']);

The editor shows the received data with the command:

1
CKEDITOR.instances.template_body.setData(httpRequest.responseText);

“template_body” is the name of the text field that is replaced by the CKEditor.
In this function I also add a new link to the page with innerHTML that makes the reference to the second function: saveFile().

The second function saveFile() get the current name of the loaded template (test.html for example) and saves the data from the editor to
a variable “editordata” with the call:

1
CKEDITOR.instances.template_body.getData();

The editor data is sent to the PHP script, escaped and urlencoded with POST.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// write content to file
$filename = '/templates/'.$_POST['file'];
$template_body = $_POST['template_body'];

if (is_writable($filename)) // check file first
{
    if (!$handle = fopen($filename, 'w'))  // open file
    {
         echo 'fail open';
    }

    if (fwrite($handle, $template_body) === FALSE) // write file
    {
        echo 'fail write';
    }

    fclose($handle); // and close the file
    echo 'success';
}
else
{
    echo 'fail not writable';
}

The PHP code is straight forward: open file, write contents to file, close file.
If success is returned then with innerHTML we write that the template was saved if not the specific fail message will be shown.
(usually those errors appear if the file is missing or the file path is wrong or the file permissions are wrong.)

So here you have it an browser based template editor.
Oh and if your template has

1
<html>, <body>

tags they will be deleted by the editor. Don’t know how to override that shit functionality.

Over and out.

Hey did you know about this?
wordpress themes, site templates

Popularity: 100% [?]