Amazon S3 - How to perform CRUD operations? - php

I'm using backbonejs for my project. My question is, how to perform CRUD operation in amazon S3? so far I can upload/create files into bucket and retrieve files but I dont know how to do update and delete files.
config.php
<?php
//Bucket Name
$bucket_name ="my_bucket";
//include the S3 class
if (!class_exists('S3'))require_once('S3.php');
//AWS access informations
if (!defined('awsAccessKey')) define('awsAccessKey', 'access_key');
if (!defined('awsSecretKey')) define('awsSecretKey', 'secret_key');
//instantiate the s3 class
$s3 = new S3(awsAccessKey, awsSecretKey);
//this is used to create a bucket in amazon S3
$s3->putBucket($bucket_name, S3::ACL_PUBLIC_READ);
?>
upload_image.php
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
if(isset($_POST) && !empty($_FILES) && !empty($_FILES['uploadfile']['name']) && isset($_POST['productId'])) {
//upload file formats
$valid_file_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
function get_file_extension($file_name) {
return substr(strrchr($file_name,'.'),1);
}
$filename = $_FILES['uploadfile']['name'];
$tmp_filename = $_FILES['uploadfile']['tmp_name'];
$filetype = strtolower($_FILES['uploadfile']['type']);
//get file extenstion to verify the format
$extension = get_file_extension($filename);
if(in_array($extension,$valid_file_formats)){
//include config.php
include_once "config.php";
//set content type in headers inorder to display image in browser
$header = array('Content-Type' => $filetype);
//change filename
$new_file_name = "w3_".time().".".$extension;
if($s3->putObject(S3::inputFile($tmp_filename), $bucket_name , $new_file_name, S3::ACL_PUBLIC_READ, array(), $header) ){
$img = "http://".$bucket_name.".s3.amazonaws.com/".$new_file_name;
// array for JSON response
$response = array();
// check for required fields
$productId = $_POST['productId'];
$imageLink = $img;
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO tbl_images(productId, imageLink,dateCreated) VALUES('$productId', '$imageLink',NOW())");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Image successfully uploaded.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
echo "1-".$img;
} else {
echo "2-Upload Failed";
}
} else {
echo "3-Not a Valid Format";
}
} else {
echo "4-Please Select a File";
}
?>
Thanks a lot in advance.

Have a look at the php sdk
http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.S3.S3Client.html
There is commands there for deleteMatching to remove items from a bucket.
As for update, call putObject again to overwrite the file.

Related

PHP / MySQL: Failed to save image to folder at server but link URL is updated MySQL database

I currently created a system that allowed a user to upload a photo only. The photo the already upload can be replaced if the user want to change it.
The current code shows that there's no error in this function. The URL updated at MySQL database. But the problem is the image doesn't update. Below is my current code:
update_photo_before.php
<?php
require_once '../../../../config/configPDO.php';
$report_id = $_POST['report_id'];
$last_insert_id = null;
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png");
//File extension
$ext = strtolower(pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION));
//Check extension
if(in_array($ext, $allowed_extensions)) {
$defID = "before_" . $report_id;
$imgPath = "images/$defID.png";
$ServerURL = "http://172.20.0.45/tgotworker_testing/android/$imgPath";
$query = "UPDATE ot_report SET photo_before = '$ServerURL', time_photo_before = GETDATE() WHERE report_id = :report_id";
$sql = $conn->prepare($query);
$sql->bindParam(':report_id', $report_id);
$sql->execute();
if ($sql){
move_uploaded_file($_FILES['uploadFile']['name'], $imgPath); //line 28
echo "<script>alert('Saved')</script>";
header("Location: view_task.php?report_id=".$_POST['report_id']);
}else{
echo "Error!! Not Saved";
}
} else {
echo "<script>alert('File not allowed')</script>";
header("Location: view_task.php?report_id=".$_POST['report_id']);
}
?>
My folder images are located at 'tgotworker_testing' --> 'android' --> 'images'.
For update_photo_before.php:
'tgotworker_testing' --> 'pages' --> 'dashboard' --> 'engineer' --> 'view_task' --> 'update_photo_before.php'
Can anyone fix my problem? Thanks!
You check to see if the database gets updated, but not if the image is saved to the server.
move_uploaded_file() returns true on success and false on failure. So you can do a similar test as you have for $sql in your code.
<?php
require_once '../../../../config/configPDO.php';
$report_id = $_POST['report_id'];
$last_insert_id = null;
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png");
//File extension
$ext = strtolower(pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION));
//Check extension
if(in_array($ext, $allowed_extensions)) {
$defID = "before_" . $report_id;
$imgPath = "images/$defID.png";
$ServerURL = "http://172.20.0.45/tgotworker_testing/android/$imgPath";
// Check if image is uploaded to folder
if(move_uploaded_file($_FILES['uploadFile']['name'], $imgPath) === true) {
// If upload succeeds, then update database
$query = "UPDATE ot_report SET photo_before = '$ServerURL', time_photo_before = GETDATE() WHERE report_id = :report_id";
$sql = $conn->prepare($query);
$sql->bindParam(':report_id', $report_id);
$sql->execute();
// Check if database updated
if (!$sql){
echo "Error!! Database not updated.";
} else {
// Success!
header("Location: view_task.php?report_id=".$_POST['report_id']);
}
} else {
// Could not upload file
echo "Error!! Could not upload file to server.";
}
}
When PHP can't upload the file it will throw a warning. If you turn on your warnings while you are debugging, it should give you the reason why it's not working and you will be better able to solve the problem.
Put these lines at the top of the script to show all warnings and errors:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

PHP move_uploaded_file fail

I am trying to upload an image through alamofire and I have done it! My server received it but when I call move_uploaded_file function in my php file it shows FAILURE. I am sure that my server received the image and i am able to create directories through php. It is just this move_uploaded_file not letting me do the job. Here is my php code:
<?php
if (empty($_FILES["image"])){
$response = array("error" => "no data");
}else{
$path = "./Upload";
if(!file_exists($path)){
mkdir($path,0777,true);
$response["message"] = "new file created";
}else{
$response["message"] = "file already exist";
if(move_uploaded_file($_FILES["image"]["tmp_name"],$path)){
$response["message"] = "You've got it!!!";
}else{
$response["message"] = "upload function fail";
}
}
}
echo json_encode($response);
?>
$path is a directory, not a file. Change it to:
$path = "./Upload/file.txt";
Change:
$path = "./Upload";
With:
$path= "uploads/" . basename($_FILES["fileToUpload"]["name"]);

uploading file from android app into desired folder

I wan to upload file from android app using PHP in specific folder below is the code which I have tried.
pleas help me what is wrong in this code and please suggest me some easy solution for this or is this method right to upload files from android app on serever
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//checking the required parameters from the request
if(isset($_POST['exp']) && isset($_POST['employee_id']) && isset($_FILES['pdf']['name']) ){
//connecting to the database
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE) or die('Unable to Connect...');
$resume_name = $_POST['exp'];
$employee_id = $_POST['employee_id'];
$file_data = $_FILES['pdf']['name'];
$upload_path = 'Images/Employee_Profile_Picture/'.$employee_id.'/Resume/';
//getting file info from the request
$fileinfo = pathinfo($_FILES['pdf']['name']);
//getting the file extension
$extension = $fileinfo['extension'];
//file url to store in the database
$file_url = $upload_path . getFileName($employee_id). '.'. $extension;
//file path to upload in the server
$file_path = $upload_path . getFileName($employee_id);
try{
if(file_exists($upload_path))
{
$existing_file = glob($upload_path."/*.*");
$empty_file = implode(" ",$existing_file);
move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;
$sql = "UPDATE employee_registration SET resume_name ='$resume_name', resume_path='$file_url' where employee_id ='$employee_id'";
//adding the path and name to database
if(mysqli_query($con,$sql)){
//filling response array with values
$response['Success'] = "File Uploaded Successfully...!";
echo json_encode($response);
}
else
{
$response['Error'] = "File Uploading Error...!";
echo json_encode($response);
}
}
else
{
mkdir('Images/Employee_Profile_Picture/'.$employee_id.'/Resume');
move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;
$sql = "UPDATE employee_registration SET resume_name ='$resume_name', resume_path='$file_url' where employee_id ='$employee_id'";
//adding the path and name to database
if(mysqli_query($con,$sql))
{
//filling response array with values
$response['Success'] = "File Uploaded Successfully...!";
echo json_encode($response);
}
else
{
$response['Error'] = "File Uploading Error...!";
echo json_encode($response);
}
}
}catch(Exception $e){
$response['error']=true;
$response['message']=$e->getMessage();
}
}
}
//here is my method getFileName
function getFileName($employee_id)
{
//mysql query to fetch data
$sql = mysql_query("SELECT resume_path from employee_registration where
employee_id = '$employee_id'") or die(mysql_error());
while ($row = mysql_fetch_array($sql, MYSQL_ASSOC))
{
$response=$row['resume_path'];
}
$resume_name = explode("/", $response);
echo $resume_name[4];
return $resume_name;
}
Change below line:
move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;
To
move_uploaded_file($_FILES['pdf']['tmp_name'],$upload_path) ;
tmp_name should be used to upload the file, as it has the full path of the file where it is temporarily stored. Where as the name contain only the name of file without any path information.
if this doenst work move_uploaded_file($_FILES['pdf']['tmp_name'],$upload_path) ;
kindly use this file_put_contents($upload_path,$_FILES['pdf']['tmp_name']);

how get parameter with POST method from rest client to php

i need to save in a folder on server pdfs and in a db the relative url.
but with the code that i show you below i get the error in php:"please choose a file"...i don't know why.
I show you my code:
REST CLIENT SIDE:
enter image description here
SERVER SIDE:
<?php
//importing dbDetails file
require_once 'dbDetails.php';
//this is our upload folder
$upload_path = 'uploads/';
//Getting the server ip
$server_ip = gethostbyname(gethostname());
//creating the upload url
//$upload_url = 'http://'.$server_ip.'/AndroidImageUpload/'.$upload_path;
$upload_url = 'http://'.$server_ip.'/azz/'.$upload_path;
//response array
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//checking the required parameters from the request
if( isset($_POST['nome_pdf']) && isset($_FILES['pdf']['nome_pdf']) && isset($_POST['id'])){
//connecting to the database
$con = mysqli_connect(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME) or die('Unable to Connect...');
//getting name from the request
$nome = $_POST['nome_pdf'];
//getting file info from the request
$fileinfo = pathinfo($_FILES['pdf']['nome_pdf']);
//getting the file extension
$extension = $fileinfo['extension'];
$id = $_POST['id'];
//file url to store in the database
$file_url = $upload_url . getFileName() . '.' . $extension;
//file path to upload in the server
$file_path = $upload_path . getFileName() . '.'. $extension;
//trying to save the file in the directory
try{
//saving the file
move_uploaded_file($_FILES['pdf']['tmp_name'],$file_path);
$sql = "INSERT INTO `my_db`.`pdfss` (`id_pdf`, `nome_pdf`, `url_pdf`,`id_user`) VALUES (NULL, '$nome','$file_url', '$id');";
//adding the path and name to database
if(mysqli_query($con,$sql)){
//filling response array with values
$response['error'] = false;
// $response['url'] = $file_url;
// $response['name'] = $name;
$response['nome_pdf'] = $nome;
$response['url_pdf'] = $file_url;
}
//if some error occurred
}catch(Exception $e){
$response['error']=true;
$response['message']=$e->getMessage();
}
//closing the connection
mysqli_close($con);
}else{
$response['error']=true;
$response['message']='Please choose a file';
}
//displaying the response
echo json_encode($response);
}
I hope that you can help me!
This line
if( isset($_POST['nome_pdf']) && isset($_FILES['pdf']['nome_pdf']) && isset($_POST['id'])){
Should be
if( isset($_POST['nome_pdf']) && isset($_FILES['nome_pdf']['tmp_name']) && isset($_POST['id'])){
Or
if( isset($_POST['nome_pdf']) && isset($_FILES['nome_pdf']['name']) && isset($_POST['id'])){
Your error comes from here
isset($_FILES['pdf']['nome_pdf'])
NOTE: You do not use $_POST when dealing with file uploads in PHP. Use $_FILES. I think you are confused with the name of the file and also the array_keys that are associated with the $_FILES array
nome_pdf is not in the $_FILES array. If you try a dump of var_dump($_FILES['pdf']);, you will see that nome_pdf is not in the array.
Replace the line with:
if( isset($_FILES['pdf']) && $_FILES['pdf']['tmp_name'] != '' && isset($_POST['id'])){
#add your code
else{
$response['error']=true;
$response['message']= 'PDF FILE: '. $_FILES['pdf'].' ID of post: '.$_POST['id'];
exit;
}
echo(json_encode($reponse));
The above change will make sure the tmp_name is not empty.
Also before moving the file, i suggest using mime type to check for the extensions

swfupload destroy session? php

hy, i need a little help here:
i use SWFupload to upload images!
in the upload function i make a folder call $_SESSION['folder'] and all the files i upload are in 1 array call $_SESSION['files'] after uploads finish i print_r($_SESSION) but the array is empty? why that?
this is my upload.php:
if($_FILES['image']['name']) {
list($name,$error) = upload('image','jpeg,jpg,png');
if($error) {$result = $error;}
if($name) { // Upload Successful
$result = watermark($name);
print '<img src="uploads/'.$_SESSION['dir'].'/'.$result.'" />';
} else { // Upload failed for some reason.
print 'noname'.$result;
}
}
function upload($file_id, $types="") {
if(!$_FILES[$file_id]['name']) return array('','No file specified');
$isimage = #getimagesize($_FILES[$file_id]['tmp_name']);
if (!$isimage)return array('','Not jpg');
$file_title = $_FILES[$file_id]['name'];
//Get file extension
$ext_arr = split("\.",basename($file_title));
$ext = strtolower($ext_arr[count($ext_arr)-1]); //Get the last extension
//Not really uniqe - but for all practical reasons, it is
$uniqer = substr(md5(uniqid(rand(),1)),0,10);
//$file_name = $uniqer . '_' . $file_title;//Get Unique Name
//$file_name = $file_title;
$file_name = $uniqer.".".$ext;
$all_types = explode(",",strtolower($types));
if($types) {
if(in_array($ext,$all_types));
else {
$result = "'".$_FILES[$file_id]['name']."' is not a valid file."; //Show error if any.
return array('',$result);
}
}
if((!isset($_SESSION['dir'])) || (!file_exists('uploads/'.$_SESSION['dir']))){
$dirname = date("YmdHis"); // 20010310143223
$pathtodir = $_SERVER['DOCUMENT_ROOT']."/ifunk/uploads/";
$newdir = $pathtodir.$dirname;
if(!mkdir($newdir, 0777)){return array('','cannot create directory');}
$_SESSION['dir'] = $dirname;
}
if(!isset($_SESSION['files'])){$_SESSION['files'] = array();}
//Where the file must be uploaded to
$folder = 'uploads/'.$_SESSION['dir'].'/';
//if($folder) $folder .= '/'; //Add a '/' at the end of the folder
$uploadfile = $folder.$file_name;
$result = '';
//Move the file from the stored location to the new location
if (!move_uploaded_file($_FILES[$file_id]['tmp_name'], $uploadfile)) {
$result = "Cannot upload the file '".$_FILES[$file_id]['name']."'"; //Show error if any.
if(!file_exists($folder)) {
$result .= " : Folder don't exist.";
} elseif(!is_writable($folder)) {
$result .= " : Folder not writable.";
} elseif(!is_writable($uploadfile)) {
$result .= " : File not writable.";
}
$file_name = '';
} else {
if(!$_FILES[$file_id]['size']) { //Check if the file is made
#unlink($uploadfile);//Delete the Empty file
$file_name = '';
$result = "Empty file found - please use a valid file."; //Show the error message
} else {
//$_SESSION['files'] = array();
$_SESSION['files'][] .= $file_name;
chmod($uploadfile,0777);//Make it universally writable.
}
}
return array($file_name,$result);
}
SWFUpload doesn't pass the session ID to the script when you upload, so you have to do this yourself. Simply pass the session ID in a get or post param to the upload script, and then in your application do this before session_start:
if(isset($_REQUEST['PHPSESSID'])) {
session_id($_REQUEST['PHPSESSID']);
}
you must pass the session ID to the upload file used by swfupload.
more details here

Categories