filenames get inserted if no file is selected during upload php - php

The script below works fine and its able to upload 5 files unto the server and insert the names into database but the only problem is when a user fails to select a file, file names are still inserted into the database
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file2 = rand(1000,100000)."-".$_FILES['file2']['name'];
$file3 = rand(1000,100000)."-".$_FILES['file3']['name'];
$file4 = rand(1000,100000)."-".$_FILES['file4']['name'];
$file5 = rand(1000,100000)."-".$_FILES['file5']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_loc2 = $_FILES['file2']['tmp_name'];
$file_loc3 = $_FILES['file3']['tmp_name'];
$file_loc4 = $_FILES['file4']['tmp_name'];
$file_loc5 = $_FILES['file5']['tmp_name'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$oname = $_POST['oname'];
$folder="uploads/";
// make file name in lower case
$new_file_name = strtolower($file);
$new_file_name2 = strtolower($file2);
$new_file_name3 = strtolower($file3);
$new_file_name4 = strtolower($file4);
$new_file_name5 = strtolower($file5);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);
$final_file2=str_replace(' ','-',$new_file_name2);
$final_file3=str_replace(' ','-',$new_file_name3);
$final_file4=str_replace(' ','-',$new_file_name4);
$final_file5=str_replace(' ','-',$new_file_name5);
if(move_uploaded_file($file_loc,$folder.$final_file))
if(move_uploaded_file($file_loc2,$folder.$final_file2))
if(move_uploaded_file($file_loc3,$folder.$final_file3))
if(move_uploaded_file($file_loc4,$folder.$final_file4))
if(move_uploaded_file($file_loc5,$folder.$final_file5))
{
}
else
{
}
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form")) {
$insertSQL = sprintf("INSERT INTO applicant(fname,lname,oname,file1,file2,file3,file4,file5) VALUES('$fname','$lname','$oname','$final_file','$final_file2','$final_file3','$final_file4','$final_file5')");
}
What i want to achieve is when no file is selected, the field should be null

It's inserting this:
rand(1000,100000)."-"

Related

Please I want to upload two files simultaneously and add info to mySQL

Please I want to upload two files simultaneously and add info to mySQL, I dont know where i'm doing it wrong. Please help me out here, below is my code
`
$name = $_POST['music_name'];
$uploader = $_POST['music_uploader'];
$artist = $_POST['music_artist'];
$lyrics = $_POST['music_lyrics'];
$file = (starz_hit_cf)."-".$_FILES['file']['name'];
$art = (art_for)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$art_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="../downloads/";
$art_hold="../../assets/img/arts/";
// new file size in KB
$new_size = $file_size/1024;
// new file size in KB
// make file name in lower case
$new_file_name = strtolower($file);
$new_art_name = strtolower($art);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);
$final_art=str_replace(' ','-',$new_art_name);
$date =date('Y-m-d H:i:s');
if(move_uploaded_file($file_loc,$folder.$final_file))
if(move_uploaded_file($art_loc,$art_hold.$final_art))
{
$sql="INSERT INTO tbl_music (musicName,musicUploader,musicArtist,musicLyrics,musicfile,musicArt,musicType,musicSize,musicDate) VALUES('$name','$uploader','$lyrics','$final_file','$final_art','$file_type','$new_size','$date')";
mysql_query($sql);
?>
<script>
alert('successfully uploaded');
window.location.href='index?success';
</script>
<?php
}
else
{
?>
<script>
alert('error while uploading file');
window.location.href='index?fail';
</script>
<?php
}
}
?>
Your kind reply is appreciated Thanks.

Changing php image upload filename to a specific name

I want to change the uploaded image filename to a certain name for example:
Original name:city.jpg -> D0000_04042018094730121.jpg (D0000 is kodeDosen and the other is a microtime timestamp.)Here is my php code:uploadDosen.php
<?php
include 'connectdb.php';
if (isset($_POST['upload_Btn'])) {
$target = "uploaddosen/".basename($_FILES['gambar']['name']);
$kodeDosen = $_POST['kodeDosen'];
$namaJurnal = $_POST['namaJurnal'];
$tipePublikasi = $_POST['tipePublikasi'];
$status= $_POST['status'];
$gambar = $_FILES['gambar']['name'];
$sql = "INSERT INTO tbl_publikasi (kodeDosen,gambar,namaJurnal,tipePublikasi,status) VALUES ('$kodeDosen','$gambar','$namaJurnal',
'$tipePublikasi','$status')";
// execute query
mysqli_query($conn, $sql);
if (move_uploaded_file($_FILES['gambar']['tmp_name'],$target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
header("location:uploadTest.php");
}
?>
Instead of using
$target = "uploaddosen/".basename($_FILES['gambar']['name']);
Put your desired name in
$ext = end((explode(".", $_FILES['gambar']['name'])));
$target = "uploaddosen/MYNEWNAME." . $ext
$ext is taking the uploaded file name and getting the file extension. Then adding it together with your new name.
Just change the value of $target to your preferred filename.
You can try:
$extention = explode(".", $_FILES['gambar']['name']);
$extention = end($extention);
$target = $kodeDosen."_".str_replace(array(".", " "), "", microtime() ).".".$extention;

Cannot update file upload form, still no proccess to database in php

my script aims to edit the uploaded files in the database, but when I run my script, the editing process is not running, if there are any additional scripts or there are any of my scripts? help me please.
<?php
require 'config.php';
if(isset($_POST['btn-edit']))
{
$tgl = $_POST['tgl'];
$no_surat = $_POST['no_surat'];
$perihal = $_POST['perihal'];
$asal_surat = $_POST['asal_surat'];
$tujuan_surat = $_POST['tujuan_surat'];
$no_rak = $_POST['no_rak'];
$no_index = $_POST['no_index'];
$jenis_surat = $_POST['jenis_surat'];
$file = $_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="uploads/";
$new_size = $file_size/1024;
$final_file = strtolower($file);
if(move_uploaded_file($file_loc,$folder.$final_file))
{
$sql="update surat set tgl = '$tgl', no_surat = '$no_surat', perihal = '$perihal', asal_surat = '$asal_surat', tujuan_surat = '$tujuan_surat', no_rak = '$no_rak', no_index = '$no_index', file = '$final_file', jenis_surat = '$jenis_surat' WHERE id = '$id'";
mysql_query($sql);
header('location:index.php?act=update');
}
else
{
header('location:index.php?act=fail');
}
}
?>

PHP assign each multiple uploaded files to variable

How can I separate multiple uploaded files ($new_file_name) out of foreach loop for sql query process? How to assign each files to its variable?
// manipulate uploaded images
if(isset($_FILES['files'])){
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name){
$file_name = $key.'_'.$_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
//explode fine name and extension
$ext_x = explode('.', $_FILES['files']['name'][$key]);
$ext = strtolower(end($ext_x));
$file_name = str_replace('.'.$ext, '', $_FILES['files']['name'][$key]);
//new file name
$output_dir = '../items/'.$list_id;
$new_file_name = rand(1, 999999).'.'.$ext;
$pathfile = $output_dir.'/'.$new_file_name;
// create directory if does not exist
if(is_dir($output_dir) == false){
mkdir($output_dir, 0700);
}
if(is_dir($pathfile) == false){
if(move_uploaded_file($file_tmp, $pathfile)){
//resize original image
WideImage::load($pathfile)->resize(300, 400)->saveToFile($pathfile);
//generate thumbnail
$split = explode('.', $new_file_name);
$thumb = $split[0].'_t.'.$split[1];
WideImage::load($pathfile)->resize(70, 70)->saveToFile($output_dir.'/'.$thumb);
}
}
}
}
//here I needed to get each of the uploaded images to update database (max 3 images)
//how to explode above $new_file_name into variable here?
$new_file_name1 = $new_file_name[0]; //and so on...
$q = $mysqli->query("UPDATE `listing` SET image1='".$new_file_name1."', image2='".$new_file_name2."', image3='".$new_file_name3."', thumbnail='".$thumb1."', WHERE list_id='".$list_id."' AND user_id='".$user_id."'") or die($mysqli->error);
I can get each of the file by
$var0 = $_FILES['files']['name'][0];
$var1 = $_FILES['files']['name'][1];
$var2 = $_FILES['files']['name'][2];
but I can't
$var0 = $new_file_name[0];
$var1 = $new_file_name[1];
$var2 = $new_file_name[2];
Thanks for advise!
Use this to set the name:
$new_file_name[] = rand(1, 999999).'.'.$ext;
and inside the for loop use:
end($new_file_name)
for the current file. E.g:
$pathfile = $output_dir.'/'.end($new_file_name);
The problem you are having is because in every iteration through the loop you setup the $new_file_name to a new random string. By using $new_file_name[] you are adding an element to $new_file_name which is then becoming an array. Using the end() functions returns the last element of the array so in the current iteration of the loop it will return the last added random string which corresponds to your current file;
EDIT:
// manipulate uploaded images
if(isset($_FILES['files'])){
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name){
$file_name = $key.'_'.$_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
//explode fine name and extension
$ext_x = explode('.', $_FILES['files']['name'][$key]);
$ext = strtolower(end($ext_x));
$file_name = str_replace('.'.$ext, '', $_FILES['files']['name'][$key]);
//new file name
$output_dir = '../items/'.$list_id;
$new_file_name[] = rand(1, 999999).'.'.$ext;
$pathfile = $output_dir.'/'.end($new_file_name);
// create directory if does not exist
if(is_dir($output_dir) == false){
mkdir($output_dir, 0700);
}
if(is_dir($pathfile) == false){
if(move_uploaded_file($file_tmp, $pathfile)){
//resize original image
WideImage::load($pathfile)->resize(300, 400)->saveToFile($pathfile);
//generate thumbnail
$split = explode('.', end($new_file_name));
$thumb = $split[0].'_t.'.$split[1];
WideImage::load($pathfile)->resize(70, 70)->saveToFile($output_dir.'/'.$thumb);
}
}
}
}
//Getting the variables
$new_file_name1 = $new_file_name[0]; //and so on...
$q = $mysqli->query("UPDATE `listing` SET image1='".$new_file_name1."', image2='".$new_file_name2."', image3='".$new_file_name3."', thumbnail='".$thumb1."', WHERE list_id='".$list_id."' AND user_id='".$user_id."'") or die($mysqli->error);
You could also use: $new_file_name[0] inside the SQL query.

Upload images and file extension missing on mysql field

I have this piece of code that executes a multi image upload and renaming it.
it works, The file is renamed correctly, but I do not understand why in the mysql database I do not have the file extension but only the name.
Example:
file name (folder): abcdefg.jpg
pd_image (mysql field): abcdefg
$resultname is the same for both
$mainame = $handle->file_dst_name;
$db_name = str_replace(" ","_",$mainame);
$image = md5(rand() * time()) . ".$db_name";
$parts = explode(".",$image);
$extension = end($parts);
$resultname = str_replace("." . $extension,"",$image);
$handle->file_new_name_body = $resultname;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 800;
$handle->image_y = 600;
$handle->Process($dir_dest);
// we check if everything went OK
if ($handle->processed) {
header("Location: index.php"); //echo 'image resized';
$handle->clean();
$query_img="INSERT into tbl_images (pd_id, file_name, pd_image) VALUES('$pd_id','$mainame','$resultname')";
$result2 = dbQuery($query_img);
I am using the class "class.upload.php"
Check this line, You are replacing the extension with the "".
$resultname = str_replace("." . $extension,"",$image);
Replace this line to
$resultname = $image.'.'.$extension;
your are giving variable $db_name as string.Correct way to concatenate the variable to another string is
$image = md5(rand() * time()).$db_name;

Categories