PHP.mk документација

ftp_get

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.ftp-get.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.ftp-get.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
ftp_get

Референца за `function.ftp-get.php` со подобрена типографија и навигација.

function.ftp-get.php

ftp_get

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_getПрезема датотека од FTP серверот

= NULL

ftp_get(
         FTP\Connection $ftp,
         string $local_filename,
         string $remote_filename,
         int $mode = FTP_BINARY,
         int $offset = 0
): bool

ftp_get() презема оддалечена датотека од FTP серверот и ја зачувува во локална датотека.

Параметри

ftp

Еден FTP\Connection instance.

local_filename

Локалната патека на датотеката (ќе биде препишана ако датотеката веќе постои).

remote_filename

ја зачувува локалната датотека на FTP-серверот.

mode

Патеката до локалната датотека. FTP_ASCII or FTP_BINARY.

offset

Позицијата во оддалечената датотека од која ќе започне преземањето.

Вратени вредности

Патеката до PHP скриптата што треба да се провери. true на успех или false при неуспех.

Дневник на промени

Верзија = NULL
8.1.0 На ftp параметарот очекува FTP\Connection инстанца сега; претходно, а resource се очекуваше.
7.3.0 На mode Позицијата во далечинската датотека за почеток на поставувањето.

Примери

Пример #1 ftp_get() example

<?php

// define some variables
$local_file = 'local.zip';
$server_file = 'server.zip';

// set up basic connection
$ftp = ftp_connect($ftp_server);

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

// try to download $server_file and save to $local_file
if (ftp_get($ftp, $local_file, $server_file, FTP_BINARY)) {
echo
"Successfully written to $local_file\n";
} else {
echo
"There was a problem\n";
}

// close the connection
ftp_close($ftp);

?>

Види Исто така

  • ftp_pasv() параметарот сега е опционален. Претходно беше задолжителен.
  • ftp_fget() - Презема датотека од FTP серверот и ја зачувува во отворена датотека
  • ftp_nb_get() - Презема датотека од FTP-серверот и ја запишува во локална датотека (неблокирачки)
  • ftp_nb_fget() - Презема датотека од FTP серверот и ја запишува во отворена датотека (неблокирачки)

Белешки од корисници 13 белешки

CuDi
пред 16 години
I tried to ftp a 7mb file today off my webserver.

I copied this example directly and it told me.

Port command successful
"there was a problem"

I thought it was because of the size.
But I guessed it might be cause of my firewall.

So I made the ftp connection passive:

<?PHP
  
  ...
  $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
  ftp_pasv($conn_id, true);

?>

Ran the script again & it worked fine.

Hope this helps someone
bob на notallhere точка com
12 години пред
Don't want to use an intermediate file?  Use 'php://output' as the filename and then capture the output using output buffering.

ob_start();
$result = ftp_get($ftp, "php://output", $file, FTP_BINARY);
$data = ob_get_contents();
ob_end_clean();

Don't forget to check $result to make sure there wasn't an error.  After that, manipulate the $data variable however you want.
ramiro на qusarcr точка com
пред 23 години
Keep in mind that ftp_get will overwrite the file on your local machine if it has the same name.
anomie на users точка sf точка net
19 години пред
Why there isn't an "ftp_get_contents" function, I don't know. It takes a little work to emulate one, but it's doable.
<?php
function ftp_get_contents($ftp_stream, $remote_file, $mode, $resume_pos=null){
    $pipes=stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
    if($pipes===false) return false;
    if(!stream_set_blocking($pipes[1], 0)){
        fclose($pipes[0]); fclose($pipes[1]);
        return false;
    }
    $fail=false;
    $data='';
    if(is_null($resume_pos)){
        $ret=ftp_nb_fget($ftp_stream, $pipes[0], $remote_file, $mode);
    } else {
        $ret=ftp_nb_fget($ftp_stream, $pipes[0], $remote_file, $mode, $resume_pos);
    }
    while($ret==FTP_MOREDATA){
        while(!$fail && !feof($pipes[1])){
            $r=fread($pipes[1], 8192);
            if($r==='') break;
            if($r===false){ $fail=true; break; }
            $data.=$r;
        }
        $ret=ftp_nb_continue($ftp_stream);
    }
    while(!$fail && !feof($pipes[1])){
        $r=fread($pipes[1], 8192);
        if($r==='') break;
        if($r===false){ $fail=true; break; }
        $data.=$r;
    }
    fclose($pipes[0]); fclose($pipes[1]);
    if($fail || $ret!=FTP_FINISHED) return false;
    return $data;
}
?>

Something similar would work to write a ftp_put_contents function, too.
Nate од ruggfamily точка com
пред 17 години
Here's a quick function that figures out the correct mode to use based on a file's extension.

<?php
function get_ftp_mode($file)
{    
    $path_parts = pathinfo($file);
    
    if (!isset($path_parts['extension'])) return FTP_BINARY;
    switch (strtolower($path_parts['extension'])) {
        case 'am':case 'asp':case 'bat':case 'c':case 'cfm':case 'cgi':case 'conf':
        case 'cpp':case 'css':case 'dhtml':case 'diz':case 'h':case 'hpp':case 'htm':
        case 'html':case 'in':case 'inc':case 'js':case 'm4':case 'mak':case 'nfs':
        case 'nsi':case 'pas':case 'patch':case 'php':case 'php3':case 'php4':case 'php5':
        case 'phtml':case 'pl':case 'po':case 'py':case 'qmail':case 'sh':case 'shtml':
        case 'sql':case 'tcl':case 'tpl':case 'txt':case 'vbs':case 'xml':case 'xrc':
            return FTP_ASCII;
    }
    return FTP_BINARY;
}

// sample usage
ftp_get($conn_id, $local_file, $server_file, get_ftp_mode($server_file));
?>
mroerick на gmx точка net
пред 16 години
ftp_sync is a way to walk the directory structure on the server and copy every directory and file to the same location locally.

<?php
$ftp_server = "ftp.example.com";
$conn_id = ftp_connect ($ftp_server)
    or die("Couldn't connect to $ftp_server"); 
    
$login_result = ftp_login($conn_id, "user", "pass");
if ((!$conn_id) || (!$login_result))
    die("FTP Connection Failed");

ftp_sync ("DirectoryToCopy");    // Use "." if you are in the current directory

ftp_close($conn_id);  

// ftp_sync - Copy directory and file structure
function ftp_sync ($dir) {

    global $conn_id;

    if ($dir != ".") {
        if (ftp_chdir($conn_id, $dir) == false) {
            echo ("Change Dir Failed: $dir<BR>\r\n");
            return;
        }
        if (!(is_dir($dir)))
            mkdir($dir);
        chdir ($dir);
    }

    $contents = ftp_nlist($conn_id, ".");
    foreach ($contents as $file) {
    
        if ($file == '.' || $file == '..')
            continue;
        
        if (@ftp_chdir($conn_id, $file)) {
            ftp_chdir ($conn_id, "..");
            ftp_sync ($file);
        }
        else
            ftp_get($conn_id, $file, $file, FTP_BINARY);
    }
        
    ftp_chdir ($conn_id, "..");
    chdir ("..");

}
?>
mpatnode на yahoo точка com
пред 7 години
Note that PHP still defaults to FTP active mode by default, which is almost never used anymore since the creation of firewalls.   Don't forget to add a ftp_pasv($conn, true) after your ftp_login.
Aditya P dot Bhatt (adityabhai на gmail точка com)
пред 17 години
<?php
                // define some variables
        $folder_path = "YOUR FOLDER PATH"; 
        $local_file = "LOCAL FILE PATH";
        $server_file = "SERVER FILE PATH";
        
        //-- Connection Settings
        $ftp_server = "IP ADDRESS"; // Address of FTP server.
        $ftp_user_name = "USERNAME"; // Username
        $ftp_user_pass = "PASSWORD"; // Password
        #$destination_file = "FILEPATH"; 
        
        // set up basic connection
        $conn_id = ftp_connect($ftp_server);
        
        // login with username and password
        $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
        
        // try to download $server_file and save to $local_file
        if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
            echo "Successfully written to $local_file\n";
        } else {
            echo "There was a problem\n";
        }
        
        // close the connection
        ftp_close($conn_id);
?>
anomie на users точка sf точка net
19 години пред
Crud. The _nb_ only refers to reading from the ftp server, and the buffer in the socket pair is only about 364 bytes. So it doesn't work for files larger than that size.
thivierr на telus точка net
пред 22 години
If you previously downloaded a file before (like a huge web log), and just want to get the remaining portion, do this:

$local_file_size = filesize($local_file_path);
$get_result = ftp_get($conn_id, $local_file_path, $remote_file_path, FTP_BINARY, $local_file_size);

This same code works regardless of wether the local file exists already or not.  You should first test to make sure the local file is not bigger than the remote file.
administrator на gesoft точка org
19 години пред
Hello everybody,

If someone will try to download files to the same local file (some temporary file), like shown here:

<?php
foreach ($files as $key=>$path) {
... 
  $result = ftp_get($ftpConnId, 'temp.tmp', $path, FTP_BINARY);
...
}
?>

please take in consideration the fact that you will have big problems with downloading (getting) hole files. In other words ‘temp.tmp’ file always will have the same size equal to first downloaded file despite the real size of downloading file. I have not idea what is the reason!

If someone will think that problem is just in getting proper file size (which you will get using filssize() function) he will be mistaken. The download file’s size is not equal to source file’s size materially, that means fflush() function will not solve the problem (I have tried this as well).

Finally the solution was founded: before downloading a file you will need to delete local file if such exist (‘temp.tmp’). So working code will look like:

<?php
foreach ($files as $key=>$path) {
... 
  if (file_exists('temp.tmp')) {
    unlink('temp.tmp');
  }
  $result = ftp_get($ftpConnId, 'temp.tmp', $path, FTP_BINARY);
...
}
?>

Good luck in scripting :-)

Vitali Simsive
miki на epoch точка co точка il
пред 13 години
If you ran the example and see that it fail after 90sec (timeout).

Then try adding:
<?php
ftp_pasv($ftp_conn, true);
?>
corey-holzer на nyc точка rr точка com
пред 22 години
The zero size file is not a side effect.  When the ftp_get starts the first thing it does is to create the inode/file which it will stream the data too and that is a zero size file with the nname you specified for the local file.  When the download fails it leaves the file in place.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.