Solved

PHP FTP Upload Help

Posted on 2014-09-23
20
273 Views
Last Modified: 2014-09-24
Hi,

I am trying to create a FTP upload option for a school that utilizes a hosted content managemnt site.  I tried using C# and that worked through visual studios utilizing inline coding but when I tried to use it on the CMS then it did not work.  The hosting site confirmed that they do not support custom C# pages.  So now I am trying to use PHP but for some reason my code just seems not to work outside of the CMS

The following is the PHP script that I would like to get working.  Right now it seems to do nothing at all:

<!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=utf-8" />
<title></title>
</head>
<body>
<?php
$ftp_server = "172.30.1.39";
$ftp_user_name = "user";
$ftp_user_pass = "password";
$destination_file = "/";
$source_file = $_FILES['file']['tmp_name']; 

// set up basic connection
$conn_id = ftp_connect($ftp_server);
ftp_pasv($conn_id, true); 

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); 

// 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, $destination_file, $source_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);
?>
<form action="" enctype="multipart/form-data" method="post">
<input name="file" type="file" />
<input name="submit" type="submit" value="Upload File" />
</form>


</body>
</html>

Open in new window

0
Comment
Question by:thomasm1948
  • 12
  • 5
  • 3
20 Comments
 
LVL 34

Expert Comment

by:gr8gonzo
ID: 40339301
The PHP installation might not have the FTP extension compiled in.

You can try using a pure-PHP version of FTP, like this:
http://www.phpclasses.org/package/1743-PHP-FTP-client-in-pure-PHP.html
0
 
LVL 34

Expert Comment

by:gr8gonzo
ID: 40339307
If you want, you can also do a quick check to confirm that that's the problem. Just create a new, empty script with these two lines:

<?php
echo (function_exists("ftp_connect") ? "FTP support exists!" : "FTP support does not exist!");
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40339366
I think you want to upload a file from a client machine to the server, is that right?
0
 

Author Comment

by:thomasm1948
ID: 40339588
that is correct.  We have an FTP site created and I am trying to see if this CMS will allow us to use PHP
0
 

Author Comment

by:thomasm1948
ID: 40339591
I can create a ASPX page in C# and everything works but the CMS will not let me upload C# code
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 40339617
What CMS is in play?

This script shows the standard design pattern for a single file upload.  There are some man page references in the comments, and you can look up the background documentation if you have any questions about why we do things this way.

<?php // demo/upload_single_example.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES YOU MUST UNDERSTAND TO UPLOAD FILES
// http://php.net/manual/en/reserved.variables.files.php
// http://php.net/manual/en/features.file-upload.php
// http://php.net/manual/en/features.file-upload.common-pitfalls.php
// http://php.net/manual/en/function.move-uploaded-file.php

// MANUAL PAGES THAT ARE IMPORTANT IF YOU ARE DEALING WITH LARGE FILES
// http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
// http://php.net/manual/en/ini.core.php#ini.post-max-size
// http://php.net/manual/en/info.configuration.php#ini.max-input-time


// PHP 5.1+  SEE http://php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8000000';

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE WANT (USE UPPERCASE ONLY)
$file_exts = array
( 'XLS'
, 'XLSX'
, 'PDF'
, 'JPG'
)
;
$f_exts = implode(', ', $file_exts);

// ESTABLISH THE NAME OF THE DESTINATION FOLDER
$my_dir = getcwd();

// OR USE THIS TO PUT UPLOADS IN A SEPARATE FOLDER
$my_dir = 'storage';
if (!is_dir($my_dir))
{
    mkdir($my_dir);
}

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;


// IF THERE IS INFORMATION POSTED
if (!empty($_POST))
{
    // IF THERE ARE ERRORS
    $error_code    = $_FILES["userfile"]["error"];
    if ($error_code)
    {
        trigger_error($errors[$error_code], E_USER_ERROR);
    }

    // GET THE FILE SIZE
    $fsize = number_format($_FILES["userfile"]["size"]);

    // SYNTHESIZE THE NEW FILE NAME FOR TEMPORARY STORAGE
    $fname = basename($_FILES['userfile']['name']);

    // FAIL IF THIS IS NOT AN ALLOWABLE EXTENSION
    $f_ext = explode('.', $fname);
    $f_ext = end($f_ext);
    $f_ext = strtoupper(trim($f_ext));
    if (!in_array($f_ext, $file_exts)) trigger_error("$f_ext NOT ALLOWED.  CHOOSE FROM $f_exts", E_USER_ERROR);

    // THE SERVER PATH TO THE FILE
    $my_path
    = getcwd()
    . DIRECTORY_SEPARATOR
    . $my_dir
    . DIRECTORY_SEPARATOR
    . $fname
    ;

    // THE URL PATH TO THE FILE
    $my_url
    = $my_dir
    . DIRECTORY_SEPARATOR
    . $fname
    ;

    // MESSAGES ABOUT THE UPLOAD STATUS, IF ANY
    $msg = NULL;

    // IF THE FILE IS NEW (DOES NOT EXIST)
    if (!file_exists($my_path))
    {
        // IF THE MOVE FUNCTION WORKED CORRECTLY
        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_path))
        {
            $upload_success = 1;
        }
        // IF THE MOVE FUNCTION FAILED IT PROBABLY THREW A MESSAGE
        else
        {
            $upload_success = -1;
            trigger_error("MOVE TO $my_path FAILED", E_USER_ERROR);
        }
    }

    // IF THE FILE ALREADY EXISTS
    else
    {
        $msg .= "<br/><b><i>$my_url</i></b> already exists" . PHP_EOL;

        // SHOULD WE OVERWRITE THE FILE? IF NOT
        if (empty($_POST["overwrite"]))
        {
            $upload_success = 0;
        }

        // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
        else
        {
            $now    = date('Y-m-d-His');
            $my_bak = $my_path . '.' . $now . '.bak';
            if (!copy($my_path, $my_bak))
            {
                $msg .= "<br/><strong>Attempted Backup Failed!</strong>" . PHP_EOL;
            }
            if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_path))
            {
                $upload_success = 2;
            }
            else
            {
                $upload_success = -1;
                trigger_error("MOVE TO $my_path FAILED", E_USER_ERROR);
            }
        }
    }

    // PREPARE A REPORT OF THE SCRIPT'S SUCCESS OR FAILURE
    if ($upload_success == 2) { $msg .= "<br/>A backup was made and the file was overwritten" . PHP_EOL; }
    if ($upload_success == 1) { $msg .= "<br/><strong>$my_url</strong> has been saved" . PHP_EOL; }
    if ($upload_success == 0) { $msg .= "<br/><strong>It was NOT overwritten.</strong>" . PHP_EOL; }
    if ($upload_success < 0)  { $msg .= "<br/><strong>ERROR: $my_url NOT SAVED - SEE WARNING FROM move_uploaded_file()</strong>" . PHP_EOL; }

    // ADD FILE SIZE AND PERMISSION INFORMATION
    if ($upload_success > 0)
    {
        $msg .= "<br/>$fsize bytes uploaded" . PHP_EOL;
        if (!chmod ($my_path, 0755))
        {
            $msg .= "<br/>chmod(0755) FAILED: fileperms() = ";
            $msg .= substr(sprintf('%o', fileperms($my_path)), -4);
        }
    }

    // SHOW THE SUCCESS OR FAILURE
    echo $msg;

    // SHOW A LINK TO THE FILE
    echo '<br/>'
    . '<a href="'
    . $my_url
    . '" target="_blank">'
    . "See: $my_url"
    . '</a>'
    ;
}


// CREATE THE FORM FOR INPUT (USING HEREDOC SYNTAX)
$form = <<<EOF
<h2>Upload a File</h2>
<p>
<form enctype="multipart/form-data" method="post">
<!--
    SOME IMPORTANT THINGS TO NOTE ABOUT THIS FORM...
    ENCTYPE= ATTRIBUTE IN THE HTML <FORM> TAG
    MAX_FILE_SIZE HIDDEN CONTROL MUST PRECEDE THE FILE INPUT CONTROLS
    INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN _FILES ARRAY
    ABSENCE OF ACTION= ATTRIBUTE IN <FORM> TAG CAUSES POST TO SAME URL
-->
<input type="hidden" name="MAX_FILE_SIZE" value="$max_file_size" />
Find a file to Upload ($f_exts): <input name="userfile" type="file" />
<br/>Check this box
<input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files
</br><input type="submit" value="Upload" />
</form>
</p>
EOF;

echo $form;

Open in new window

0
 

Author Comment

by:thomasm1948
ID: 40339680
we are using eschoolview
0
 
LVL 34

Expert Comment

by:gr8gonzo
ID: 40339755
Did you run the test I suggested?
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40339756
Have you asked their support what language their CMS is using?  I can't find that detail in their web site.
http://www.eschoolview.com/School-CMS-Support.aspx
0
 

Author Comment

by:thomasm1948
ID: 40339911
yes I asked, they suggested that I jus create my own upload page and then use JavaScript in their CMS to show the log in and upload information.
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 

Author Comment

by:thomasm1948
ID: 40339920
I just ran this code on my Linux server and I cannot connect to the ftp server

<!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=utf-8" />
<title>Simple FTP Upload Script using PHP by 2netlodge</title>
</head>

<body>
<?php
if(isset($_POST['ftp']))
       {
            $ftp = $_POST['ftp'];
            $username = $_POST['username'];
            $pwd = $_POST['pwd'];
            $filename = $_FILES['file']['name'];
            $tmp = $_FILES['file']['tmp_name'];
            $d = $_POST['des'];
            
            $connect = ftp_connect($ftp)or die("Unable to connect to host");
            ftp_login($connect,$username,$pwd)or die("Authorization Failed");
            echo "Connected!<br/>";                        
            
            if(!$filename)
                  {
                        echo"Please select a file";
                  }
            else
                  {
                        ftp_put($connect,$d.'/'.$filename,$tmp,FTP_ASCII)or die("Unable to upload");
                                    echo"File successfully uploaded to FTP";
                  }
      }
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="text" name="ftp" placeholder="FTP link"/><br/>
<input type="text" name="username" placeholder="Username"/><br/>
<input type="password" name="pwd" placeholder="Password"/><br/>
<input type="file" name="file" /><br/>
<input type="text" name="des" placeholder="Destination"  /><br/>
<br/><input type="submit" value="Upload"/></form>
<footer>Share and get more scripts and codes like this, visit <a href="http://2netlodge.com">http://2netlodge.com</a> Forum</footer>
</body>
</html>
0
 

Author Comment

by:thomasm1948
ID: 40339944
All what I really need is for the user to put a username and password in

I figure the code should be able to point to localhost or its own ip.  The FTP users that I created point to a shared home directory and they do not need to actually put a path in
0
 

Author Comment

by:thomasm1948
ID: 40340035
Just running some test and I cannot connect to the ftp server from PHP.  I can log in, if I go to ftp:// just fine.  I would do this in .NET but I already started everything in LINUX.  Please help

<?php
$un='Student';
$pw='Kilo1948';

// Connect to ftp
$conn_id = ftp_connect('localhost', 21);

// Open a session to an external ftp site
$login_result = ftp_login ($conn_id, $un, $pw);

// Check open
if (!$conn_id) {
    print "FTP connection failed!";
    exit();
}

if (!!$login_result) {
    print "FTP login failed!";
    exit();
 }
if (ftp_pasv($conn_id, true) == FALSE) {
    print "Passive FTP connection failed!";
    exit();


}

?>
0
 
LVL 34

Accepted Solution

by:
gr8gonzo earned 250 total points
ID: 40340140
Again, did you run the test I suggested to confirm that you have the FTP extension compiled into PHP on your server?
0
 

Author Comment

by:thomasm1948
ID: 40340268
I am not sure how to do that in centos

I ran setsebool httpd_can_network_connect=1 and now I get passed the connection error, but the login fails even though it is correct

How can I ensure on centos 6.5 that PHP has the ftp extensions.  I admit I just ran yum install php
0
 

Author Comment

by:thomasm1948
ID: 40340288
ok just ran yum install php-ftp and I got a message indicating that I am running the latest php common install
0
 

Author Comment

by:thomasm1948
ID: 40340316
I got it to work.
0
 
LVL 34

Expert Comment

by:gr8gonzo
ID: 40341674
Can you say how?
0
 

Author Comment

by:thomasm1948
ID: 40341725
When I removed PHP, the built in PHP on centos seemed to have worked.  There was some sort of confliction and I thought I had to install the PHP.  Weird....  I also entered this command

httpd_can_network_connect=1
0
 

Author Closing Comment

by:thomasm1948
ID: 40341730
Thank you for all for help
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Batch, VBS, and scripts in general are incredibly useful for repetitive tasks.  Some tasks can take a while to complete and it can be annoying to check back only to discover that your script finished 5 minutes ago.  Some scripts may complete nearly …
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

757 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

22 Experts available now in Live!

Get 1:1 Help Now