# allow_url_include の設定で ftp_connect()エラー

4 月 18 日に ftp 環境に繋げてファイル投げる PHP を作りました。
ローカル環境でテストして問題がないので、テストサーバーにテストしてみました。
けど、何故か ftp_connect()エラーが出ました。

# ftp_connect

非常にシンプルで FTP 接続をオープンするための関数

対応バージョン(PHP 4, PHP 5, PHP 7)

説明

ftp_connect ( string $host [, int $port = 21 [, int $timeout = 90 ]] ) : resource

戻り値
成功した場合に FTP ストリームを、エラー時に FALSE を返します。

# ローカル環境

ローカル環境では connect してログインも投げるのも全部できたのに、テストサーバー持っていくと接続 connect すら通らないことに。
いろんなファイルを絡んで作ってたので、最初はファイルやデータやプログラムがローカルと違うのではないかと考え、ローカルのデータを全てテストサーバーに持っていって書き換えました。
だが、結果は残念。
何も解決しないまま、頭を抱えて 2 時間はまりました。

# まさか PHP 7のせい?

もしかしたら、PHP に何か問題があるじゃないかと思い、PHPinfo を確認したら、テストサーバーが PHP バージョン7でローカルが5でした。
まさか、PHP 7から ftp_connect()サポート終了?と思いながら、調べたら問題が全くありません。
しかも、「PHP 7 ftp_connect() 接続できない」とグーグル先生に聞いても全くヒットしないことがわかりました。

# 復活は、php.ini の設定にあり

そこから、ftp_connect()がつながらないことをずーと調べましたが、あまり変な気配がなく時間だけ過ぎていきます。
とりあえず、PHP.ini を変えようと思って allow_url_fopen は元々 On なので、allow_url_include を Off から On に変更して httpd   restart しました。

結果:復活

# allow_url_include って

デフォルトは"0" になっていますが、このオプションを指定すると include, include_once, require, require_once で URL 対応の fopen ラッパーが使用できるようになります。

# PHP で FTP ファイルアップロード・ダウロード

2015 年の古い記事になりますが、シンプルでわかりやすいので、参考に[PHP] FTP でのアップ/ダウンロード (opens new window)

# アップロード

$ftpValue = array(
    'ftp_server' => FTP_ADDRESS,
    'ftp_user_name' => FTP_USER,
    'ftp_user_pass' => FTP_PASS
);
$remote_file = REMOTE_FILE_NAME;
$upload_file = LOCAL_FILE_NAME;

$connection = ftp_connect($ftpValue['ftp_server']);

$login_result = ftp_login(
    $connection,
    $ftpValue['ftp_user_name'],
    $ftpValue['ftp_user_pass']
);

ftp_pasv($connection, true);
$ftpResult = ftp_put($connection, $remote_file, $upload_file, FTP_BINARY, false);

if (!$ftpResult) {
    throw new InternalErrorException('Something went wrong.');
}

ftp_close($connection);

# ダウンロード

$ftpValue = array(
    'ftp_server' => FTP_ADDRESS,
    'ftp_user_name' => FTP_USER,
    'ftp_user_pass' => FTP_PASS
);
$remote_file = REMOTE_FILE_NAME;
$download_file = LOCAL_FILE_NAME;

$connection = ftp_connect($ftpValue['ftp_server']);

$login_result = ftp_login(
    $connection,
    $ftpValue['ftp_user_name'],
    $ftpValue['ftp_user_pass']
);

//リモートでのファイル存在チェック
if(ftp_size($connection, REMOTE_FILE_NAME)){
    ftp_pasv($connection, true);
    $ftpResult = ftp_get($connection, $download_file, $remote_file, FTP_BINARY, false);
}

if (!$ftpResult) {
    throw new InternalErrorException('Something went wrong.');
}

ftp_close($connection);

# 備考

2017-04-19

同じタグを持つ記事をピックアップしました。