April 13, 2016

PHP file upload to slack

So I don’t know why this one took me this long to find, but I spent a long time today trying to figure out why my PHP script wasn’t uploading my file I wanted to slack. I had the string to send to slack correct, but every time I tried I was getting a no_file_content error.

I was using the, apparently now, old method of referencing a file for POST-back. That is $file = '@/path/to/file.png'

Here is the new method, in case any one else had as much trouble as I did finding it $file = new CurlFile('filename.png', 'image/png');

Here is the PHP wiki article on the “new” method

And here it is, in action

<?php
$slacktoken = "longthingwithlotsofletters";
$header = array();
$header[] = 'Content-Type: multipart/form-data';
$file = new CurlFile('/home/john/myphoto.jpg', 'image/jpg');

$postitems =  array(
    'token' => $slacktoken,
    'file' =>  $file,
    'text' => "This is my photo",
    'title' => "Why this?",
    'filename' => "my-photo.jpg"
);
    
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_URL, "https://slack.com/api/files.upload");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS,$postitems);

//Execute curl and store in variable
$data = curl_exec($curl);
?>

Yay now I can upload files from PHP