Solved

PHP FTP upload Via HTML form

Posted on 2004-04-16
4
2,225 Views
Last Modified: 2010-05-18
   I am developing a html form that will POST to an PHP module that plugs into my PHP based CMS (http://www.drupal.org) and upload a specified file from a local computer to a remote FTP server. I have spent all afternoon piecing together information and I have sucessfully uploaded a file using a stand alone version of the php script where I have pluged in the filename manually. This is the main problem I am trying to tackle:

    I can't seem to get the ftp_put command to recognize the data from the variable I am trying to pass to it. I think that this may be because when the client browses to the file on their local computer, the information that is passed through to the ftp_put contains their local path. I would think that this path would need to be omited when specifying the destination path on the ftp server. The problems is, I don't know for sure - and although I have tried - I don't know how to fix it.

    Ultimately I will be modifying a php form_mail module that works with my CMS to work as the FTP upload interface. The code that I have included does not include any of the form_mail code, which in and of itself is relatively redundant because all of the action happens once the ftp code is executed.

The following section of this question will contain two sections of code, firstly the HTML form that i am POSTing with and secondly the PHP script that i am working with to upload files from various client sources (for the most part straight from php.net:

The Form:

<form action="form_mail" method="post" enctype="multipart/form-data">
<br>
<p>Instructions:<br>
  1. Left-Click Browse.<br>
  2. In the dialog that opens, please browse to your zipped batch, select it, and click open.<br>
  3. Left-Click Upload.<br>
</p>
<input type=file name=source_file size=20>
<br>
<input type="submit" class="form-submit" name="op" value="Send" />


The PHP:

<?php
// set up basic connection
$conn_id = ftp_connect("10.10.10.2");
$ftp_user_name = "xxxxxx";
$ftp_server = "xxx";
$s_file = $_POST['source_file'];
$d_file = $_POST['source_file'];

// login with username and password
$login_result = ftp_login($conn_id, "xxxxxx", "xxxxxxx");

// check connection
if ((!$conn_id) || (!$login_result)) {
       echo "FTP connection has failed!";
       echo "Attempted to connect to $ftp_server for user $ftp_user_name";
       exit;
   } else {
       echo "Connected to $ftp_server, for user $ftp_user_name";
   }

// upload the file
$upload = ftp_put($conn_id, $d_file, $s_file, FTP_BINARY);

// check upload status
if (!$upload) {
       echo "FTP upload has failed!";
   } else {
       echo "Uploaded $source_file to $ftp_server as $destination_file";
   }

// close the FTP stream
ftp_close($conn_id);
?>

Thank you for your kind consideration!

Sadian
0
Comment
Question by:sadian
  • 3
4 Comments
 
LVL 5

Accepted Solution

by:
TheClickMaster earned 500 total points
ID: 10847836
After the file is uploaded to your webserver, its path & name will be in the variable

$_FILES['userfile']['tmp_name'];

therefore try to change it to

$s_file = $_FILES['userfile']['tmp_name'];
$d_file = $_FILES['userfile']['tmp_name'];


Also, you can check the size, and encoding type of the uploaded file with:

$_FILES['userfile']['size']
$_FILES['userfile']['type']

You can use this to validate the file. If no file is uploaded, $_FILES['userfile']['size'] will be 0 and $_FILES['userfile']['tmp_name'] will be empty.

Additionnal stuff:

The original name (on the users machine) is in
$_FILES['userfile']['name']

And if there were errors you have

$_FILES['userfile']['error']

which will contain an error code. (Have a look at this page to see the possible error codes: http://www.zend.com/manual/features.file-upload.errors.php )

Also might have a look at http://www.zend.com/manual/features.file-upload.php

Hope this helps

-TCM-
0
 
LVL 5

Expert Comment

by:TheClickMaster
ID: 10847856
After re-reading it you might want to change $s_file to something else depending on how you want it to name the files on the FTP server.

Should they keep the same name? If so try:

$s_file = substr($_FILES['userfile']['tmp_name'],strrpos($_FILES['userfile']['tmp_name'],"/");

Of course this always depends on the directory strucutre of the FTP server maybe you have to put it inside a specific directory...
0
 
LVL 5

Expert Comment

by:TheClickMaster
ID: 10847861
And that code was mising a closing paranthesis =)

s_file = substr($_FILES['userfile']['tmp_name'],strrpos($_FILES['userfile']['tmp_name'],"/"));
0
 
LVL 2

Author Comment

by:sadian
ID: 10878805
First, TCM - your awesome - keep up the great work.

I ended up dropping the idea of utilizing FTP to transfer the files. This is considering that the server is in our local office and the added expense of a professional level FTP server (considering we are hosting with w2k & apache2 (cause IIS doesn't support mod_rewrite.)) I decided to go with a solution that utilizes HTTP uploads. The final code itself contains alot of html but here is the basic code I built my my page upon:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
      <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
      <title>Upload a File</title>
</head>
<body>
<?php // upload_file.php
// This script displays and handles an HTML form.
// This script takes a file upload and stores it on the server.

// Address error handing.
ini_set ('display_errors', 1);
error_reporting (E_ALL & ~E_NOTICE);

if (isset ($_POST['submit'])) { // Handle form.

      // Try to move the uploaded file.
      if (move_uploaded_file ($_FILES['thefile']['tmp_name'], "../uploads/{$_FILES['thefile']['name']}")) {
      
            print '<p>Your file has been uploaded.</p>';
            
      } else { // Problem!
      
            print '<p>Your file could not be uploaded because: <b>';
            
            // Print a message based upon the error.
            switch ($_FILES['thefile']['error']) {
                  case 1:
                        print 'The file exceeds the upload_max_filesize setting in php.ini';
                        break;
                  case 2:
                        print 'The file exceeds the MAX_FILE_SIZE setting in the HTML form';
                        break;
                  case 3:
                        print 'The file was only partially uploaded';
                        break;
                  case 4:
                        print 'No file was uploaded';
                        break;
            }
            print '</b>.</p>';
      }
      
} // End of SUBMIT IF.

// Leave PHP and display the form.
?>

<form action="upload_file.php" enctype="multipart/form-data" method="post">
<p>Upload a file using this form: <br /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" name="thefile" /><br /><br />
<input type="submit" name="submit" value="Upload This File" />
</p>
</form>
</body>
</html>
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now