Search Flex Components Free

Custom Search

December 29, 2007

File Uploads with PHP and Flex

Structure
The PHP scripts used in our Flex applications for file uploads are semi-modular. They are based on switch statements which evaluate the variable "request." We found this to be a simple and effective way to manage communication between the Flex application and the server. For example, if we had a "user.php" page, and wanted to add a new user to our database, we would make a "case 'add'" in our switch statement, and inserted the code for processing a database request.
Feedback
We also soon found that it was important to have good communication between Flex and the server so we could prevent and debug errors efficiently. We did this by creating a function that ran at the end of every page to construct an XML that contained the feedback for Flex. The XML structure was very generic, including a tag which containted a boolean value, followed by data or, in the case of false in the success tag, nodes with specific errors to report.
Example
Here's an example PHP that could be used in the Flex application to upload a file:

<?php

$errors = array();
$data = "";
$success = "false";

function return_result($success,$errors,$data) {
echo("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
?>
<results>
<success><?=$success;?></success>
<?=$data;?>
<?=echo_errors($errors);?>
</results>
<?
}

function echo_errors($errors) {

for($i=0;$i<count($errors);$i++) {
?>
<error><?=$errors[$i];?></error>
<?
}

}

switch($_REQUEST['action']) {

case "upload":

$file_temp = $_FILES['file']['tmp_name'];
$file_name = $_FILES['file']['name'];

$file_path = $_SERVER['DOCUMENT_ROOT']."/myFileDir";

//checks for duplicate files
if(!file_exists($file_path."/".$file_name)) {

//complete upload
$filestatus = move_uploaded_file($file_temp,$file_path."/".$file_name);

if(!$filestatus) {
$success = "false";
array_push($errors,"Upload failed. Please try again.");
}

}
else {
$success = "false";
array_push($errors,"File already exists on server.");
}

break;

default:
$success = "false";
array_push($errors,"No action was requested.");

}

return_result($success,$errors,$data);

?>

Related Flex Tutorials