upload picture in database using android studio - php

<?php ## Heading ##
require_once 'include/db_connection.php';
global $connection; $upload_path = 'uploads/';
//this is our upload folder
$server_ip = gethostbyname(gethostname());
//Getting the server ip
$upload_url = 'http://'.$server_ip.'/android_upload/'.$upload_path;
//upload url
//response array
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//checking the required parameters from the request
if(isset($_POST['caption'])) {
$caption = $_POST['caption'];
$fileinfo = pathinfo($_FILES['image']['name']);
//getting file info from the request
$extension = $fileinfo['extension'];
//getting the file extension
$file_url = $upload_url . getFileName() . '.' . $extension;
//file url to store in the database
$file_path = $upload_path . getFileName() . '.'. $extension;
//file path to upload in the server
$img_name = getFileName() . '.'. $extension;
//file name to store in the database
try{
move_uploaded_file($_FILES['image']['tmp_name'],$file_path);
//saving the file to the uploads folder;
//adding the path and name to database
$sql = "INSERT INTO photos(photo_name, photo_url, caption) ";
$sql .= "VALUES ('{$img_name}', '{$file_url}', '{$caption}');";
if(mysqli_query($connection,$sql)){
//filling response array with values
$response['error'] = false;
$response['photo_name'] = $img_name;
$response['photo_url'] = $file_url;
$response['caption'] = $caption;
}
//if some error occurred
}catch(Exception $e){
$response['error']=true;
$response['message']=$e->getMessage();
}
//displaying the response
echo json_encode($response);
//closing the connection
mysqli_close($connection);
}else{ $response['error'] = true;
$response['message']='Please choose a file';
}
}
/* We are generating the file name so this method will return a file name
for the image to be uploaded */
function getFileName(){
global $connection;
$sql = "SELECT max(id) as id FROM photos";
$result = mysqli_fetch_array(mysqli_query($connection, $sql));
if($result['id']== null) return 1;
else return ++$result['id'];
mysqli_close($connection);
}
?>

Here is picture upload code and get response image url save your database. u hope you try this.
<?php
include('confi.php');
/**********MYSQL Settings****************/
function GetImageExtension($imagetype)
{
if(empty($imagetype)) return false;
switch($imagetype)
{
case 'image/bmp': return '.bmp';
case 'image/gif': return '.gif';
case 'image/jpeg': return '.jpg';
case 'image/png': return '.png';
default: return false;
}
}
if($_SERVER['REQUEST_METHOD'] == "POST"){
if (isset($_FILES["file"]["name"])) {
$file_name=$_FILES["file"]["name"];
$temp_name=$_FILES["file"]["tmp_name"];
$imgtype=$_FILES["file"]["type"];
$ext= GetImageExtension($imgtype);
$imagename=date("m-Y")."-".rand().$_FILES['file']['name'];
$target_path ='images/'.$imagename;
if(move_uploaded_file($temp_name, $target_path)) {
$result = $url.'api/'.$target_path;
$json = array( "status" =>1,"file-url" => $result, "files" => $_FILES);
}else{
if ($_FILES['uploaded']['error'] !== UPLOAD_ERR_OK) {
$json = array( "status" =>0, "error" => $_FILES['uploaded']);
}
else{
$json = array( "status" =>0,"files" => $_FILES);
}
}
}
else{
$json = array("status" =>0, "error" => "Problem occurred");
}
}else{
$json = array("status" => 0, "message" => "Request method is wrong!");
}
header('Content-type:application/json');
echo json_encode($json);
?>

Related

Failed to upload mp4 files in PHP

am trying to upload .mp4 files with php but it's not working. Here's the script:
PHP Class to handle the upload:
class CustomFileUpload
{
public static function upload($data)
{
$errors = [];
$response = [];
$file = htmlentities(trim($data['file']['name']), ENT_QUOTES, 'UTF-8');
$tmpDir = $data['file']['tmp_name'];
$fileSize = $data['file']['size'];
$fileExt = strtolower(pathinfo($file,PATHINFO_EXTENSION));
$validExtensions = ['mp3', 'mp4'];
$uploadDir = '';
if ($fileExt == "mp4") {
$uploadDir = './public/ex-media/videos/';
} elseif ($fileExt == "mp3") {
$uploadDir = './public/ex-media/audios/';
} else {
$errors['msg'] = 'file type not allowed.';
$response['status'] = 407;
$response['msg'] = "error";
$response['error'] = $errors;
return $response;
}
if(!in_array($fileExt,$validExtensions))
{
$errors['msg'] = "Invalid extension detected for selected image file, please use a supported image extension.";
$errors['ext-detected'] = $fileExt;
}
if(empty($errors))
{
$uuid = explode("-", $data['uuid']);
$fileNewName = $uuid[0]."-".time().".".$fileExt;
var_dump($tmpDir);
exit();
$moved = move_uploaded_file($tmpDir, $uploadDir.$fileNewName);
if ($moved) {
$response['status'] = 200;
$response['msg'] = "success";
$response['fileUrl'] = $fileNewName;
echo('heres ur newly uploaded file - '.$fileNewName);
exit();
return $response;
} else {
$response['status'] = 502;
$response['msg'] = "failed";
$response['error'] = "upload failed for UNKNOWN reasons!";
echo('error while uploading file - go to CustomFileUpload.php');
exit();
return $response;
}
}
else {
$response['status'] = 407;
$response['msg'] = "error";
$response['error'] = $errors;
return $response;
}
}
}
PHP Controller Action that calls the CustomFileUpload class:
public function uploadAction()
{
$response = ['status_code' => 404];
if ($this->getRequest()->isPost())
{
$data = $this->params()->fromPost();
$request = $this->getRequest();
$data = array_merge_recursive(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$fileUpload = CustomFileUpload::upload($data);
}
return new JsonModel($response);
}
If I upload an mp3 file, it works perfectly but for mp4, it's the opposite. So I tried to dump the content of the tmp_dir var_dump($tmpDir); exit(); as seen the CustomFileUpload class. After doing this, it turns out that the tmp_dir is empty for mp4 files which is not so for the mp3 files as seen in the screenshots below (taken from Postman).
tmp_dir IS NOT EMPTY for mp3 file:
enter image description here
tmp_dir IS EMPTY for mp3 file:
enter image description here
Please, how do I fix these?

file not found exception in laravel

I am facing some problem while uploading image in laravel framework of my project .I checked image is uploading to folder , but still this error is coming
Below is coding
/////////// Course Image ///////////
$tmp_name1 = $course_image['tmp_name'];
$type1 = $course_image['type'];
$name1 = $course_image['name'];
$res1 = $this->upload_file($tmp_name1, $name1);
if ($res1) {
$course_image_url = $res1;
} else {
$course_image_url = "";
}
function upload_file($source, $name) {
$list = explode(".", $name);
$ext = $list[count($list) - 1];
$ext = strtolower($ext);
if (in_array($ext, $this->file_extension)) {
$filename = md5(date("YmdHis") . microtime() . rand(100, 100000000)) . "." . $ext;
$destination = "public/uploads/" . $filename;
$res = move_uploaded_file($source, $destination);
if ($res) {
return $destination = "uploads/" . $filename;
} else {
$message = "Internal server error";
(json_encode(array("responseCode" => "500", "responseMsg" => array("status" => "error", "statusReason" => $message))));
}
} else {
$message = "Invalid file extention";
(json_encode(array("responseCode" => "500", "responseMsg" => array("status" => "error", "statusReason" => $message))));
}
}
There are lots of codes , I posted only the required one .
You should follow the Laravel Example for Uploading Files.
I.e., you can check if a file has been uploaded successfully using:
if ($request->hasFile('image')) {
//
}
And you can move / rename a file using:
$request->file('image')->move($destinationPath);
or
$request->file('image')->move($destinationPath, $fileName);
I found that issue .
Go to line number 66 of this path(D:\xampp\htdocs\blog\vendor\laravel\framework\src\Illuminate\Http\UploadedFile.php) in your project folder .or search the text instanceof static.
After it remove the "instanceof static" ,then it is working fine.
Thanx

image upload error in php codeigniter [The upload path does not appear to be valid.]

I was using php codeigniter 2.x now i updated it to 3.x, after that my upload code is not working.
this is my code. please go though it.
when this code is working always getting the error
The upload path does not appear to be valid.
$this->load->library('upload');
$session = $this->ifisSession();
$uploadfolder = 'profileImgs';
$fullPath = 'abc';
$imageconfig['upload_path'] = $fullPath;
$imageconfig['max_size'] = (1024); // 1mb file size
$imageconfig['allowed_types'] = 'gif|jpg|png';
$imageconfig['max_width'] = (1024 );
$imageconfig['max_height'] = (1024);
$fieldName = 'profileimage';
//$uploadfilename = $_FILES[$fieldName];
$uploadfilename = $_FILES[$fieldName]['name'];
// printv($uploadfilename, 'this ihere');
$fileinfo = pathinfo($uploadfilename);
if (isset($fileinfo['extension'])) {
$ext = $fileinfo['extension'];
$imageconfig['file_name'] = $session['firstname'] . '_' . $session['user_id_pk'] . '_' . uniqid() . '.' . $ext;
}
$this->load->library('upload', $imageconfig);
if (!$this->upload->do_upload('profileimage')) {
$error = $this->upload->display_errors();
$data['data']['profileUpdate_error'] = $error;
// move to profile page with erro message
} else {
$profileUploadinfo = array('upload_data' => $this->upload->data());
$profileimgurl = '';
$res = $this->Model_userinfo->updateProfileImg($session['user_id_pk'], $profileimgurl);
if($res > 0){
$data['data']['profileUpdate_success'] = 'Profile Updated';
}else{
$data['data']['profileUpdate_error'] = 'Profile Not updated';
}
}

move uploaded file success but could not find file in folder

I have the following code
public function upload() {
if($_FILES){
$this->load->model('account/customer');
$file = $_FILES['profile'];
$file_name = $file['name'];
// $ext = end(explode('.', $file_name));
// $file_name = 'na_'.md5(time()).'.'.$ext;
echo $file_content = $file['tmp_name'];
$data = array('customer_id' => $this->customer->getId(), 'img_url' => $file['name']);
$this->model_account_customer->profileImage($data);
echo 'test/'.$file_name;
$img = move_uploaded_file($file['tmp_name'], 'test/'.$file['name']);
if($img) {
$return = json_encode(array('status' => 1));
} else {
$return = json_encode(array('status' => 0));
}
echo $return;
}
}
The above code returning status as 1 but could not see the file in folder.
I check folder permission is 0777
Try appending a / in front of the path
move_uploaded_file($file['tmp_name'], '/test/'.$file['name']);

How can I upload a file to amazon S3 with Codeigniter/PHP?

I'm trying to upload a file to my Amazon S3 bucket. My friend had this working on our site in the past but a year later its busted and I can't figure out what's wrong. We are using the S3 PHP library developed by Geoff gaudreault.
This library looks pretty straightforward to me, really it looks like there is one key function: putObject().
Unfortunately, I'm not even getting out of the gate. I'm getting the following error message:
Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.
Here's my codeigniter PHP for my upload form action:
function s3(){
$config['upload_path'] = $_SERVER["DOCUMENT_ROOT"].'/temp/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000000';
$config['max_width'] = '1024000';
$config['max_height'] = '768000';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
echo 'failure';
}
else
{
$data = array('upload_data' => $this->upload->data());
$fn = $data['file_name'];
$type = substr($fn, strrpos($fn, '.') + 1);
$this->load->library('s3');
$temp_file_path = $_SERVER["DOCUMENT_ROOT"]."/temp/" . $data['file_name'];
$contents = read_file($temp_file_path); // will this blow up or timeout for large files?!
$newFileName = uniqid().".".substr($temp_file_path, strrpos($temp_file_path, '.') + 1);
$contentPath = "mysite.com/Images";
$this->s3->putObject($newFileName, $contents, $contentPath, 'private', $type);
echo 'success';
}
}
Does anyone have any thoughts?
I switched to a different S3 PHP library, which is also referred to as S3.php, that is part of this really nice Netuts tutorial source code.
Just plugging in my AWS keys and bucket name into the demo's page.php file, I was able to upload to my bucket in like 2 minutes. So this tutorial is super easy. Very exciting!
in codeigniter
Here link to upload and delete image in s3 bucket
<?php
function profile_upload()
{
//print_r($_FILES);
if ($this->session->userdata('user_login')) {
$file = $_FILES['agent_profile_file']['tmp_name'];
if (file_exists($file)) {
$allowedExts = array("gif", "jpeg", "jpg", "png");
$typefile = explode(".", $_FILES["agent_profile_file"]["name"]);
$extension = end($typefile);
if (!in_array(strtolower($extension), $allowedExts)) {
//not image
$data['message'] = "images";
} else {
$userid = $this->session->userdata['user_login']['userid'];
$full_path = "agent_image/" . $userid . "/profileImg/";
/*if(!is_dir($full_path)){
mkdir($full_path, 0777, true);
}*/
$path = $_FILES['agent_profile_file']['tmp_name'];
$image_name = $full_path . preg_replace("/[^a-z0-9\._]+/", "-", strtolower(uniqid() . $_FILES['agent_profile_file']['name']));
//move_uploaded_file($path,$image_name);
$data['message'] = "sucess";
$s3_bucket = s3_bucket_upload($path, $image_name);
if ($s3_bucket['message'] == "sucess") {
$data['imagename'] = $s3_bucket['imagepath'];
$data['imagepath'] = $s3_bucket['imagename'];
}
//print_r($imagesizedata);
//image
//use $imagesizedata to get extra info
}
} else {
//not file
$data['message'] = "images";
}
} else {
$data['message'] = "login";
}
echo json_encode($data);
//$file_name2 = preg_replace("/ /", "-", $file_name);
}
// Helper file add code
// image compress code
function compress($source, $destination, $quality)
{
ob_start();
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($source);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source);
}
$filename = tempnam(sys_get_temp_dir(), "beyondbroker");
imagejpeg($image, $filename, $quality);
//ob_get_contents();
$imagedata = ob_end_clean();
return $filename;
}
// type for if image then it will reduce size
// site for it in web of mobile because mobile webservice image will in base 64
// $tempth will file temp path
// $image_path will file where to save path
function s3_bucket_upload($temppath, $image_path, $type = "image", $site = "web")
{
$bucket = "bucket-name";
$data = array();
$data['message'] = "false";
// For website only
if ($site == "web") {
if ($type == "image") {
$file_Path = compress($temppath, $image_path, 90);
} else {
$file_Path = $temppath;
}
}
try {
$s3Client = new S3Client([
'version' => 'latest',
'region' => 'us-west-2',
'credentials' => [
'key' => 'aws-key',
'secret' => 'aws-secretkey',
],
]);
// For website only
if ($site == "web") {
$result = $s3Client->putObject([
'Bucket' => $bucket,
'Key' => $image_path,
'SourceFile' => $file_Path,
//'body'=> $file_Path,
'ACL' => 'public-read',
//'StorageClass' => 'REDUCED_REDUNDANCY',
]);
$data['message'] = "sucess";
$data['imagename'] = $image_path;
$data['imagepath'] = $result['ObjectURL'];
} else {
// $tmp = base64_decode($base64);
$upload = $s3Client->upload($bucket, $image_path, $temppath, 'public-read');
$data['message'] = "sucess";
$data['imagepath'] = $upload->get('ObjectURL');
}
} catch (Exception $e) {
$data['message'] = "false";
// echo $e->getMessage() . "\n";
}
return $data;
}

Categories