Image corrupted after php curl transfer FTP

2019-05-16 11:25发布

I am using the following code to transfer an image and it is working except the jpg is corrupted after the transfer. Is says invalid image format and shows a blurred image.

I tried using regular php without curl and get the same results.

Does anyone know why whatever I try works but corrupts the image.jpg

$curl = curl_init();
$fh   = fopen("test.jpg", 'w');
curl_setopt($curl, CURLOPT_URL, "ftp://{$serverInfo['user']}: {$servererInfo['password']}@{$serverInfo['ftp1.server.com']}/{$serverInfo['For_Web/Web Images/Full Size/00-99/file']}");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
fwrite($fh, $result);
fclose($fh);
curl_close($curl);`

标签: php curl ftp
1条回答
相关推荐>>
2楼-- · 2019-05-16 12:03

There are a few problems;

You should open your file for writing in binary mode, that is;

$fh = fopen("test.jpg", 'wb');

curl_exec returns a bool (success), not the contents of the file, the file should instead be passed to CURLOPT_FILE.

You should set the username/password using CURLOPT_USERPWD, not sure if the URL way could be made to work too, though.

You should set CURLOPT_BINARYTRANSFER.

Working sample;

$curl = curl_init();
$fh = fopen("fips.exe", 'wb');
curl_setopt($curl, CURLOPT_URL, 'ftp://ftp.sunet.se/pub/FreeBSD/tools/fips.exe');
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FILE, $fh);
curl_setopt($curl, CURLOPT_USERPWD, 'anonymous:olle');
$result = curl_exec($curl);
fclose($fh);
curl_close($curl);
查看更多
登录 后发表回答