I am trying to upload a file from my local server to the Paperless NGX API using PHP. The API requires a CSRF token and Basic Authentication for the POST request. However, I am having trouble obtaining the CSRF token and making the request successfully. Here is the code I have written so far:
- Getting the CSRF Token:
$apiUrl = 'http://hostname:8000/api/documents/post_document/';
$filePath = '/path/to/file.pdf';
$username = 'username';
$password = 'password';
function getCsrfToken($apiUrl, $username, $password) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$response = curl_exec($ch);
$headers = [];
$header_text = substr($response, 0, curl_getinfo($ch, CURLINFO_HEADER_SIZE));
foreach (explode("rn", $header_text) as $i => $line) {
if ($i === 0) {
$headers['http_code'] = $line;
} else {
list ($key, $value) = explode(': ', $line);
$headers[$key] = $value;
}
}
curl_close($ch);
return $headers['X-CSRFToken'] ?? null;
}
$csrfToken = getCsrfToken($apiUrl, $username, $password);
if (!$csrfToken) {
die('CSRF-Token could not be retrieved');
}
- Uploading the file:
$ch = curl_init();
$file = new CURLFile($filePath);
$postData = [
'document' => $file
];
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-CSRFToken: ' . $csrfToken,
'Content-Type: multipart/form-data'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 201) {
echo 'File uploaded successfully!';
} else {
echo 'Error uploading file: ' . $response;
}
}
uploadFile($apiUrl, $filePath, $csrfToken, $username, $password);
However, when I run this code, I receive a “405 Method Not Allowed” response when attempting to get the CSRF token. I suspect that the API URL I am using to get the CSRF token is incorrect, or the method I am using to retrieve it is not supported.
Could anyone provide guidance on how to properly retrieve the CSRF token and successfully upload a file to the Paperless NGX API with Basic Authentication in PHP?
Thank you!