1 Reply Latest reply on May 15, 2008 2:14 PM by tam2000k2

    Flex FTP and PHP

    tam2000k2
      Hi Everyone,

      As you can see by the title, I'm trying to use Flex to upload a file, followed by having PHP FTP the file to the server.

      I have been successful at having PHP move the file once Flex uploads it, but that is using http and the client wants this to be strictly ftp:

      Here's the Flex code:
      [code]
      <?xml version="1.0" encoding="utf-8"?>
      <mx:Application xmlns:mx=" http://www.adobe.com/2006/mxml" layout="absolute" backgroundAlpha="0.0" backgroundColor="0x000000" backgroundGradientColors="[#000000, #000000]" borderThickness="0" height="220" width="616" paddingTop="0" paddingBottom="0" paddingLeft="0" paddingRight="0" verticalAlign="top">
      <fab:FABridge bridgeName="fab" id="fab" xmlns:fab="bridge.*" />
      <mx:Script>
      <![CDATA[
      import flash.net.URLRequest;
      import flash.net.URLLoader;

      private var file:FileReference = new FileReference();
      private function init():void
      {
      file.addEventListener(Event.SELECT, selectHandler);
      }

      private function selectHandler(event:Event):void
      {

      }

      private function browse(event:MouseEvent):void
      {
      var filefilter:FileFilter = new FileFilter("Video Files", "*.mov;*.m2v;*.mp4;*.m4v;*.wmv;*.avi;*.swf;");
      file.addEventListener(Event.SELECT, fileSelected);
      file.addEventListener(Event.COMPLETE, uploadComplete);
      file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadDataComplete);
      file.addEventListener(IOErrorEvent.IO_ERROR, handleError);
      file.browse([filefilter]);
      }

      public function handleError(event:IOErrorEvent):void
      {
      status_txt.text = 'ERROR: ' + event.text + '\n';
      }
      public function fileSelected(event:Event):void
      {
      if (event.currentTarget.size<15800000)
      {
      _progressbar.visible=true;
      file = FileReference(event.target);
      txt_file.text = file.name;
      status_txt.text = file.name + ' is uploading. \n';
      file.addEventListener(ProgressEvent.PROGRESS, progressHandler);
      var Form:URLVariables = new URLVariables();
      var request:URLRequest = new URLRequest();
      Form.txt_file = txt_file.text;
      request.data = Form;
      request.url = 'ftp_test3.php';
      file.upload(request);

      }
      else
      {
      mx.controls.Alert.show('Max File Size is: 15MB','File Too Large',4,null).clipContent
      }
      }

      public function uploadComplete(event:Event):void
      {
      status_txt.text += 'Upload complete' + '\n';
      _progressbar.label = '';
      _progressbar.visible=false;
      }

      private function progressbarInit():void
      {
      _progressbar.visible=false;
      }

      private function progressHandler(event:ProgressEvent):void
      {
      _progressbar.setProgress(50,100);
      _progressbar.label = 'Uploading ' + Math.round(event.bytesLoaded / 1024) + ' kb of ' + Math.round(event.bytesTotal / 1024) + ' kb ' ;
      }

      public function uploadDataComplete(event:DataEvent):void
      {
      // used to send message via Javascript to let me know that it actually completed
      ExternalInterface.call('sendRequestPost_video', '3');
      }
      ]]>
      </mx:Script>


      <mx:Panel backgroundColor="0x000000" color="0xFFFFFF" borderThickness="0" paddingTop="0" paddingBottom="0" paddingLeft="0" paddingRight="0" height="220" width="614">
      <mx:Form>
      <mx:TextInput id='txt_file' horizontalCenter='0' top='0' color="0x000000" width="100" />
      <mx:Button id="browse_button" label="Upload Video" click="browse(event);" width="100" />
      <mx:ProgressBar id='_progressbar' labelPlacement='center' trackHeight='15' left='-2' right='2' top='60' height='20' color="0x000000" width="300" />
      </mx:Form>
      <mx:Label id="status_txt" color="0xFFFFFF" width="589" height="50" fontSize="16" />
      </mx:Panel>
      <mx:HTTPService id="userRequest" url="ftp_test3.php" method="POST">
      <mx:request>
      <txt_file>txt_file.text</txt_file>
      </mx:request>
      </mx:HTTPService>
      </mx:Application>
      [/code]

      And here's the PHP code that moves the file, which is successful:
      [code]
      <?php

      $upload_dir = $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']) . '/'."movies/";
      $upload_url = " http://".$_SERVER['HTTP_HOST' . '/';
      $message ="";
      $temp_name = $_FILES['Filedata']['tmp_name'];
      $file_name = $_FILES['Filedata']['name'];
      $file_name = str_replace("\\","",$file_name);
      $file_name = str_replace("'","",$file_name);
      $file_path = $upload_dir.$file_name;
      $result = move_uploaded_file($temp_name, $file_path);
      chmod("movies/".$file_name, 0777);
      chown("movies/".$file_name, www);
      if ($result)
      {
      $message = "<result><status>OK</status><message>$file_name uploaded successfully.</message></result>";
      }
      else
      {
      $message = "<result><status>Error</status><message>Somthing is wrong with uploading a file.</message></result>";
      }
      echo $message;
      ?>
      [/code]

      The above code works fine, but it's not FTP.

      So, I use the same concept but with ftp, which BTW, the below FTP PHP scripts works on it's own to upload a file via FTP. It appears as though Flex is not communicating with the PHP file.

      [code]
      <?php
      //-- SMTP Mail Function By Aditya Bhatt
      if(isset($_POST['SubmitFile'])){
      $myFile = $_FILES['txt_file']['tmp_name']; // This will make an array out of the file information that was stored.
      $myFileName = basename($_FILES['txt_file']['name']); //Retrieve filename out of file path
      $destination_file = $_REQUEST['filepath'].$myFileName;
      #"/developers/uploadftp/aditya/".$myFileName; //where you want to throw the file on the webserver (relative to your login dir)
      // connection settings
      $ftp_server = 'someIPnumber'; //address of ftp server.
      $ftp_user_name = 'username'; // Username
      $ftp_user_pass = 'password'; // Password

      $conn_id = ftp_connect($ftp_server) or die("<span style='color:#FF0000'><h2>Couldn't connect to $ftp_server</h2></span>"); // set up basic connection
      #print_r($conn_id);
      $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass) or die("<span style='color:#FF0000'><h2>You do not have access to this ftp server!</h2></span>"); // login with username and password, or give invalid user message
      if ((!$conn_id) || (!$login_result)) { // check connection
      echo "<span style='color:#FF0000'><h2>FTP connection has failed! <br />";
      echo "Attempted to connect to $ftp_server for user $ftp_user_name</h2></span>";
      exit;
      } else {
      // echo "Connected to $ftp_server, for user $ftp_user_name <br />";
      }
      $upload = ftp_put($conn_id, $destination_file, $myFile, FTP_BINARY); // upload the file
      if (!$upload) { // check upload status
      echo "<span style='color:#FF0000'><h2>FTP upload of $myFileName has failed!</h2></span> <br />";
      } else {
      echo "<span style='color:#339900'><h2>Uploading $myFileName Completed Successfully!</h2></span><br /><br />";
      }
      ftp_close($conn_id); // close the FTP stream
      }
      ?>
      <html>
      <head></head>
      <body>
      <form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST" id="myForm">
      Please choose a file: <input name="txt_file" type="file" id="txt_file" tabindex="1" size="35" onChange="txt_fileName.value=txt_file.value" /><br><br>
      <input name="txt_fileName" type="hidden" id="txt_fileName" tabindex="99" size="1" />

      <input type="submit" name="SubmitFile" value="Upload File" accesskey="ENTER" tabindex="2" />
      </form>
      </body>
      </html>
      [/code]

      THanks in advance and if there are any articles or tutorials for this concept, let me know -- I have read the chapter in the source book, but it sends the uploaded file to a cfm page and I need it to work with PHP.
        • 1. Re: Flex FTP and PHP
          tam2000k2 Level 1
          I found the issue and corrected it:
          I had to remove the "if the form was submitted conditional"
          [code]
          if(isset($_POST['SubmitFile'])){
          [/code]
          Because the php form would never be submitted via Flex

          and I changed the following code from txt_file to Filedata
          [code]
          $myFile = $_FILES['txt_file']['tmp_name

          $myFile = $_FILES['Filedata']['tmp_name']; // This will make an array out of the file information that was stored.
          // $file = $myFile['tmp_name']; //Converts the array into a new string containing the path name on the server where your file is.

          $myFileName = basename($_FILES['Filedata']['name']); //Retrieve filename out of file path
          [/code]

          THe only thing that I have to figure out now, is that the files are being uploaded to the root directory of the user logging in, but other than that, it works :-)