Connect to FTP with PHP with a password that has @

2019-02-20 04:21发布

I have the following problem:

I need connect to FTP and read one CSV file. The main problem it's password has @, $, %... How can I connect with especials characters? I tried the following ways to connect:

FILE OPEN

$filename = 'ftp://user:p@s($word@ftp.myftp.url/file.csv'; 
$handle = fopen($filename, "r") or die("Error");

FTP LOGIN

$ftp_server = "ftp.myftp.url/file.csv";
$ftp_user = "user";
$ftp_pass = "p@s($word";
$conn_id = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login_result = ftp_login($ftp_server, $ftp_user, $ftp_pass) or die("Could not connect to 2");
$data = file_get_contents('ftp.myftp.url/file.csv');

Thanks for all!

2条回答
干净又极端
2楼-- · 2019-02-20 04:57

You should replace hexadecimal value for @(at) char. Try this,

@ -> %40, $ -> %24

$ftp_pass = "p%40s(%24word";

查看更多
Luminary・发光体
3楼-- · 2019-02-20 05:14

You have two distinct problems with your two pieces of code.


FILE OPEN

$filename = 'ftp://user:p@s($word@ftp.myftp.url/file.csv'; 
$handle = fopen($filename, "r") or die("Error"); 

Here, the problem is the @, as you have correctly guessed, as it has a meaning in the URL syntax (as a separator between credentials and hostname).

You have to URL-encode the @ to %40:

$filename = 'ftp://user:p%40s($word@ftp.myftp.url/file.csv'; 

You mentioned that the actual password also has %. That has to be URL-encoded to %25.


FTP LOGIN

$ftp_server = "ftp.myftp.url/file.csv";
$ftp_user = "user";
$ftp_pass = "p@s($word";
$conn_id = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login_result = ftp_login($ftp_server, $ftp_user, $ftp_pass) or die("Could not connect to 2");

Here, the problem is not @, as no URL is involved (neither % would be a problem). Here, the problem is the $, as you are using double-quotes, so $word is replaced with a value of (probably undefined) variable word, effectively making the password be p@s( only.

Use single quotes to avoid the $ being interpreted as a variable:

 $ftp_pass = 'p@s($word';

Or escape the $ with \:

 $ftp_pass = "p@s(\$word";
查看更多
登录 后发表回答