PHP Extension
PHP Extension
Upload a File to an AI Provider (OpenAI, Google, Antropic, X)
See more AI Examples
Uploads a file to an AI provider using the provider's File API and returns theid that can later be used to reference the file in an query. This currently works with ChatGPT, Gemini, Claude, and Grok.
Chilkat PHP Extension Downloads
<?php
include("chilkat.php");
$success = false;
$ai = new CkAi();
// The provider can be "openai", "google", "claude", "grok", or any AI that supports uploading files for later reference by ID.
$ai->put_Provider('openai');
// Use your provider's API key.
$ai->put_ApiKey('MY_API_KEY');
// We can upload directly from a file in the filesystem, or from a Chilkat StringBuilder, or from a Chilkat BinData.
// Some AI providers require a content-type.
// Also, some AI providers are picky about what content-type's are accepted.
// Check the AI provider's documentation.
// "application/json" is generally always acceptable.
// "text/plain" can be used as a fallback for any text file.
$contentType = 'application/json';
$localFilePath = 'qa_data/hamlet.json';
$filenameOnServer = 'hamlet.json';
// Upload directly from a file.
$file_id = $ai->uploadFile($localFilePath,$contentType);
if ($ai->get_LastMethodSuccess() == false) {
print $ai->lastErrorText() . "\n";
print 'AI File Upload Failed.' . "\n";
}
else {
print 'File ID: ' . $file_id . "\n";
print 'File uploaded.' . "\n";
}
// Upload from the contents of a StringBuilder
$sb = new CkStringBuilder();
$success = $sb->LoadFile($localFilePath,'utf-8');
if ($success == false) {
print $sb->lastErrorText() . "\n";
exit;
}
$file_id = $ai->uploadFileSb($sb,$filenameOnServer,$contentType);
if ($ai->get_LastMethodSuccess() == false) {
print $ai->lastErrorText() . "\n";
print 'AI File Upload Failed.' . "\n";
}
else {
print 'File ID: ' . $file_id . "\n";
print 'File uploaded.' . "\n";
}
// Upload from the contents of a BinData
$bd = new CkBinData();
$success = $bd->LoadFile($localFilePath);
if ($success == false) {
print $bd->lastErrorText() . "\n";
exit;
}
$file_id = $ai->uploadFileBd($bd,$filenameOnServer,$contentType);
if ($ai->get_LastMethodSuccess() == false) {
print $ai->lastErrorText() . "\n";
print 'AI File Upload Failed.' . "\n";
}
else {
print 'File ID: ' . $file_id . "\n";
print 'File uploaded.' . "\n";
}
?>