I am trying to upload mp3 files to Amazon S3 but for some reason anything I upload is uploaded with a byte length of zero. I cannot seem to figure out why this is happening. I've tried following a tutorial and adjusting the code myself. Any help is appreciated.
<?php
error_reporting(0);
require '../../../../includes/aws-sdk-php/vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
if (isset($_GET['test'])){
if($_GET['test'] == "true"){
include("../../depend.php");
include("../../../../includes/okta-jwt/okta-jwt-functions.php");
include("../../../../includes/aws-s3/functions.php");
$jwtToken = $_GET['token'];
$validateJWT = validateJWT($jwtToken);
echo "$validateJWT";
die();
}
}
include("../../depend.php");
include("../../../../includes/okta-jwt/okta-jwt-functions.php");
if(isset($_POST['episodeTitle'])){
$episodeTitle = $_POST['episodeTitle'];
}
if(isset($_POST['episodeDescription'])){
$episodeDescription = $_POST['episodeDescription'];
}
if(isset($_POST['explicitContent'])){
$explicitContent = $_POST['explicitContent'];
}
if(isset($_POST['episodeShowID'])){
$episodeShowID = $_POST['episodeShowID'];
}
if(isset($_POST['jwtToken'])){
$jwtToken = $_POST['jwtToken'];
}
if(isset($_POST['audioFile'])){
$episodeAudio = $_POST['audioFile'];
}
$validateJWT = validateJWT($jwtToken);
$payloadJSON = json_decode($validateJWT);
$payloadDecoded = $payloadJSON;
$payloadUserID = $payloadDecoded->userID;
//Check if JWT Token Is Valid
if($payloadUserID != 0){
$payloadUserOrgID = $payloadDecoded->userOrgID;
$payloadRole = $payloadDecoded->role;
$payloadExp = $payloadDecoded->exp;
$payloadState = $payloadDecoded->state;
$payloadFirstName = $payloadDecoded->firstName;
$payloadLastName = $payloadDecoded->lastName;
$payloadFullName = $payloadDecoded->fullName;
$episodeStateCode = bin2hex(random_bytes(25));
date_default_timezone_set('UTC');
$showUtcTimestamp = date("Y-m-d H:i:s");
// AWS Info
$bucketName = 'XXX';
$IAM_KEY = 'XXX';
$IAM_SECRET = 'XXX';
// Connect to AWS
try {
// You may need to change the region. It will say in the URL when the bucket is open
// and on creation.
$s3 = S3Client::factory(
array(
'credentials' => array(
'key' => $IAM_KEY,
'secret' => $IAM_SECRET
),
'version' => 'latest',
'region' => 'us-east-2'
)
);
} catch (Exception $e) {
// We use a die, so if this fails. It stops here. Typically this is a REST call so this would
// return a json object.
die("Error: " . $e->getMessage());
}
// $keyName = "test_example/" . basename($_FILES["audioFile"]['name']);
// $keyName = "org-$payloadUserOrgID/$episodeStateCode-" . basename($_FILES["audioFile"]['name']);
$keyName = "org-$payloadUserOrgID/$episodeStateCode.mp3";
$pathInS3 = 'https://s3.us-east-2.amazonaws.com/' . $bucketName . '/' . $keyName;
// Add it to S3
try {
// Uploaded:
$file = $_FILES["audioFile"]['tmp_file'];
$s3->putObject(
array(
'Bucket'=>$bucketName,
'Key' => $keyName,
'SourceFile' => $file,
'StorageClass' => 'STANDARD'
)
);
} catch (S3Exception $e) {
die('Error:' . $e->getMessage());
} catch (Exception $e) {
die('Error:' . $e->getMessage());
}
echo 'Done';
}
?>
I can confirm that the file is being uploaded to S3 but the data in the file is not there. Any help in this would be very much appreciated.
I try to send attachment pdf file. I get the email but no attachmetn.
I have try to use https://github.com/sendinblue/APIv3-php-library/blob/master/docs/Model/SendSmtpEmail.mdenter
$sendSmtpEmail = new \SendinBlue\Client\Model\SendSmtpEmail();
$sendSmtpEmail['to'] = array(array('email'=>'email#email.com'));
$sendSmtpEmail['templateId'] = 39;
$sendSmtpEmail['params'] = array(
'NUMEROFACTURE'=> "12345",
'CODECLIENT' => "1234567",
'TOSEND' => "email1#email.net",
'MONTANTFACTURE'=> number_format(12, 2, ',', ' '),
);
$attachement = new \SendinBlue\Client\Model\SendSmtpEmailAttachment();
$attachement['url']= __DIR__'/facture/Facture-'.$row["ClePiece"].'.pdf';
$attachement['name']= 'Facture-'.$row["ClePiece"].'.pdf';
$attachement['content']= "utf-8";
$sendSmtpEmail['attachment']= $attachement;
$sendSmtpEmail['headers'] = array('Content-Type'=>'application/pdf','Content-Disposition'=>'attachment','filename'=>'Facture-'.$row["ClePiece"].'.pdf',"charset"=>"utf-8");
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'YOUR_API_KEY');
$apiInstance = new SendinBlue\Client\Api\SMTPApi(new GuzzleHttp\Client(),$config);
try {
$result = $apiInstance->sendTransacEmail($sendSmtpEmail);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling SMTPApi->sendTransacEmail: ', $e->getMessage(), PHP_EOL;
}
According to the SendSmtpEmailAttachment documentation, you have two ways to attach a file using a url or a content.
url | Absolute url of the attachment (no local file).
content | Base64 encoded chunk data of the attachment generated on the fly
You are wrongly assigning "utf-8" to the content. This mean you need to convert the pdf data into a base64 chunk data. First, get the pdf path in your server as $pdfdocPath. Get the pdf content using file_get_contents method and encode it using base64_encode method. Finally, split the content in small chunks using chunk_split as shown in the next snippet:
$sendSmtpEmail = new \SendinBlue\Client\Model\SendSmtpEmail();
$sendSmtpEmail['to'] = array(array('email'=>'email#email.com'));
$sendSmtpEmail['templateId'] = 39;
$sendSmtpEmail['params'] = array(
'NUMEROFACTURE'=> "12345",
'CODECLIENT' => "1234567",
'TOSEND' => "email1#email.net",
'MONTANTFACTURE'=> number_format(12, 2, ',', ' '),
);
$pdfdocPath = __DIR__.'/facture/Facture-'.$row["ClePiece"].'.pdf';
$b64Doc = chunk_split(base64_encode(file_get_contents($pdfdocPath)));
$attachement = new \SendinBlue\Client\Model\SendSmtpEmailAttachment();
$attachement['name']= 'Facture-'.$row["ClePiece"].'.pdf';
$attachement['content']= $b64Doc;
$sendSmtpEmail['attachment']= $attachement;
$sendSmtpEmail['headers'] = array('Content-Type'=>'application/pdf','Content-Disposition'=>'attachment','filename'=>'Facture-'.$row["ClePiece"].'.pdf',"charset"=>"utf-8");
Update:
I checked the APIv3-php-library source code and I found that the constructor will do the validation of name and content.
$dataEmail = new \SendinBlue\Client\Model\SendEmail();
$dataEmail['emailTo'] = ['abc#example.com', 'asd#example.com'];
// PDF wrapper
$pdfDocPath = __DIR__.'/facture/Facture-'.$row["ClePiece"].'.pdf';
$content = chunk_split(base64_encode(file_get_contents($pdfDocPath)));
// Ends pdf wrapper
$attachment_item = array(
'name'=>'Facture-'.$row["ClePiece"].'.pdf',
'content'=>$content
);
$attachment_list = array($attachment_item);
// Ends pdf wrapper
$dataEmail['attachment'] = $attachment_list;
$templateId = 39;
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'YOUR_API_KEY');
$apiInstance = new SendinBlue\Client\Api\SMTPApi(new GuzzleHttp\Client(),$config);
try {
$result = $apiInstance->sendTemplate($templateId, $dataEmail);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling SMTPApi->sendTemplate: ', $e->getMessage(), PHP_EOL;
}
$dataEmail= new \SendinBlue\Client\Model\SendEmail();
$dataEmail['emailTo'] = ['abc#example.com', 'asd#example.com'];
$dataEmail['attachmentUrl'] = "http://www.ac-grenoble.fr/ia07/spip/IMG/pdf/tutoriel_pdf_creator-2.pdf";
// if you want to use content attachment base64
// $b64Doc = chunk_split(base64_encode($data));
// $attachment_array = array(array(
// 'content'=>$b64Doc,
// 'name'=>'Facture-'.$row["ClePiece"].'.pdf'
// ));
// $dataEmail['attachment'] = $attachment_array;
//Don't forget to delete attachmentUrl
$templateId = 39;
$dataEmail = $dataEmail;
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'YOUR_API_KEY');
$apiInstance = new SendinBlue\Client\Api\SMTPApi(new GuzzleHttp\Client(),$config);
try {
$result = $apiInstance->sendTemplate($templateId, $dataEmail);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling SMTPApi->sendTemplate: ', $e->getMessage(), PHP_EOL;
}
According to the documentaiton SMTPApi->sendTransacEmail function gets SendSmtpEmail object. That object has restrictions for the attachment attribute:
If templateId is passed and is in New Template Language format then only attachment url is accepted. If template is in Old template Language format, then attachment is ignored.
But SMTPApi->sendTemplate function don't have this restriction.
$credentials = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'YOUR-KEY');
$apiInstance = new SendinBlue\Client\Api\TransactionalEmailsApi(new GuzzleHttp\Client(),$credentials);
$sendSmtpEmail = new \SendinBlue\Client\Model\SendSmtpEmail([
'subject' => 'test email!',
'sender' => ['name' => 'from name', 'email' => 'from#mail.com'],
//'replyTo' => ['name' => 'test', 'email' => 'noreply#example.com'],
'to' => [[ 'name' => 'Tushar Aher', 'email' => 'receivedto#gmail.com']],
'htmlContent' => '<html><body><h1>This is a transactional email {{params.bodyMessage}}</h1></body></html>',
'params' => ['bodyMessage' => 'this is a test!']
]);
/*$attachement = new \SendinBlue\Client\Model\SendSmtpEmailAttachment();
$attachement['url']= FCPATH.'uploads/invoice/ticket-498410.pdf';
$attachement['name']= 'ticket-498410.pdf';
$attachement['content']= "utf-8";
$sendSmtpEmail['attachment']= $attachement;*/
// PDF wrapper
$pdfDocPath = FCPATH.'uploads/invoice/ticket-498410.pdf';
$content = chunk_split(base64_encode(file_get_contents($pdfDocPath)));
// Ends pdf wrapper
$attachment_item = array(
'name'=>'ticket-498410.pdf',
'content'=>$content
);
$attachment_list = array($attachment_item);
// Ends pdf wrapper
$sendSmtpEmail['attachment'] = $attachment_list;
try {
$result = $apiInstance->sendTransacEmail($sendSmtpEmail);
print_r($result);
} catch (Exception $e) {
echo $e->getMessage(),PHP_EOL;
}
After everything was created in Google Cloud below code was written to upload images from my server to google cloud but i am getting error with google storage class
My upload_gcs.php code below
require 'vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Core\Exception\GoogleException;
if (isset($_FILES) && $_FILES['file']['error']== 0) {
$allowed = array ('png', 'jpg', 'gif', 'jpeg');
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array(strtolower ($ext), $allowed)) {
echo 'The file is not an image.';
die;
}
$projectId = 'photo-upload-205311';
$storage = new StorageClient ([
'projectId' => $projectId,
'keyFilePath' => 'Photo Upload-3af18f61531c.json'
]);
$bucketName = 'photo-upload-205311.appspot.com';
$bucket = $storage->bucket($bucketName);
$uploader = $bucket-> getResumableUploader (
fopen ($_FILES['file']['tmp_name'], 'r'),[
'name' => 'images/load_image.png',
'predefinedAcl' => 'publicRead',
]);
try {
$uploader-> upload ();
echo 'File Uploaded';
} catch (GoogleException $ex) {
$resumeUri = $uploader->getResumeUri();
$object = $uploader->resume($resumeUri);
echo 'No File Uploaded';
}
}
else {
echo 'No File Uploaded';
}
Error which i am getting is below
> Warning: The use statement with non-compound name
> 'GoogleCloudStorageStorageClient' has no effect in upload_gcs.php on
> line 4
>
> Fatal error: Class 'StorageClient' not found in upload_gcs.php on line
> 16
Is my process correct or are there any other ways to upload image from my server to google cloud storage.
The correct namespace for the script has to be used otherwise it's unresolvable. See correction below.
<?php
require 'vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Core\Exception\GoogleException;
class GCPStorage {
function __construct()
{
$projectId = '<your-project-id>';
$bucketName = '<your-bucket-name>';
$storage = new StorageClient([
'projectId' => $projectId,
'keyFilePath' => '<your-service-account-key-file>'
]);
$this->bucket = $storage->bucket($bucketName);
}
function uploadToBucket()
{
if(/your-precondition/) {
return 'No File Uploaded';
}
$uploadedFileLocation = $_FILES['file']['tmp_name'];
$uploader = $this->bucket->getResumableUploader(
fopen($uploadedFileLocation, 'r'),
['name' => 'images/file.txt', 'predefinedAcl' => 'publicRead']
);
try {
$object = $uploader->upload();
} catch(GoogleException $ex) {
$resumeUri = $uploader->getResumeUri();
try {
$object = $uploader->resume($resumeUri);
} catch(GoogleException $ex) {
return 'No File Uploaded';
}
} finally {
return 'File Uploaded';
}
}
}
$gcpStorage = new GCPStorage;
echo $gcpStorage->uploadToBucket();
A small suggestion: assert your precondition early as a guard clause by returning early when it fails.
Error:Unable to open using mode r: fopen(): Filename cannot be empty I keep getting this error when I try to upload larger files (more than 5MB). I have uploaded the PHP app to AWS Elastic Beanstalk and I upload the files to AWS S3. I don't even have fopen() in the code.
Alson when I test the site using XAMPP I don't get this error.
This is the code I use to upload file to S3:
<?php
session_start();
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
// AWS Info
$bucketName = 'tolga20.images';
$IAM_KEY = '******************';
$IAM_SECRET = '*************************';
$feedback = '';
$unqiue_num = mt_rand(1000, 9999);
if(isset($_FILES['fileToUpload'])) {
$user_set_id = $_POST['user_set_id'];
// Connect to AWS
try {
// You may need to change the region. It will say in the URL when the bucket is open
// and on creation.
$s3 = S3Client::factory(
array(
'credentials' => array(
'key' => $IAM_KEY,
'secret' => $IAM_SECRET
),
'version' => 'latest',
'region' => 'eu-west-2'
)
);
} catch (Exception $e) {
// We use a die, so if this fails. It stops here. Typically this is a REST call so this would
// return a json object.
die("Error: " . $e->getMessage());
}
$temp_name = explode(".", $_FILES["fileToUpload"]["name"]);
$newfilename = $unqiue_num . "-" . $user_set_id . '.' . end($temp_name);
// For this, I would generate a unqiue random string for the key name. But you can do whatever.
$keyName = 'images/' . basename($newfilename);
$pathInS3 = 'https://s3.eu-west-2.amazonaws.com/' . $bucketName . '/' . $keyName;
// Add it to S3
try {
// Uploaded:
$file = $_FILES["fileToUpload"]['tmp_name'];
$s3->putObject(
array(
'Bucket'=>$bucketName,
'Key' => $keyName,
'SourceFile' => $file,
'StorageClass' => 'REDUCED_REDUNDANCY'
)
);
} catch (S3Exception $e) {
die('Error:' . $e->getMessage());
} catch (Exception $e) {
die('Error:' . $e->getMessage());
}
//$feedback = 'File uploaded! Custom name: ' . '<b><i>' . $newfilename;
$_SESSION['newfilename'] = $newfilename;
header("Location: next.php");
}
?>
Try to increase the POST_MAX_SIZE and UPLOAD_MAX_FILESIZE values in your php.ini!
$file = $_FILES["fileToUpload"]['tmp_name'];
change to
$file = $_FILES["fileToUpload"]['name'];
Hope it will solve your problem.
I am trying to create event with picture, but when i upload picture to facebook it throws me an error (#324) Missing or invalid image file
this is the function to upload picture.
public function uploadFacebookEventPicture($fullPath, $eventId) {
$mainImage = '#' . $fullPath;
$imgData = array(
'picture' => $mainImage
);
try {
$data = $this->facebook->api('/'.$eventId, 'post', $imgData);
return $data;
} catch (FacebookApiException $e) {
error_log('Failed to attach picture to event. Exception: ' . $e->getMessage());
}
return null;
}
the par of code i use after form post
if ($file[$name]['error'] == 0) {
$fileName = $file[$name]['name'];
$fileInfo = pathinfo($fileName);
$newFileName = md5($fileName . microtime()) . '.' . $fileInfo['extension'];
$fullPath = $this->config->applications->uploadPath . $newFileName;
$form->$name->addFilter('Rename', $fullPath);
if ($form->$name->receive()) {
$resize = new SimpleImage();
$resize->load($fullPath);
$resize->resizeToWidth($this->config->applications->resize->width);
$resize->save($fullPath);
// Gathering data for saving files information
$fileInfo = array(
'name' => $newFileName,
'type' => FileTypes::IMAGE,
'description' => 'Application: Uploaded from Events form in back-end',
);
$fileId = $dbFiles->save($fileInfo);
$eventFileData = array(
'event_id' => $eventId,
'file_id' => $fileId,
'main_image' => ($name == 'mainImage') ? 1 : 0
);
$dbEventFiles->save($eventFileData);
if ($name === 'mainImage') {
$success = **$this->uploadFacebookEventPicture($fullPath, $eventData['fb_event_id']**);
}
}
}
facebook object is created with upload file true
$facebook = new Facebook(array(
'appId' => $config->facebook->appId,
'secret' => $config->facebook->secret,
'fileUpload' => true
));
According to Facebook bug tracker, this bug has been fixed:
Bug tracker post
Status changed to Fixed
Code above works fine for uploading facebook event picture.