Attaching files to Zendesk comments using SDK/API

In addition to generating comments and tickets through Zendesk API, we can also attach files to comments. The method is simple and straightforward.

You basically provide the uploaded file path and MIME type to upload method of the Attachments API and it will return an attachment token that will then be provided as a parameter to the create or update method of the Tickets API. Here is a bit of sample code:

$allowedFileTypes = array(‘images/jpeg’,’image/png’,’image/jpeg’,’image/gif’, ‘application/pdf’, ‘application/x-pdf’);

$path = str_replace(array(” “,”-“,”_”,”,”,”+”,”&”,”%”), “”, $_FILES[‘file’][‘name’]);
$type = $_FILES[‘file’][‘type’];

if(!in_array(strtolower($_FILES[‘file’][‘type’]), $allowedFileTypes)){

$fileError=true;
$FileError_msg = “Invalid file type! Only images and PDFs are allowed.”;

}else{
if(move_uploaded_file($_FILES[‘file’][‘tmp_name’], $path)){

try {

$att = $ZDESK::$_sdk->attachments()->upload(array(‘file’=>$path,’type’=>$type));

} catch (Exception $e) {

$fileError=true;
$FileError_msg = “Could not upload file! Please try again.”;

}

}else{

$fileError=true;
$FileError_msg = “Could not upload file! Please try again.”;

}
}

}

if($fileError==false){

$params = array (
‘subject’ => $subject,
‘comment’ => array (
‘body’ => $description,
‘author_id’ => $user,
‘uploads’ => array($att->upload->token)
),
‘priority’ => ‘normal’,
’email’ => $userdata [’email’],
‘group_id’ => $department,
‘custom_fields’ => array (
24318441 => $userdata [‘login’],
24318451 => $userdata [’email’],
24313942 => $userdata [‘firstname’] . ‘ ‘ . $userdata [‘lastname’]
),
‘type’ => $type,
‘submitter_id’=>$user,
‘requester_id’=>$user
);

$new_ticket = $ZDESK::saveTicket ($params);

@unlink($path);

}

alexey

alexey

Application developer, movie buff, occasional reader and a huge Manchester United fan.
alexey

Application developer, movie buff, occasional reader and a huge Manchester United fan.