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;
Related
i have this weird problem never faced it before. the code is working fine when i upload a small file but when i upload larg file (105mb) the query dose not work and gives me this output
MySQL server has gone away - 2006 ../uploads/sermons/2019.03.08-Bro-GK.mp3
$uploadDirectory = "../uploads/sermons/";
require '../includes/config.php'; // this contains the connection ($conn)
$errors = []; // Store all foreseen and unforseen errors here
$fileExtensions = ['mp3','wav']; // Get all the file extensions
$fileName = $_FILES['file']['name'];
$fileSize = $_FILES['file']['size'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileType = $_FILES['file']['type'];
$fileExtension = explode('.',$fileName);
$fileExtension = end($fileExtension);
$fileExtension = strtolower($fileExtension);
$uploadPath = $uploadDirectory . basename($fileName);
if (! in_array($fileExtension,$fileExtensions)) {
$errors[] = "This file extension is not allowed. Please upload a mp3 or wav file";
}
if (empty($errors)) {
$didUpload = move_uploaded_file($fileTmpName, $uploadPath);
if ($didUpload) {
$title = mysqli_real_escape_string($conn,$_POST["Title"]);
$speaker = mysqli_real_escape_string($conn,$_POST["Speaker"]);
$date = mysqli_real_escape_string($conn,$_POST["date"]);
$date = date('Y-m-d', strtotime($date));
$description = mysqli_real_escape_string($conn,$_POST["Description"]);
$query = "Insert into `sermons` (`Title`,`Description`,`Speaker`,`Date`,`Link`) values('$title','$description','$speaker','$date','$uploadPath');";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn)." - ".mysqli_errno($conn)." ".$uploadPath);
It seems like you're running into a read timeout, because the upload takes longer than the script keeps the connection open. Try setting the value of the MYSQLI_OPT_READ_TIMEOUT to something suitable like so mysqli_options($conn, MYSQLI_OPT_READ_TIMEOUT, value_in_seconds);. You'll probably have to setup $conn before actually connecting, in case you run into this bug https://bugs.php.net/bug.php?id=76703
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;
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)."-"
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.
I'm trying to create a php cropper based on other online tutorials but I keep coming up with errors and I can't understand what the actual errors mean. Here is my php code with the errors written in too:
<?php
include("settings.php");
$extension = end(explode(".", $_FILES["avatar"]["name"]));
$id = mysqli_real_escape_string($con, $_POST["id"]);
$time = time();
$avatarid= time().'-'.mt_rand(1000, 9999);
$avatar = mysqli_real_escape_string($con, $_POST["avatar"]);
$w= mysqli_real_escape_string($con, $_POST["w"]);
$h= mysqli_real_escape_string($con, $_POST["h"]);
$x= mysqli_real_escape_string($con, $_POST["x"]);
$y= mysqli_real_escape_string($con, $_POST["y"]);
$rw = 300;
$rh = 300;
$path = "../uploads/avatars/";
$unlink = "$path$avatar";
$newimage = "$path$avatar";
$insert_avatar_sql = "UPDATE members SET avatar = '".$avatarid.".".$extension."' WHERE id = '$id'";
$insert_avatar_res = mysqli_query($con, $insert_avatar_sql);
if(mysqli_affected_rows($con)>0){
unlink($unlink);
move_uploaded_file($_FILES["avatar"]["tmp_name"],"$path" . $avatarid . "." . $extension);
$wratio = ($rw/$w);
$hratio = ($rh/$h);
$newW = ceil($w * $wratio);
$newH = ceil($h * $hratio);
$newimg = imagecreatetruecolor($newW,$newH);
$ext=$extension;
if($ext=="jpg" || $ext=="jpeg" )
{
$source = imagecreatefromjpeg($newimage); // Warning: imagecreatefromjpeg(../uploads/avatars/1380641918-4496.jpg) [function.imagecreatefromjpeg]: failed to open stream: No such file or directory in C:\AppServ\www\music.co.uk\php\avatar.php on line 34
}
else if($ext=="png")
{
$source = imagecreatefrompng($newimage);
}
else
{
$source = imagecreatefromgif($newimage);
}
imagecopyresampled($newimg,$source,0,0,$x1,$y1,$newW,$newH,$w,$h); // Warning: imagecopyresampled(): supplied argument is not a valid Image resource in C:\AppServ\www\music.co.uk\php\avatar.php on line 44
uploads/1380642027-5994
imagejpeg($newimg,$path.$avatarid,90);
echo "uploads/".$avatarid;
exit;
header("Location: ../edit.php?page=profile");
}
else{
header("Location: ../404.php");
exit();
}
?>
Please help me with this, I've been messing with Avatar uploads for 3 days solid now and I want to get this done, even if I have to use a different php script
For your first error you're passing $newimage to imagecreatefromjpeg(). During this process $newimage does not have a value that imagecreatefromjpeg() can understand. So basically if $newimage is a file or directory, it's not valid so your problem is the value assigned to $newimage.(Make sure "../uploads/avatars/1380641918-4496.jpg" is valid) Not sure what to tell you on the second warning. Good Luck.