Connect to FTP with PHP with a password that has @

非 Y 不嫁゛ 提交于 2019-12-01 11:52:54

问题


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!


回答1:


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";



回答2:


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

@ -> %40, $ -> %24

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



来源:https://stackoverflow.com/questions/47157363/connect-to-ftp-with-php-with-a-password-that-has

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!