Laravel 4.2 Uploading file in specific folder - php

Hi im creating a project in laravel 4.2 that uploads different files (e.g Pdf and images) in specific folders about 8 or 9 folders to be exact i just try the do a if statement but dont know what happend but its not working and there are no error displayed when i execute the code. please help me work this code or do you have any idea to simplify my code TIA!
Here's my code in my controller
public function upload()
{
$finame = Input::get('name');
$ftype = Input::get('type');
$username = Input::get('user');
$desc = Input::get('desc');
$date = Input::get('date');
$upload = Input::file('file');
$add = Files::upload2($finame,$ftype,$username,$desc,$date,$upload);
if ($add == true && $ftype == "pf") {
$upload -> move(public_path('pf'),$upload->getClientOriginalName());
return \Response::json(array('success' => true));
return Redirect::to('/home')->with('message', 'message|Record Successfully Added.');
} elseif ($add == true && $ftype == "sf") {
$upload -> move(public_path('sf'),$upload->getClientOriginalName());
return \Response::json(array('success' => true));
return Redirect::to('/home')->with('message', 'message|Record Successfully Added.');
} } elseif ($add == true && $ftype == "gale") {
$upload -> move(public_path('gale'),$upload->getClientOriginalName());
return \Response::json(array('success' => true));
return Redirect::to('/home')->with('message', 'message|Record Successfully Added.');
} } elseif ($add == true && $ftype == "advisory") {
$upload -> move(public_path('advisory'),$upload->getClientOriginalName());
return \Response::json(array('success' => true));
return Redirect::to('/home')->with('message', 'message|Record Successfully Added.');
} else {
return Redirect::back()->with('message', 'error|Error');
}
}
And my code in model:
public static function upload2($finame,$ftype,$username,$desc,$date,$upload)
{
$files = new self;
$files->file_name = $finame;
$files->file_type = $ftype;
$files->username = $username;
$files->description = $desc;
$files->date = $date;
$files->upload = $upload->getClientOriginalName();
try {
$files->save();
} catch (Exception $e) {
dd($e);
}
}
and in the view add this script:
<script>
var form = document.getElementById('upload');
var request = new XMLHttpRequest();
form.addEventListener('submit', function(e){
e.preventDefault();
var formdata = new FormData(form);
request.open('post', '/upload');
request.addEventListener("load", transferComplete);
request.send(formdata);
});
function transferComplete(data){
response = JSON.parse(data.currentTarget.response);
if(response.success){
document.getElementById('message').innerHTML = "File Successfully Uploaded!";
}
}
</script>

Related

Image taken from Android webview camera not saving to folder

I have this Smart Webview I got on https://github.com/ which was great. Being Android newbie developer, I have been having issue trying to solve this problem. If I select image from the phone directory and send to the backend(PHP); everything worked fine: image is moved to the upload folder; but If I take picture using the Android camera, the image never send to folder but the name of the image is saves into the database.
MainActivity for image upload
// handling input[type="file"]
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams){
if(check_permission(2) && check_permission(3)) {
if (ASWP_FUPLOAD) {
asw_file_path = filePathCallback;
Intent takePictureIntent = null;
Intent takeVideoIntent = null;
if (ASWP_CAMUPLOAD) {
boolean includeVideo = false;
boolean includePhoto = false;
// Check the accept parameter to determine which intent(s) to include.
paramCheck:
for (String acceptTypes : fileChooserParams.getAcceptTypes()) {
// Although it's an array, it still seems to be the whole value.
// Split it out into chunks so that we can detect multiple values.
String[] splitTypes = acceptTypes.split(", ?+");
for (String acceptType : splitTypes) {
switch (acceptType) {
case "*/*":
includePhoto = true;
includeVideo = true;
break paramCheck;
case "image/*":
includePhoto = true;
break;
case "video/*":
includeVideo = true;
break;
}
}
}
// If no `accept` parameter was specified, allow both photo and video.
if (fileChooserParams.getAcceptTypes().length == 0) {
includePhoto = true;
includeVideo = true;
}
if (includePhoto) {
takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = create_image();
takePictureIntent.putExtra("PhotoPath", asw_pcam_message);
} catch (IOException ex) {
Log.e(TAG, "Image file creation failed", ex);
}
if (photoFile != null) {
asw_pcam_message = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
}
if (includeVideo) {
takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
File videoFile = null;
try {
videoFile = create_video();
} catch (IOException ex) {
Log.e(TAG, "Video file creation failed", ex);
}
if (videoFile != null) {
asw_vcam_message = "file:" + videoFile.getAbsolutePath();
takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(videoFile));
} else {
takeVideoIntent = null;
}
}
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
if (!ASWP_ONLYCAM) {
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType(ASWV_F_TYPE);
if (ASWP_MULFILE) {
contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
}
Intent[] intentArray;
if (takePictureIntent != null && takeVideoIntent != null) {
intentArray = new Intent[]{takePictureIntent, takeVideoIntent};
} else if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else if (takeVideoIntent != null) {
intentArray = new Intent[]{takeVideoIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.fl_chooser));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, asw_file_req);
}
return true;
}else{
get_file();
return false;
}
}
//Creating image file for upload
private File create_image() throws IOException {
#SuppressLint("SimpleDateFormat")
String file_name = new SimpleDateFormat("yyyy_mm_ss").format(new Date());
String new_name = "file_"+file_name+"_";
File sd_directory = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
return File.createTempFile(new_name, ".jpg", sd_directory);
}
//Creating video file for upload
private File create_video() throws IOException {
#SuppressLint("SimpleDateFormat")
String file_name = new SimpleDateFormat("yyyy_mm_ss").format(new Date());
String new_name = "file_"+file_name+"_";
File sd_directory = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
return File.createTempFile(new_name, ".3gp", sd_directory);
}
PHP that handles upload
if(isset($_FILES['photo'])){
$upload_dir = 'profile_img/'; // upload directory
$email = $_POST['email'];
$imgFile = $_FILES['photo']['name'];
$tmp_dir = $_FILES['photo']['tmp_name'];
$imgSize = $_FILES['photo']['size'];
$imgType = $_FILES['photo']['type'];
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png'); // image extensions
$vid_extensions = array('avi', 'mp4', 'wav','3gp','AAC','flv','wmv'); // video extensions
$aud_extensions = array('mp3'); // audio extensions
// rename uploading image
$userpic = rand(1000,1000000).".".$imgExt;
if(!empty($imgFile)){
$pic = $userpic;
}else{
$pic = '';
}
if(!empty($imgFile) && in_array($imgExt, $valid_extensions)){
move_uploaded_file($tmp_dir,$upload_dir.$pic);
}
if(!empty($imgFile) && in_array($imgExt, $vid_extensions)){
move_uploaded_file($tmp_dir,$video.$pic);
}
if(!empty($imgFile) && in_array($imgExt, $aud_extensions)){
move_uploaded_file($tmp_dir,$audio.$pic);
}
$query = mysqli_query($mysqli,"UPDATE customer_login SET img = '$pic' WHERE email='$email'");
if($query){
echo 1;
}else{
echo "Error occured: ".$mysqli->error;
}
}
Uri.fromFile(photoFile))
Since Android N/7 you cannot use a file uri.
It will produce a FileUriExposedException.
Use FileProvider.getUriForFile() instead to obtain a content scheme uri.

Use PHP function to override default JSON target with Array

We built an API to directly access other social networks APIs using our keys.
I'm trying to build a fuction to access that API.
The default function has been written and is working.
Question
How can I specify a new array to target the json data?
This will override the default setting.
function SocialAPI($handle, $service, $path="") {
$handle = strtolower($handle);
$service = strtolower($service);
$api = file_get_contents("https://api.service.domain.com/v1/Social?handle=$handle&service=$service");
if($api !== false) {
$data = json_decode($api, true);
if($data !== null) {
if($service === "twitter") {
return $data['0']['followers_count'];
}
if($service === "instagram") {
if(!empty($path)) {
while($id = array_shift($path)) {
echo $data[$id];
}
return $data;
} else {
return $data['user']['followed_by']['count'];
}
}
} else {
return false;
}
} else {
return "API call failed.";
}
}
//Test API Function - ** TO BE DELETED **
echo SocialAPI("JohnDoe", "Instagram", "['user']['full_name']");
exit();
function array_deref($data, $keys) {
return empty($keys) ? $data
: array_deref($data[$keys[0]], array_slice($data, 1))
}
function SocialAPI($handle, $service, $path="") {
$handle = strtolower($handle);
$service = strtolower($service);
$api = file_get_contents("https://api.service.domain.com/v1/Social?handle=$handle&service=$service");
if ($api === false) {
return "API call failed.";
}
$data = json_decode($api, true);
if($data !== null) {
return false;
}
if ($service === "twitter") {
if (empty($path)) $path = ['0','followers_count'];
return array_deref($data, $path);
} elseif ($service === "instagram") {
if (empty($path)) $path = ['user','followed_by'];
return array_deref($data, $path);
}
}
//Test API Function - ** TO BE DELETED **
echo SocialAPI("JohnDoe", "Instagram", ['user', 'full_name']);
echo SocialAPI("JohnDoe", "Instagram");
exit();
I added a utility function, array_deref, to walk the arrays recursively (calls itself to handle each level down).

Image not moving to proper folder zend framework2

I started working on Zend Framework image upload.The code is not showing any errors but image not moving to proper destination.
public function uploadAction()
{
error_reporting(E_ALL);
ini_set('display_errors', 1);
$form = new UploadForm();
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost())
{
$profile = new Upload();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
//print_r($data);die;
//set data post and file ...
$form->setData($data);
if ($form->isValid())
{
$favicon = $data['fileupload']['name'];
$ext = pathinfo($favicon, PATHINFO_EXTENSION);
$faviconnewname = "_favicon." . $ext;
$favadapter = new \Zend\File\Transfer\Adapter\Http();
$favadapter->setDestination('public/img/upload'); //upload destination
$favadapter->addFilter('Rename', $faviconnewname, $favicon);
if($favadapter->receive($favicon))
{
echo "suceess";
}
else
{
echo "Failed";
}
die;
}
}
return array('form' => $form);
}
The image is not received and gives failed message.Can you solve this problem.Thanks in advance
You write "gives failed message" so apparently something goes wrong. You should try to find out what and why... All we can do is guess with the information you are giving inside your question.
If you read the ZF2 documentation on this file adapter class here then you can see that the adaper has a getMessages method. This might give you some insight on what actually goes wrong:
$adapter = new Zend\File\Transfer\Adapter\Http();
$adapter->setDestination('public/img/upload');
if (!$adapter->receive()) {
$messages = $adapter->getMessages();
echo implode("\n", $messages);
}
This code snippet comes straight out of the official docs!
Your final running code make sure you comment filters
public function uploadAction()
{
error_reporting(0);
$em = $this->getEntityManager();
$form = new UploadForm($em);
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost())
{
$profile = new Upload();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
//print_r($data);die;
//set data post and file ...
$form->setData($data);
if ($form->isValid())
{
$favicon = $data['fileupload']['name'];
$ext = pathinfo($favicon, PATHINFO_EXTENSION);
$faviconnewname = "_favicon." . $ext;
$favadapter = new \Zend\File\Transfer\Adapter\Http();
$favadapter->setDestination('public/img/upload/'); //upload destination
//$favadapter->addFilter('Rename', $faviconnewname, $favicon);
if (!$favadapter->receive())
{
$messages = $adapter->getMessages();
echo implode("\n", $messages);
}
else
{
echo "success";
}
// die;
}
}
// if ($request->isPost())
// {
// $fname = $_FILES['fileupload']['name'];
// $tmp_name = $_FILES["fileupload"]["tmp_name"];
// $uploads_dir = 'public/img/upload';
// if(move_uploaded_file($tmp_name,"$uploads_dir/$fname"))
// {
// echo "Uploaded";
// }
// else
// {
// echo "Error";
// }
// }
return array('form' => $form);
}

Inserting uploaded filenames into database table

I am trying to insert uploaded filenames to a table with the date they were uploaded, but I am running into some errors with trying to get the values of the filename with $_FILES
Here is my code:
public function uploadAction()
{
if (!$user = $this->identity()) {
return $this->redirect()->toUrl('/login/log');
}
$user = $this->identity();
$layout = $this->layout();
$layout->setVariable('user1', $user->username);
$form = new FileUploadForm();
$request = $this->getRequest();
if ($request->isPost()) {
$file = new File();
$form->setInputFilter($file->getInputFilter());
$captions = $request->getPost()->toArray();
$get_file = $this->params()->fromFiles('file');
$data = array_merge_recursive($this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray());
$form->setData($data);
if ($form->isValid()) {
$size = new Size(array('min' => '10kB', 'max' => FileHandler::FILESIZE . 'MB'));
$extension = new Extension(array('jpg', 'jpeg', 'png'), true);
$adapter = new Http();
$adapter->setValidators(array($size, $extension), $get_file['name']);
if (!$adapter->isValid()) {
return $this->redirect()->toUrl('/admin/upload-failure');
} else {
$dir_check = !is_dir(FileHandler::UPLOAD_PATH . $user->username)
?
mkdir(FileHandler::UPLOAD_PATH . $user->username) ? FileHandler::UPLOAD_PATH . $user->username : null
: FileHandler::UPLOAD_PATH . $user->username;
$adapter->setDestination($dir_check);
if ($adapter->receive($get_file['name'])) {
$this->getFileUploadFactory()->insertUploadDate($_FILES);
$file->exchangeArray($form->getData());
return $this->redirect()->toUrl('/admin/upload-success');
} else {
return $this->redirect()->toUrl('/admin/upload-failure');
}
}
}
}
public function insertUploadDate(array $file)
{
try {
$insert = new Insert('uploads');
foreach ($file as $key => $value) {
$insert->columns(array('filename', 'upload_date'))
->values(array('filename' => $value, 'upload_date' => date('Y-m-d')));
$adapter = $this->table_gateway->getAdapter();
$adapter->query(
$this->sql->getSqlStringForSqlObject($insert),
$adapter::QUERY_MODE_EXECUTE
);
}
return true;
} catch (\PDOException $e) {
// save the exception message to the error file
$writer = new Stream(self::ERROR_PATH);
$logger = new Logger();
$logger->addWriter($writer);
$logger->info($e->getMessage() . "\r\r");
return false;
}
}
and then in the controller I am calling it like this:
$this->getFileUploadFactory()->insertUploadDate($_FILES);
Like I said, it's not inserting the correct names of the files I uploaded (using html5 multiple upload option)
Thanks!

PHP file path updating after unlink the previous file

In my php file using file uploading control. After unlink previous file and update with new file it's not getting update with new image file. It's showing previous image in listing, when i refresh it's showing new image. Using both listing and update screen in single php file. I used the document cache clear. Even it's not working.
<?php
require_once("../config/config.php");
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
<?php
require_once("../images.inc.php");
if(Tools::isLoggedIn('admin') == false)
{
Tools::redirectTo($link->rewrite_link(array("template"=>ADMIN_URI."index")));
}
$id_product = (Tools::getVar("id_product")) ? Tools::getVar("id_rpoduct") : 0;
$page = intval(Tools::getVar("page"));
$product = new Product($id_product);
if(Tools::isSubmit("OnSave"))
{
$id_product = Tools::getVar("id_product");
$product = new Product($id_product);
$product->name = Tools::getVar("name");
$product->id_category = Tools::getVar("id_category");
$product->short_description = Tools::getVar("short_description");
$product->code = Tools::getVar("code");
$product->weight = Tools::getVar("weight");
$product->price = Tools::getVar("price");
$product->size = Tools::getVar("size");
$product->meta_title = Tools::getVar("meta_title");
$product->meta_description = Tools::getVar("meta_description");
$product->meta_keyword = Tools::getVar("meta_keyword");
$product->status = Tools::getVar("status");
if(($product->name)=="")
{
$errors['err_name'] = "Name is required";
}
if(($product->short_description)=="")
{
$errors['err_short_description'] = "Description is required";
}//edit on
if($product->id_category <= 0)
{
$errors['err_id_category'] ="Parent Category is required";
}
if($product->code == '')
{
$errors['err_code'] ="Product Code is required";
}
if(sizeof($errors) == 0)
{
if($id_product) {
$product->date_upd = date('Y-m-d H:i:s');
if(isset($_FILES) AND sizeof($_FILES) AND $_FILES['image']['name'] != NULL && $id_product) {
$postimage = $product->postImage($id_product);
}
if($product->update())
{
$redirect = array("template"=>ADMIN_URI."product");
$session->set("success","Product Updated Successfully");
Tools::redirectTo($link->rewrite_link($redirect));
}
else {
$errors['fail'] ="Please Try again Later";
}
}
else {
$product->date_add = date('Y-m-d H:i:s');
$product->date_upd = date('Y-m-d H:i:s');
$id_product = $product->add(DB::RETURN_INSERT_ID);
if(isset($_FILES) AND sizeof($_FILES) AND $_FILES['image']['name'] != NULL && $id_product) {
$product->postImage($id_product);
}
if($id_product){
$redirect = array("template"=>ADMIN_URI."product");
$session->set("success","Product Added Successfully");
Tools::redirectTo($link->rewrite_link($redirect));
}
else {
$errors['fail'] ="Please Try again Later";
}
}
}
}
if(Tools::getVar('action') == 'delete' && Tools::getVar('id_product') )
{
$id_product = Tools::getVar('id_product');
$product = new Product($id_product);
if($product->delete()) {
$session->set("success","Product Deleted successfully");
Tools::redirectTo($link->rewrite_link(array("template"=>ADMIN_URI."product")));
}
else {
$errors['fail'] ="Please Try again Later";
}
}
if(Tools::getVar('action') == "status_change" && Tools::getVar('id_product'))
{
$id_product = Tools::getVar('id_product');
$product = new Product($id_product);
$product->status =Tools::getVar("status");
$product->update();
$session->set("success","Status updated successfully");
Tools::redirectTo($link->rewrite_link(array("template"=>ADMIN_URI."product")));
}
require_once("header.php");
?>
My Image upload class like,
<?php
class Product extends ObjectModel
{
protected function uploadImage($id, $name, $dir, $ext = false)
{
if (isset($_FILES[$name]['tmp_name']) AND !empty($_FILES[$name]['tmp_name']))
{
// Delete old image
if (file_exists($dir.$id.'.'.$this->imageType)) {
$imagesTypes = $this->productImageTypes;
foreach ($imagesTypes AS $k => $imageType)
{
if (file_exists($dir.$id.'-'.stripslashes($imageType['name']).'.jpg'))
{
unlink($dir.$id.'-'.stripslashes($imageType['name']).'.jpg');
}
}
unlink($dir.$id.'.'.$this->imageType);
}
// Check image validity
if ($error = checkImage($_FILES[$name], $this->maxImageSize))
$_errors[] = $error;
elseif (!$tmpName = tempnam(TEMP_DIR, 'SST') OR !move_uploaded_file($_FILES[$name]['tmp_name'], $tmpName))
return false;
else
{
$_FILES[$name]['tmp_name'] = $tmpName;
// Copy new image
if (!imageResize($tmpName, $dir.$id.'.'.$this->imageType, NULL, NULL, ($ext ? $ext : $this->imageType)))
$_errors[] = Tools::displayError('An error occurred while uploading image.');
else {
$imagesTypes = $this->productImageTypes;
foreach ($imagesTypes AS $k => $imageType)
imageResize($dir.$id.'.jpg', $dir.$id.'-'.stripslashes($imageType['name']).'.jpg', (int)($imageType['width']), (int)($imageType['height']));
}
if (sizeof($_errors))
return false;
else
{
unlink($tmpName);
return true;
}
return false;
}
}
return true;
}
}
Assuming that your browser is displaying a cached version of the image since your saving new data to the same file name, try appending a query string containing a randomized string or timestamp to the image url when generating the HTML to display it. Something like this:
PHP
$image_tag='<img src="image-file.jpg?t='.timestamp().'" />';
This should make the browser fetch a fresh version of the image instead of using it's cached version.

Categories