I am using following script to upload images. Here is the link : http://filer.grandesign.md/
Using this script It's allowing the preview after upload the image. Like bellow image :
You can see that, it's also allowing to delete the Image - See red bucket icon
What I am doing now :
When I upload the image I renamed the uploaded image and save it to database.
The code is bellow :
require_once('class.upload.php');
if(!isset($_FILES['files'])) {
die();
}
$files = array();
foreach ($_FILES['files'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
foreach ($files as $file) {
$handle = new upload($file);
if ($handle->uploaded) {
$handle->file_new_name_body = 'mpic_list_'.uniqid('', true);
$menu_list_image = $handle->file_new_name_body;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 360;
$handle->image_y = 240;
$handle->process('images/menu_images/');
$handle->file_new_name_body = 'mpic_small_'.uniqid('', true);
$menu_small_image = $handle->file_new_name_body;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 100;
$handle->image_y = 65;
$handle->process('images/menu_images/');
$handle->file_new_name_body = 'mpic_large_'.uniqid('', true);
$menu_large_image = $handle->file_new_name_body;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 700;
$handle->image_y = 470;
$handle->process('images/menu_images/');
if ($handle->processed) {
$all_images = $menu_list_image . $menu_small_image . $menu_large_image;
$u_id = (int) $_SESSION['logged_user_id'];
if(!isset($_SESSION['last_id'])) {
// insert upload image section data...
$insert_menu_details = mysqli_query($conn, "INSERT INTO products (p_id) VALUES ('')");
$last_id = mysqli_insert_id($conn);
$insert_upload_image = mysqli_query($conn, "INSERT INTO product_images VALUES ('', '$menu_large_image', '$menu_list_image', '$menu_small_image', '$last_id', '$u_id')");
$_SESSION['last_id'] = $last_id;
} else {
// update upload image section data
$session_last_id = $_SESSION['last_id'];
$update_upload_image = mysqli_query($conn, "INSERT INTO product_images VALUES ('', '$menu_large_image', '$menu_list_image', '$menu_small_image', '$session_last_id', '$u_id')");
}
$handle->clean();
} else {
//echo 'error : ' . $handle->error;
echo 'Error';
}
}
}
What I need :
Now I want to delete my uploaded image. But here is an issue which is : by default this script is deleting the uploaded image using following PHP line :
<?php
if(isset($_POST['file'])){
$file = 'images/menu_images/' . $_POST['file'];
if(file_exists($file)){
unlink($file);
}
}
?>
But I can't delete it because when I upload the image to folder (images/menu_images/) I renamed it to something like that : abedkd12415775554.jpg
My Question is How can I delete my uploaded image using this script ?
You need to return the new images name that you are generating from server scripting like-
In the loop you are executing for inserting filename in database-
$array = array("oldName" => "newName");
echo json_encode($array);
You can also use numeric index if you are using some logic at your javascript end for creating array.
In javascript on delete option you can retrieve the value by using the image name and can perform delete.
check this
$res=mysqli_query("SELECT file FROM tbl_uploads WHERE id=".$_GET['remove_id']);
$row=mysqli_fetch_array($res);
mysqli_query("DELETE FROM tbl_uploads WHERE id=".$_GET['remove_id']);
unlink("uploads/".$row['file']);
Replace Your table and id name
Related
Screen Shot of HTML Form.
Can you suggest me where am I doing mistakes in my Laravel app, each time i am uploading multiple files throug the form, files is uploading perfectly in given location, but only 1 records are being inserted into database table. Here is my code...
// Upload bg_certificateArr photo
if ($request->hasFile('bg_certificate')) {
foreach ($request->file('bg_certificate') as $key => $file) {
// Get image extention
$extention = $file->getClientOriginalExtension();
// Generate new image name
$bgCertImgName = 'ac-bg-cert-' . date('Y-m-d-H-i-s') . '.' . $extention;
$bgCertImgPath = 'accountant/images/bank_guarantee/' . $bgCertImgName;
// Upload Profile Image
Image::make($file)->save($bgCertImgPath);
// Insert data into bank guarantee table
$bg_amountArr = $data['bg_amount'];
$bg_numberArr = $data['bg_number'];
$bank_idArr = $data['bank_id'];
$bg_from_dateArr = $data['bg_from_date'];
$bg_to_dateArr = $data['bg_to_date'];
$bg_amount = $bg_amountArr[$key];
$bg_number = $bg_numberArr[$key];
$bank_id = $bank_idArr[$key];
$bg_from_date = $bg_from_dateArr[$key];
$bg_to_date = $bg_to_dateArr[$key];
// echo '<pre>';
// print_r($bg_to_date);
// die();
$ac_bg->school_id = $schoolID;
$ac_bg->ledgers_id = $acLedger->id;
$ac_bg->bg_amount = $bg_amount;
$ac_bg->bg_number = $bg_number;
$ac_bg->bank_id = $bank_id;
$ac_bg->bg_from_date = $bg_from_date;
$ac_bg->bg_to_date = $bg_to_date;
$ac_bg->bg_certificate = $bgCertImgName;
$ac_bg->save();
}
}
initialize $ac_bg for every foreach loop.
if ($request->hasFile('bg_certificate')) {
foreach ($request->file('bg_certificate') as $key => $file) {
$ac_bg = new AccountBankGuarantee; // like this
// Get image extention
$extention = $file->getClientOriginalExtension();
// Generate new image name
$bgCertImgName = 'ac-bg-cert-' . date('Y-m-d-H-i-s') . '.' . $extention;
$bgCertImgPath = 'accountant/images/bank_guarantee/' . $bgCertImgName;
// Upload Profile Image
Image::make($file)->save($bgCertImgPath);
// Insert data into bank guarantee table
$bg_amountArr = $data['bg_amount'];
$bg_numberArr = $data['bg_number'];
$bank_idArr = $data['bank_id'];
$bg_from_dateArr = $data['bg_from_date'];
$bg_to_dateArr = $data['bg_to_date'];
$bg_amount = $bg_amountArr[$key];
$bg_number = $bg_numberArr[$key];
$bank_id = $bank_idArr[$key];
$bg_from_date = $bg_from_dateArr[$key];
$bg_to_date = $bg_to_dateArr[$key];
// echo '<pre>';
// print_r($bg_to_date);
// die();
$ac_bg->school_id = $schoolID;
$ac_bg->ledgers_id = $acLedger->id;
$ac_bg->bg_amount = $bg_amount;
$ac_bg->bg_number = $bg_number;
$ac_bg->bank_id = $bank_id;
$ac_bg->bg_from_date = $bg_from_date;
$ac_bg->bg_to_date = $bg_to_date;
$ac_bg->bg_certificate = $bgCertImgName;
$ac_bg->save();
}
}
You haven't posted full code here, but I believe before loop you somehow set $ac_bg variable. So looking at your code you create one record and update it in every next loop iteration.
So to fix this you should probably do something like this:
foreach ($request->file('bg_certificate') as $key => $file) {
$ac = new Ac(); // don't know what's the exact model class here
Then in every loop iteration you will create new record instead of updating it.
I have a form with a Dropzone div, for massive image uploads with another data.
But, as the images are uploaded with ajax I need to know which Id's are assigned to those images.
The problem became when I save those ids in the session data. It just saves the first and the latest ids.
For example, when I submit 4 images it returns me the second and the last id.
😒
My controller method (via Ajax):
public function store(Request $request)
{
$photos = $request->file('file');
if (!is_array($photos))
$photos = [$photos];
if (!is_dir($this->photos_path))
mkdir($this->photos_path, 0777);
for ($i = 0; $i < count($photos); $i++) {
$photo = $photos[$i];
$name = sha1(date('YmdHis') . str_random(30));
$save_name = $name . '.' . $photo->getClientOriginalExtension();
$resize_name = $name . str_random(2) . '.' . $photo->getClientOriginalExtension();
Image::make($photo)
->resize(250, null, function ($constraints) {
$constraints->aspectRatio();
})
->save($this->photos_path . '/' . $resize_name);
$photo->move($this->photos_path, $save_name);
$upload = new UploadedImages();
$upload->filename = $save_name;
$upload->resized_name = $resize_name;
$upload->original_name = basename($photo->getClientOriginalName());
$upload->user_id = Auth::id();
$upload->save();
Session::push('uploaded_images_ids', $upload->id);
}
return Response::json(['message' => 'Image saved Successfully'], 200);
}
Response with Debug bar (should response 4 ids, not 2):
You can create an array to store your image and id
Here is the idea below
$image_array = [];
for ($i = 0; $i < count($photos); $i++) {
....
array_push($image_array,['image_name' => $save_name, 'image_id' => $upload->id]);
}
I know this is duplicate question. But I have tried all the answers which I have found on the https://stackoverflow.com/ .
I think in my case I am inserting and updating data if same date match than record will update if not than it will insert.
Below is my file code:
<?php
if ( isset( $_POST['submit'] ) && $_POST['upload-csv'] == 'upload' ) {
$error = array();
$success = array();
$filename = $_FILES['file']['name'];
$filetype = wp_check_filetype( $filename );
if ( $filetype['ext'] == 'csv' && $filetype['type'] == 'text/csv' ) {
$handle = fopen( $_FILES['file']['tmp_name'], "r" );
$row = 0;
$skip_row_number = array("1");
while ( ($data = fgetcsv( $handle, 1000, "," )) !== FALSE ) {
$data = array_map("utf8_encode", $data);
if ($row > 0)
{
$table_name = $wpdb->prefix . 'prayer';
$ipquery = $wpdb->get_results("SELECT * FROM `$table_name` WHERE `date` = '".$data[0]."'");
$query_res = $wpdb->num_rows;
// Check if same date data
if($query_res >=1){
$updateQuery = "UPDATE `$table_name` SET
`date` = '".$data[0]."',
`first_start` = '".$data[1]."',
`first_end` = '".$data[2]."',
`second_start` = '".$data[3]."',
`second_end` = '".$data[4]."',
`third_start` = '".$data[5]."',
`third_end` = '".$data[6]."',
`forth_start` = '".$data[7]."',
`forth_end` = '".$data[8]."',
`five_start` = '".$data[9]."',
`five_end` = '".$data[10]."',
`done` = '".$data[10]."'
WHERE `$table_name`.`date` = '".$data[0]."';";
$up_res = $wpdb->query($updateQuery);
}else{
$query = "INSERT INTO $table_name (date, first_start, first_end, second_start,
second_end, third_start, third_end, forth_start, forth_end, five_start, five_end, done)
VALUES ('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."','".$data[4]."','".$data[5]."','".$data[6]."','".$data[7]."','".$data[8]."','".$data[9]."','".$data[10]."','".$data[11]."')";
$insert_res = $wpdb->query($query);
}
}
$row++;
}
fclose( $handle );
$success[] = 'Import done.';
} else {
$error[] = 'Please upload CSV file only';
}
}
?>
I have tried the below answer for skip the header:
Skip the first line of a CSV file
Import CSV, exclude first row
skip first line of fgetcsv method in php
Help me sort out this issue.
ParseCSV is latest and easy way to get data from CSV and you can get control of data from CSV easily.
in which you have to add library file as per proper path
e.g. require_once 'parsecsv.lib.php';
After then it return title and data seperately.
$filename = 'abc.csv'; // path of CSV file or after upload pass temp path of file
$csv = new parseCSV();
$csv->auto($filename);
foreach ($csv->titles as $value):
$getcsvtitle[] = // get header in variable
endforeach;
foreach ($csv->data as $key => $row):
//$getdataasperrow = // get data row wise.
endforeach;
ParseCSV return data in array format after just adding library, so you can easily separate header and other data, and compatible to new line and special character as well as i have been always using it as well.
Please refer below link for further detail as well.
ParseCSV GitHub
I want to generate excel report from php,in which there are two images for each row. But the generated excel sheet show images only for the first row.
following is my used code
$pixels = 120;
$points = PHPExcel_Shared_Drawing::pixelsToPoints($pixels);
$wpixels = 95;
$wpoints = PHPExcel_Shared_Drawing::pixelsToPoints($wpixels);
while ($data = mysql_fetch_array($rsExport)) {
#extract($data);
$image_path = "../../../upload/jrf/".$img_upload;
$sign_path = "../../../upload/jrf/".$sign_upload;
$activeSheet->setCellValue("A".$rowNum, $i);
$activeSheet->setCellValue("B".$rowNum, $jrf_roll_no);
$activeSheet->setCellValue("C".$rowNum, $name);
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setPath($image_path);
$objDrawing->setCoordinates('D'.$rowNum);
$objDrawing->setResizeProportional(false);
$objDrawing->setWidth($wpoints);
$objDrawing->setWorksheet($activeSheet);
$activeSheet->getRowDimension($rowNum)->setRowHeight($points);
$activeSheet->getColumnDimension('D'.$rowNum)->setAutoSize(true);
$objDrawing1 = new PHPExcel_Worksheet_Drawing();
$objDrawing1->setPath($sign_path);
$objDrawing1->setCoordinates('E'.$rowNum);
$objDrawing1->setResizeProportional(false);
$objDrawing1->setWidthAndHeight($wpoints,$points);
$objDrawing1->setWorksheet($activeSheet);
$activeSheet->getColumnDimension('E'.$rowNum)->setAutoSize(true);
$rowNum++;
$i++;
}
Using code below in module to create product and assign uploaded image to it. On localhost everything works fine, but when I move module to server I get problem. Module on server creates product successfully. But when I open on backend created product image section I get following image with question mark, (screenshot below code). When I get on ftp to img dir (/img/p/3/7/37.jpg) there is no img directory or img itself. So it looks like there is problem creating img directory. Does anyone had problem like this and can forward me where to search problem?
<?php
//Create product
$product = new Product();
$product->ean13 = 12456;
$product->name = array((int)Configuration::get('PS_LANG_DEFAULT') => 'test');
$product->link_rewrite = array((int)Configuration::get('PS_LANG_DEFAULT') => 'test');
$product->id_category = 3;
$product->id_category_default = 3;
$product->redirect_type = '404';
$product->price = 33;
$product->wholesale_price = 25;
$product->minimal_quantity = 1;
$product->show_price = 1;
$product->on_sale = 0;
$product->online_only = 1;
$product->meta_keywords = 'test';
$product->id_tax_rules_group = 0;
$product->add();
$product->addToCategories(array(3));
StockAvailable::setQuantity($product->id,'',10);
//Add main product image
$id_product = $product->id;
$url = 'http://www.webadress.com/image/product/color/0959.jpg';
$shops = Shop::getShops(true, null, true);
$image = new Image();
$image->id_product = $id_product;
$image->position = Image::getHighestPosition($id_product) + 1;
$image->cover = true; // or false;
if (($image->validateFields(false, true)) === true &&
($image->validateFieldsLang(false, true)) === true && $image->add())
{
$image->associateTo($shops);
if (!AdminImportController::copyImg($id_product, $image->id, $url, 'products', false))
{
$image->delete();
}
}
?>
If image is copied correctly, you should try (!AdminImportController::copyImg($id_product, $image->id, $url, 'products', true)) to regenrate miniatures