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.
Related
On my site I use google api to upload images in folder. Actually, there is no official documentation from google how to use api using php, only python, js and etc. Current problem is that I get no errors, but file isn't uploading. I'm 100% sure that my service workers work (sorry for such bad english) properly. Below I put my php code for uploading images:
<?php
include '../vendor/autoload.php';
function handleGoogleDrive($file)
{
//connecting to google drive
$client = new \Google_Client();
$client->setApplicationName('Somesite');
$client->setScopes([\Google_Service_Drive::DRIVE]);
$client->setAccessType('offline');
$client->setAuthConfig('./credentials.json');
$client->setClientId('2445617429-6k99ikago0s0jdh5q5k3o37de6lqtsd3.apps.googleusercontent.com');
$client->setClientSecret('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');
$service = new Google_Service_Drive($client);
//counting amount of files in folder, there is no real reason in doing that
//it is just a test of connecting
$folder_id = '1eQtNOJjlA2CalZYb90bEs34IaP6v9ZHM';
$options = [
'q' => "'" . $folder_id . "' in parents",
'fields' => 'files(id, name)'
];
//printing result
$results = $service->files->listFiles($options);
echo count($results->getFiles());
//trying to add file
$data = file_get_contents("../test.jpg");
$file = new Google_Service_Drive_DriveFile();
$file->setName(uniqid(). '.jpg');
$file->setDescription('A test document');
$file->setMimeType('image/jpeg');
$new_file = $service->files->create($file, [
'data' => $data,
'mimeType' => 'image/jpeg',
'uploadType' => 'multipart',
]);
print_r($new_file);
}
This is my standard upload code for uploading.
Try removing 'uploadType' => 'multipart', in your code.
I also cant see you setting the folder id when you upload your file which means its going to root directory.
// Upload a file to the users Google Drive account
try{
$filePath = "image.png";
$folder_id = '1eQtNOJjlA2CalZYb90bEs34IaP6v9ZHM';
$fileMetadata = new Drive\DriveFile();
$fileMetadata->setName("image.png");
$fileMetadata->setMimeType('image/png');
$fileMetadata->setParents(array($folder_id));
$content = file_get_contents($filePath);
$mimeType=mime_content_type($filePath);
$request = $service->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'fields' => 'id'));
printf("File ID: %s\n", $request->id);
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}
Remember if you are using a service account, files are uploaded to the service accounts drive account unless you add the folder you want to upload the file to.
files list
// Print the next 10 events on the user's drive account.
try{
$optParams = array(
'pageSize' => 10,
'fields' => 'files(id,name,mimeType)'
);
$results = $service->files->listFiles($optParams);
$files = $results->getFiles();
if (empty($files)) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($files as $file) {
$id = $file->id;
printf("%s - (%s) - (%s)\n", $file->getId(), $file->getName(), $file->getMimeType());
}
}
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}
Using the code which was suggested to me, this is full solution.
(Thanks everybody who helped me)
<?php
include '../vendor/autoload.php';
function handleGoogleDrive($file)
{
//connecting to google drive
$client = new \Google_Client();
$client->setClientId('YOUR ID IN SECRET FILE');
$client->setClientSecret(YOUR SECRET IN JSON FILE);
$client->setRedirectUri(YOUR REDIRECT URI);
//you should register redirect uri
$client->setApplicationName('Somesite');
$client->setScopes([\Google_Service_Drive::DRIVE]);
$client->setAuthConfig('./credentials.json');
$service = new Google_Service_Drive($client);
try{
$filePath = "../test.jpg";
$folder_id = 'YOUR FOLDER ID';
$fileMetadata = new Google_Service_Drive_DriveFile();
$fileMetadata->setName("image.png");
$fileMetadata->setMimeType('image/png');
$fileMetadata->setParents(array($folder_id));
$content = file_get_contents($filePath);
$mimeType=mime_content_type($filePath);
$request = $service->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'fields' => 'id'));
printf("File ID: %s\n", $request->id);
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
try{
$optParams = array(
'pageSize' => 10,
'fields' => 'files(id,name,mimeType)'
);
$results = $service->files->listFiles($optParams);
$files = $results->getFiles();
if (empty($files)) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($files as $file) {
$id = $file->id;
printf("%s - (%s) - (%s)\n", $file->getId(), $file->getName(), $file->getMimeType());
}
}
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}
}
Based on the sdk code, the s3 client code uses retry logic, but the sample code from the docs suggest doing a loop until the multipart upload finishes correctly.
$s3Client = new S3Client([
'profile' => 'default',
'region' => 'us-east-2',
'version' => '2006-03-01'
]);
$bucket = 'your-bucket';
$key = 'my-file.zip';
// Using stream instead of file path
$source = fopen('/path/to/large/file.zip', 'rb');
$uploader = new ObjectUploader(
$s3Client,
$bucket,
$key,
$source
);
do {
try {
$result = $uploader->upload();
if ($result["#metadata"]["statusCode"] == '200') {
print('<p>File successfully uploaded to ' . $result["ObjectURL"] . '.</p>');
}
print($result);
} catch (MultipartUploadException $e) {
rewind($source);
$uploader = new MultipartUploader($s3Client, $source, [
'state' => $e->getState(),
]);
}
} while (!isset($result));
Is that MultipartUploadException being thrown after the standard 3 retries for it have happened? Or are multipart uploads not covered by the retry policy?
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 upload .mp3 file to Amazon S3 Server Using this code, i am not getting any resposne from server. On other hand .txt OR .pdf OR .odf file is working fine. What i do for .mp3 and .zip file Structure.
<?php
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Common\Aws;
use Aws\Common\Enum\Size;
use Aws\Common\Exception\MultipartUploadException;
use Aws\S3\Model\MultipartUpload\UploadBuilder;
use Aws\S3\Model\ClearBucket;
$buketname = '***********';
$filename = 'first.mp3';
$fileloc = '/var/www/html/aws/aws-sdk-php/first.mp3';
// 1. Instantiate the client.
$s3 = S3Client::factory(array(
'credentials' => array(
'key' => '**************',
'secret' => '**************',
)
));
try {
$result = $s3->putObject(array(
'Content-Type' => 'audio/mpeg',
'Bucket' => $buketname,
'Key' => $filename,
'SourceFile' => $fileloc,
'Metadata' => array(
'Agent' => 'xyz'
)
));
// We can poll the object until it is accessible
$s3->waitUntilObjectExists(array(
'Bucket' => $buketname,
'Key' => $filename
));
echo "File Uploaded : ".$filename;
} catch (\Aws\S3\Exception\S3Exception $e) {
echo $e->getMessage();
}
<?php
ob_start();
/* Amazon A3 */
// Auto Load Things i need
require 'vendor/autoload.php';
// Define Things i will use
use Aws\Common\Aws;
use Aws\Common\Enum\Size;
use Aws\Common\Exception\MultipartUploadException;
use Aws\S3\Model\MultipartUpload\UploadBuilder;
use Aws\S3\Model\ClearBucket;
// Static Variables
$aws_access_key = AWSACCESSKEY; // AWS Access key
$aws_access_security = AWSACCESSSECURITY; // AWS Security Key
$aws_default_buket = AWSDEFAULTBUKET; // Your Default Bucket
$aws_default_region = AWSDEFAULTREGION; // Your Default Region
$aws_default_scema = AWSDEFAULTSCEMA; // Default Protocol Schema
$aws_default_uploadfrom = AWSDEFAULTUPLOADFROM; // File Upload from Directory
// Instantiate the AWS client with your AWS credentials
$aws = Aws::factory(array(
'key' => $aws_access_key,
'secret' => $aws_access_security,
'region' => $aws_default_region,
'scheme' => $aws_default_scema,
));
// Define S3client Object
$s3Client = $aws->get('s3');
$useridfolder = $_REQUEST["useridfolder"];
if(!empty($_FILES['inputFilemp3']['name'])) {
$timestamp = time();
$uploaddir = "mp3uploads/";
$filename = $_FILES['inputFilemp3']['name'];
//$filename = strtolower($filename);
$filename = strip_tags($filename);
//$str = preg_replace('/[\r\n\t ]+/', ' ', $str);
//$str = preg_replace('/[\"\*\/\:\<\>\?\'\|]+/', ' ', $str);
//$str = strtolower($str);
//$str = html_entity_decode( $str, ENT_QUOTES, "utf-8" );
//$str = htmlentities($str, ENT_QUOTES, "utf-8");
//$str = preg_replace("/(&)([a-z])([a-z]+;)/i", '$2', $str);
//$str = str_replace(' ', '-', $str);
//$str = str_replace('--','-',$str);
//$str = rawurlencode($str);
//$str = str_replace('%', '-', $str);
//$str = str_replace('#', '', $str);
//$str = ltrim($str, '-');
//$filename = preg_replace('/-{2,}/','-',$str);
///new line
$final_location = "mp3uploads/".$useridfolder."/".$timestamp."/".$filename;
/* crete and prepare directories */
/* file type check */
$type = $_FILES["inputFilemp3"]["type"];
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed','audio/mpeg','audio/x-mpeg','audio/mp3','audio/x-mp3','audio/mpeg3','audio/x-mpeg3','audio/mpg','audio/x-mpg','audio/x-mpegaudio');
$okay = false;
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
}
}
if(($okay == false) || ($_FILES["inputFilemp3"]["size"] > 157286400)){
echo "INVALID FILE";
} else{
/* file upload action */
if ($_FILES["inputFilemp3"]["error"] > 0)
{
echo " INVALID FILE";
} else {
$buketname = $aws_default_buket; // Get Bucket name
$filename = $final_location;
$fileloc = $_FILES['inputFilemp3']['tmp_name'];
$fileacl = 'private'; // private | public-read | public-read-write | authenticated-read | bucket-owner-read | bucket-owner-full-control
if(!$buketname || !$filename || !$fileloc || !$fileacl){
echo "Dude! your commands don't seems like they are ok!";
die();
}
try {
$uploader = UploadBuilder::newInstance()
->setClient($s3Client)
->setSource($fileloc)
->setBucket($buketname)
->setKey($filename)
->setConcurrency(3)
->setOption('ACL', $fileacl)
->setOption('Metadata', array('Agent' => 'aisS3Client'))
->setOption('CacheControl', 'max-age=7200')
->build();
// Perform the upload. Abort the upload if something goes wrong
try {
$uploader->upload();
//echo "File Uploaded : ".$filename;
} catch (MultipartUploadException $e) {
$uploader->abort();
//echo "File Did not Uploaded : ".$filename;
}
} catch (\Aws\S3\Exception\S3Exception $e) {
echo $e->getMessage();
}
unlink($_FILES['inputFilemp3']['tmp_name']);
$download_url= AWSDOWNLOADURL.$filename;
echo $download_url = trim($download_url);
}
}
}
?>
Source
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.