PHP Implementation ftp Upload File Example

  • 2021-07-16 01:58:21
  • OfStack

FTP uploading is a common and very important application skill of PHP implementation. Today, I will share with you a simple example of PHP implementing FTP uploading files. I hope to help you learn PHP.

The main code is as follows:


function make_directory($ftp_stream, $dir){
  // if directory already exists or can be immediately created return true
  if ($this->ftp_is_dir($ftp_stream, $dir) || @ftp_mkdir($ftp_stream, $dir)) return true;
  // otherwise recursively try to make the directory
  if (!$this->make_directory($ftp_stream, dirname($dir))) return false;
  // final step to create the directory
  return ftp_mkdir($ftp_stream, $dir);
}
 
function ftp_is_dir($ftp_stream, $dir){
  // get current directory
  $original_directory = ftp_pwd($ftp_stream);
  // test if you can change directory to $dir
  // suppress errors in case $dir is not a file or not a directory
  if ( @ftp_chdir( $ftp_stream, $dir ) ) {
    // If it is a directory, then change the directory back to the original directory
    ftp_chdir( $ftp_stream, $original_directory );
    return true;
  } else {
    return false;
  }
}

$conn = ftp_connect("ftp Address ") or die("Could not connect");
ftp_login($conn,"ftpname","password");
// Utilization ftp Create Directory 
make_directory($conn,$path);
// Utilization ftp Select Enter Directory 
ftp_chdir($conn,$path);
// Start uploading 
if(ftp_put($conn,$info[0]['savename'],getcwd().$upload->savePath.$info[0]['savename'],FTP_BINARY)){
 unlink(getcwd().$upload->savePath.$info[0]['savename']);
}
ftp_close($conn);
// Pay attention to the upload side ftp Permission setting 

Interested friends can test and run or rewrite the code described in this article, which can make the code function more perfect while deepening understanding.


Related articles: