George Dimitriadis George Dimitriadis - 15 days ago 8
PHP Question

Google analytics upload file with cURL

I am trying to upload a .csv file to google analytics through php. Unfortunately, the google analytics API doesn't provide a way to save the filename, so I am trying to upload the file with cURL instead. I am stuck badly, mainly because I don't know how to properly translate a cURL command into php code.

This is the cURL command that uploads the file successfully, meaning it does exactly what I want, found here :

curl -X POST -F "upload=@YOURFILENAME.csv;type=application/octet-stream" "" -v

I have tried to translate the above command into PHP code in the following ways, but I am doing something wrong, because an invalid file is getting uploaded (probably an empty file ?).

Attempt 1:

$parameters = [
'upload' => '@/local/path/to/my/file/test2.csv;type=application/octet-stream',
$url = '' .
$account->code .
'/webproperties/' .
$property->code .
'/customDataSources/' .
$datasource->code .
'/uploads?access_token=' .
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($process, CURLOPT_HEADER, false);
curl_setopt($process, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_UPLOAD, true);
curl_setopt($process, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($process, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec($process);
$httpcode = curl_getinfo($process, CURLINFO_HTTP_CODE);
// Runs, but the upload is invalid.

Attempt 2

// Same as above, except the $parameters set like this
$parameters = [
'upload' => '@/local/path/to/my/file/test2.csv',
'type' => 'application/octet-stream',

Attempt 3

// Same as above, except the $parameters set like this
$cfile = new \CURLFile('/local/path/to/my/file/test2.csv','application/octet-stream','upload');
$parameters = [
'upload' => $cfile,
'type' => 'application/octet-stream',

I did many other attempts which I fail to even remember by now. I can't believe it's so hard to get it working when I already have the command that works and all I need is to translate it into code ... hope someone out there can help me, thanks a lot in advance !


In short, what I need to do is translate the following curl command into php code:

curl -X POST -F "upload=@YOURFILENAME.csv;type=application/octet-stream" ""


Well, after 2 weeks I was still unable to find a solution, so I ended up using exec. Yes yes I know I know, bad practice etc etc, but I am sticking with it until I find a way to do it properly.

Anyway, in case someone is as desperate for a solution as me, this is what I ended up with

$result = exec('curl -X POST -F "upload=@' . $fullPathToFile . ';type=application/octet-stream" "' . $url . '"', $output, $return_var);