Wednesday, February 2, 2022

[SOLVED] Transalte curl command to PHP

Issue

Hello I have this Linux command that downloads a compressed file

curl -L -O http://www.url.com

The problem is that when I do curl inside PHP I get the HTML code instead of the compressed file.

The PHP code is this:

$url = https://www.example.com
$filePath = '/app/storage/temp/' . $fileName;
$fp = fopen($filePath . 'me', "w");
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_FTPAPPEND, 0);
curl_setopt($ch, CURLOPT_FILE, $fp);

$data = curl_exec($ch);
fwrite($fp, $data);
curl_close($ch);
fclose($fp);

I can't share the real URL since it contains secret keys.

EDIT

The curl command downloaded the same HTML file as the curl command when I added the -L -O options to the curl command it started working, so the thing here is, how can I add those lines with PHP


Solution

Guys sorry for making this hard for you since I couldn't give much information about my doubt.

The problem is solved, I realized that the URL did work with

curl -O -L htttp://www.example.com

and also by the web browser.

This last thing was actually the one that gave me the path:

  1. Open the web browser
  2. Click F12
  3. Paste the URL and hit enter

I came to realize I needed to add some headers the headers were these:

accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8

accept-encoding:gzip, deflate, br

accept-language:en-US,en;q=0.8,es-MX;q=0.6,es;q=0.4

user-agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36

After I added these headers to the curl inside PHP the result was the compressed zip file I was searching for.



Answered By - Jesus Walker
Answer Checked By - Timothy Miller (WPSolving Admin)