How to convert blob to file and send with CURL

Hello, i m trying to send file with curl but before sending i need to take it from mysql blob. File is not been sent correctly :frowning:

//FILE
$query= mysqli_query($conn, "SELECT name, type, size, content FROM files WHERE id='".intval($id)."'");

list($name, $type, $size, $content) = mysqli_fetch_array($query);
$name=html_entity_decode($name, ENT_NOQUOTES, 'UTF-8');
header("Content-length: $content");
header('Content-type: $type');
header("Content-Disposition: inline;filename=$name");
 

//CURL
$url = 'https://www.someurl.com';
$user = 'username';
$pass = 'password';

$post = array('file'=> '@'.$content);
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_USERPWD, $user.":".$pass);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


$response = curl_exec($ch); 
curl_close($ch);

What em i missing ?Why file is not sent? BTW connection works.

The @ notation is for when you have an actual file. You have a string with the contents of a file, so you should write $contents to a file and then use that filename with @ notation:

//Save string into temp file
$file = tempnam(sys_get_temp_dir(), 'POST');
file_put_contents($file, $content);

$post = array(
    'file' => '@'.$file,
);

And then once uploading is done you can remove the temporary file:

@unlink($file);

Also, in the Content-Length header you should use strlen($content), not $content

1 Like

Thanks for answer! It makes wrong format: i tried to print_r $post and got Array ( [file] => @C:\Windows\Temp\POS3B38.tmp )

That is correct. That is the file where your contents are in. Curl will open that file, read the contents, and send it.

I can only pass PDF and JSON so i get “wrong file format” on return message. What can i do here?

use a PDF or JSON file.

I do that. It just pass that POS3B38.tmp i think.

Is there a way to put temporary files on C:/xampp/htdocs/somefolder/myfile.pdf ? not on C:\Windows\Temp\POS3B38.tmp? I m 100% sure i m sending PDF

You could do that manually for testing, just write it into that file (considering virtual path vs. absolute path) instead of using tmpname() to get the filename. Obviously if it works you have to consider multiple users and so on.

I was reading elsewhere that you should specify “pdf” rather than “file” in your $post array, but I haven’t used CURL myself so it may not be relevant.

At the end i did like this:

file_put_contents($_SERVER["DOCUMENT_ROOT"].'/temporary/'.$name, $content);

$file_name_with_full_path = realpath($_SERVER["DOCUMENT_ROOT"].'/temporary/'.$name);
$post = array('file'=> '@'.$file_name_with_full_path);

Thanks everyone that tried to help :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.