move_uploaded_file for different input files - php

the method I have is I create three input files which will be posted to three different column in database table.
Heres my parameter:
$additional_comments=$_POST['additional_comments'];
$image_one = $_FILES['image_one']['type'];
$image_two = $_FILES['image_two']['type'];
$image_three = $_FILES['image_three']['type'];
if($image=="image/jpeg" || $image=="image/jpg" || $image=="image/gif" || $image=="image/png")
{
$gambar_satu = $foldername . basename($_FILES['image_one']['name']);
$gambar_dua = $foldername . basename($_FILES['image_two']['name']);
$gambar_tiga = $foldername . basename($_FILES['image_three']['name']);
if ( move_uploaded_file
($_FILES['image']['tmp_name'], $gambar_satu)
($_FILES['image']['tmp_name'], $gambar_dua)
($_FILES['image']['tmp_name'], $gambar_tiga)
)
{
$stmt = $mysqli->prepare
("INSERT INTO table...
In the if (move_uploaded_file... I am trying to insert three paramater there which they are $gambar_satu, $gambar_dua, $gambar_tiga.
My question is how is the correct way to do this? Thanks in advance.

Quoting directly from the php website
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>
Hope it helps!

Related

Foreach loop not working properly in my Laravel 9 Code?

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.

PHP Delete Multiple File Image in folder

I have trouble when i want delete Multiple File Image in folder, i can delete the image in folder but just 1 image, other image can't delete in folder although in DB the image is 1 id, this my script
if (ISSET($_POST['remove_product'])) {
require("../koneksi.php");
$id = $_POST['id'];
$cari=mysql_query("select * from t_productimage where id_product='$id'");
$dt=mysql_fetch_array($cari);
$gmbr=$dt['image'];
$tmpfile = "../images_product/$gmbr";
$sql=mysql_query("DELETE a.*, b.*, c.* FROM t_product a, t_productsize b, t_productimage c WHERE a.id = '$id' AND b.id_product = '$id' AND c.id_product = '$id'");
if(!$sql){
echo '<script language="javascript" type="text/javascript">
alert("delete gambar gagal !");</script>';
echo "<meta http-equiv='refresh' content='0; url=home.php?p=product'>";
}else{
unlink ($tmpfile);
echo "<meta http-equiv='refresh' content='0; url=home.php?p=product'>";
}
exit();
}
thks a lot for responsed
The use of mysql is no longer recommended as it has been deprecated for some time and the code is vulnerable to sql injection, but you could try like this.
Fetch the results and then iterate though using a simple loop and use the returned value to populate an array which can then be used to display a message or redirect as you see fit.
You ought to however look into using mysqli or PDO in conjunction with prepared statements
if( isset( $_POST['remove_product'] ) ) {
require("../koneksi.php");
$id = $_POST['id'];
$results=array();
$cari=mysql_query("select * from t_productimage where id_product='$id'");
if( $cari ){
while( $dt=mysql_fetch_array( $cari ) ){
$gmbr = $dt['image'];
$tmpfile = "../images_product/$gmbr";
$results[ $gmbr ]=#unlink( $tmpfile );
}
$result=mysql_query("DELETE
a.*,
b.*,
c.*
FROM
t_product a,
t_productsize b,
t_productimage c
WHERE
a.id = '$id' AND b.id_product = '$id' AND c.id_product = '$id'");
$results['product-deleted']=$result;
}
if( !empty( $results ) ){
foreach( $results as $key => $status ){
printf('<div>%s -> %s</div>', $key, $status ? 'deleted' : 'error' );
}
}
}
Using following function, you can delete multiple images or images in multi level folder structure like given example:
**folders**
folder1/d1 f1.png
folder1/d1 f2.png
folder1/file.png
deleted -file.png
folder1/folder2
folder1/folder2/d2 f1.png
folder1/folder2/d2 f2.png
folder1/folder2/file.png
deleted -file.png
folder1/folder2/folder 3
folder1/folder2/folder 3/d3 f1.png
folder1/folder2/folder 3/d3 f2.png
folder1/folder2/folder 3/file.png
deleted -file.png
rrmdir('folder1');
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir . "/" . $object) == "dir") {
echo $dir . "/" . $object . '<br>';
rrmdir($dir . "/" . $object);
} else {
// unlink($dir . "/" . $object);
echo $dir . "/" . $object . '<br>';
if ($object == 'file.png') {
echo "deleted -" . $object . '<br>';
unlink($dir . "/" . $object);
}
}
}
}
reset($objects);
// rmdir($dir);
}
}

When import CSV skip header or first row

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

How to upload multiple image with rename in php and insert database?

Hi how to upload multiple image in php with rename and insert databse?
my code is below but not rename and insert 1 rows in datase.
$uploads_dir = 'uploaded/up/';
foreach ($_FILES["layout_plan_no_of_images"]["error"] as $i => $k) {
if ($k == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["layout_plan_no_of_images"]["tmp_name"][$i];
$name = $_FILES["layout_plan_no_of_images"]["name"][$i];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
$sql="INSERT INTO projects (layout_plan_no_of_images)VALUES(':layout_plan_no_of_images')";
$sql_result = $db->queryPrepared($sql, array(
':layout_plan_no_of_images' => $_FILES['layout_plan_no_of_images']['name']
));
Hi try to below code may be help for with rename
foreach($_FILES["layout_plan_no_of_images"]['name'] as $key=>$tmp_name){
$file_name=$_FILES["layout_plan_no_of_images"]["name"][$key];
$file_tmp=$_FILES["layout_plan_no_of_images"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
$filename=basename($file_name,$ext);
$newFileName=(string)$filename.time().".".$ext;
move_uploaded_file($file_tmp=$_FILES["layout_plan_no_of_images"]["tmp_name"][$key],"uploaded/".$newFileName);
$concateFiles .= $comma.$newFileName;
$comma = ',';
}
$sql="INSERT INTO projects (`layout_plan_no_of_images`, `pid`)VALUES($concateFiles)";
$sql_result = $db->queryPrepared($sql, array(
':layout_plan_no_of_images' => $concateFiles,
));

How to insert "Null" value in MySQL Database Cell if no Files are added?

I have a form that sends input data to corresponding field on MYSQL database.Right now I have it setup where any files that are uploaded are packaged in a zip and placed in the "uploads" folder while it sends to the database the file name/location. How do I make it where when the user uploads no files it sends to the database as NULL result in the corresponding database "file" cell and no zip file is sent to the "uploads" folder ?
**UPDATE: OK I started with suggested answer but don't get "NULL" when no file is uploaded just the usual that I have written.I tried an if/else statement and it's the same. What am i doing wrong?
This what the array looks like when no file is uploaded: Array (
[name] => Array ( [0] => ) [type] => Array ( [0] => ) [tmp_name] =>
Array ( [0] => ) [error] => Array ( [0] => 4 ) [size] => Array ( [0]
=> 0 ) )
The error field contains 4. i think this might the reason why its not working.I don't understand why this error field has this number. Any suggestions please?
PHP
<?php
$project = $_POST['project'];
$assignto = $_POST['assignto'];
$asdate = $_POST['asdate'];
$chdate = $_POST['chdate'];
$ddate = $_POST['ddate'];
$notes = $_POST['notes'];
$asdate=date('Y-m-d', strtotime($asdate));
$chdate=date('Y-m-d', strtotime($chdate));
$ddate=date('Y-m-d', strtotime($ddate));
$timestamp = time();
if (isset ($_POST['submit']))
{
$filesArray= $_FILES["files"];
for ($num=0; $num<count($filesArray["name"]);$num++)
{
$fileName = $filesArray["name"][$num];
$tempName= $filesArray["tmp_name"][$num];
move_uploaded_file($tempName,"tmp/".$fileName);
}
$archiveName= $timestamp.".zip";
$filesArrayNames= $_FILES["files"]["name"];
$zipsDir= scandir ("uploads/");
$error = false;
foreach($zipsDir as $zipDirfile)
{
if($zipDirfile == $archiveName)
{
$error= true ;
break;
}
}
if ($error== false)
{
$tmpDir = scandir ("tmp/");
$zip = new ZipArchive;
$zip->open("uploads/".$archiveName, ZipArchive::CREATE);
for ($num =0; $num<count($filesArray["name"]);$num++)
{
$fileName = $filesArray["name"][$num];
foreach($tmpDir as $tmpDirfile)
{
if($tmpDirfile == $fileName)
{
$zip->addFile("tmp/".$fileName);
echo " Adding: ".$fileName."<br/>";
}
}
}
$zip->close();
for ($num=0; $num<count($filesArray["name"]);$num++)
{
$fileName = $filesArray["name"][$num];
foreach($tmpDir as $tmpDirFile)
{
if($tmpDirfile == $fileName)
{
unlink("tmp/".$fileName);
}
}
}
}
else
{
echo "Name already exists";
}
} if (!empty($filesArray)) {
$filepath = "NULL";
}else
{$filepath = addslashes("https://docs.google.com/viewer?url=www.art.com/uploads/".$archiveName.""); }
print_r($filepath);
mysql_connect("tre.com","amadast","ufco1954") or die ('Error:' .mysql_error());
//database connection
mysql_select_db("mediamanagement");
$sql = "INSERT INTO demo (`name`, `id_continent`, `lastvisit`, `cdate`, `ddate`, `file`,`notes`)
VALUES ('".$project."', '".$assignto."','".$asdate."','".$chdate."','".$ddate."','".$filepath."','".$notes."')";
mysql_query($sql);
header('Location: edit-projects.html');
?>
Where you create the $filepath variable, simply check whether you have files uploaded, and if you don't use "NULL" as the content.
For example:
$filepath = addslashes("https://docs.google.com/viewer?url=www.amada-stage.com/uploads/".$archiveName."");
if (empty($filesArray)) {
$filepath = "NULL";
}
You can do a similar thing to prevent the upload occuring:
Change
if ($error== false)
to
if ($error == false && !empty($filesArray))
BTW: I hope those aren't real database credentials in your mysql_connect line!

Categories