Uploading files via REST API using PHP

I’m trying to upload a file using the REST API with PHP. I created a simple web form to upload a file, and when submit it I get “RT/4.4.4 200 Ok # Correspondence added”, and the ticket is uploaded with the corresponded text, but the attachment isn’t in the ticket.

Below is the code I’m using.

<?php $url = "http://".$url ."/REST/1.0/ticket/".$ticket_num ."/comment?user=$username&pass=$password"; $attachment_1 = curl_file_create($_FILES["file"]["tmp_name"], $_FILES["file"]["type"], $_FILES["file"]["name"]); $fields = [ "content" => "id: ".$ticket_num ."\nAction: correspond\nText: test attachment\nAttachment:" .$_FILES["file"]["name"], "attachment_1" => $attachment_1 ]; $fields_string = http_build_query($fields); $ch = curl_init(); $fp = fopen($_FILES["file"]["tmp_name"], 'r'); curl_setopt($ch, CURLOPT_USERPWD, $username .":".$password); curl_setopt($ch, CURLOPT_INFILE, $fp); curl_setopt($ch, CURLOPT_INFILESIZE, filesize($_FILES["file"]["tmp_name"])); curl_setopt($ch, CURLOPT_INFILE, $fp); curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'CURL_callback'); curl_setopt($ch, CURLOPT_BUFFERSIZE, 128); curl_setopt($ch,CURLOPT_URL, $url); curl_setopt($ch,CURLOPT_POST, count($fields)); curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string); curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); $post_result = curl_exec($ch); echo $post_result; ?>

I couldn’t figure out how to format the code so here’s a screenshot of it.

This works for me using Curl:

curl --form 'content=Queue: General
Requestor: root@localhost
content: Some content
Action: correspond
Attachment: test.txt
Text: Required text field: req' --form 'attachment_1=@test.txt' 'http://SOME RT URL/REST/1.0/ticket/3/comment?user=root&pass=password'

Generating PHP from Postman using the Curl example I get:

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://SOME RT/REST/1.0/ticket/3/comment?user=root&pass=password",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_POSTFIELDS => array('content' => 'Queue: General
Requestor: root@localhost
content: Some content
Action: correspond
Attachment: test.txt
Text: Required text field: req','attachment_1' => '@test.txt'),
  CURLOPT_HTTPHEADER => array(
    "Cookie: RT_SID_The%20SOME RT=123"
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

I don’t know if that PHP will work though as it was just generated by Postman

The CURL example works, so I’ll just wrap that in PHP. Thanks.