Skip to content

Instantly share code, notes, and snippets.

@sharifbdp
Created February 25, 2016 05:11
Show Gist options
  • Save sharifbdp/91457ea4af012ee5f30d to your computer and use it in GitHub Desktop.
Save sharifbdp/91457ea4af012ee5f30d to your computer and use it in GitHub Desktop.
Image Upload into S3 (CodeIgniter)
/**
* File Upload into Amazon S3
* @param string $input_name
* @param int $restaurant_id
* @return string/bolean
*/
public function _fileUpload($input_name, $restaurant_id) {
if (isset($_FILES[$input_name]) && ($_FILES[$input_name]) != NULL) {
$file_full_name = $_FILES[$input_name]['name'];
// current time and date
$extention = explode(".", $file_full_name);
//$picname = $filename[0];
//$file_type = $filename[1];
$file_type = strtolower(end($extention));
$rand_string = random_string('alnum', 8);
// AMAZON
$file_new_name = date("YmdHis") . $restaurant_id . $rand_string . "." . $file_type;
// AWS Start
require_once './aws/aws-autoloader.php';
// Instantiate an Amazon S3 client.
$s3 = new Aws\S3\S3Client([
'version' => 'latest',
'region' => 'ap-southeast-1',
'credentials' => [
'key' => 'YOUR_KEY',
'secret' => 'YOUR_SECRET',
],
]);
try {
$result = $s3->putObject([
'Bucket' => 'BUCKET_NAME',
'Key' => 'UPLOAD_DIR' . date("Y") . '/' . date("m") . '/' . $file_new_name,
'Body' => fopen($_FILES[$input_name]['tmp_name'], 'r'), //'Body' => fopen('/path/to/file', 'r'),
'ACL' => 'public-read'
]);
} catch (Aws\Exception\S3Exception $e) {
echo "There was an error uploading the file.\n";
}
if ($result['ObjectURL']) {
return $file_new_name;
} else {
return NULL;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment