mysqli insert Is not working when uploading large file - php

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

Related

Why on submitting form with image as file, my $_FILES array returns Array() empty array and my image is not stored on desired folder after submit

I have almost filled up this signup form 30 times in a day debugging this and still the image is not reaching to the destination folder as it should.
This code is present in htdocs/Email/signup.php and uploaded file should be moved to htdocs/gid113/Eagleeye/guard/imges/id.jpg and even only "id." is inserted in mysql database and not "id.jpg" unable to get the extension for image .
if(isset($_POST['signup'])){
$result = $conn->query("SHOW TABLE STATUS LIKE 'guard'");
$data = mysqli_fetch_assoc($result);
$id = $data['Auto_increment'];
$_SESSION["id"] = $id;
print_r($_FILES);
// File Image handling while signup
if($_FILES['img']['error']==UPLOAD_ERR_OK){
$file_name = $_FILES['img']['name'];
$file_size = $_FILES['img']['size'];
$file_tmp = $_FILES['img']['tmp_name'];
$file_type = $_FILES['img']['type'];
$destination = "../gid113/Eagleeye/guard/imges/".basename($file_name);
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
move_uploaded_file($file_tmp,$destination);
// $new_name ="./imges/".$id.".".$file_extension;
$new_name = id.".".$file_extension;
rename($destination,$new_name);
// $img=pathinfo($new_name,PATHINFO_BASENAME);
$img=$new_name;
}
}
SOLUTION:-
Added $ before Id in $new_name declaration.
Specified path to destination folder to the second parameter of rename as well.
if(isset($_FILES['img'])){
$file_name = $_FILES['img']['name'];
$file_size = $_FILES['img']['size'];
$file_tmp = $_FILES['img']['tmp_name'];
$file_type = $_FILES['img']['type'];
$destination = "../gid113/Eagleeye/guard/imges/".basename($file_name);
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
move_uploaded_file($file_tmp,$destination);
// $new_name ="./imges/".$id.".".$file_extension;
$new_name = $id.".".$file_extension;
rename($destination,"../gid113/Eagleeye/guard/imges/".$new_name);
// $img=pathinfo($new_name,PATHINFO_BASENAME);
$img=$new_name;
}

PHP file moving functionality is not working properly

Main issue is image file is not moving from temp location to new location. But it is not giving any error. And all mysql queries are working. Al the html part also working.
$newFileName = $_POST['filename'];
$imageTitle = $_POST['filetitle'];
$imageDesc = $_POST['filedesc'];
$file = $_FILES['file'];
$fileName = $file['name'];
$fileType = $file['type'];
$fileTempName = $file['temp_name'];
$fileError = $file['error'];
$fileSize = $file['size'];
$fileExt = explode(".",$fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg","jpeg","png");
if(in_array($fileActualExt,$allowed)){
if($fileError === 0){
if($fileSize < 20000000){
$imageFullName = $newFileName . "." . uniqid("",true) . "." . $fileActualExt;
$fileDestination = "../gallery/" . $imageFullName;
include_once 'dbh.inc.php';
if(!empty($imageTitle) || !empty($imageDesc)){
$sqlSelect = "SELECT * FROM gallery;";
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$sqlSelect)){
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rowCount = mysqli_num_rows($result);
$setImageOrder = $rowCount+1;
$sqlInsert = "INSERT INTO gallery(title,description,imgfullname,ordergallery) VALUES(?,?,?,?);";
if(mysqli_stmt_prepare($stmt,$sqlInsert)){
mysqli_stmt_bind_param($stmt,"ssss", $imageTitle,$imageDesc,$imageFullName,$setImageOrder);
mysqli_stmt_execute($stmt);
move_uploaded_file($fileTempName, $fileDestination);
}
}
}
}
}
}
Your $imageTitle and $imageDesc variables are empty in this code since they are never given a value. Therefore it will not enter the if statement and move the files.
You've probably been downvoted here because your description of what the code actually does is somewhat vague. You also do not appear to have tested or published a MCVE. Why, for instance, do you SELECT * FROM gallery; when all you use the data for is to display a count (which is irrelevant to the problem you describe).
You're handling of the filename is sensibly done, although ideally the path should be outwith the document root (and subsequent read access mediated by a script).
That "all mysql queries are working" suggests that the execution thread is reaching move_uploaded_file(), we shouldn't be guessing how the code works / what diagnostics you may have run. Each of those "if" statements should have an "else". Each of the mysqli_*() calls should check the return value. You should be checking the return value of move_uploaded_file(). You should also be checking your log file for errors and warnings (after verifying that the logging mechanism is working as expected).
From a cursory glance through the code (I imagine that the relevant POST vars are populated) the next place I would be looking (after the return values and logs) is at the permissions on the target directory.

Cannot upload file with custom php function

I try using function to upload different kind of file by giving it variables. As shown below:
<?
function fn_fileUpload($data,$dir,$uid){
include_once($_SERVER['DOCUMENT_ROOT']."/cgi-bin/connect.php");
if(isset($data) && $data['error'] === UPLOAD_ERR_OK){
$fileTmpPath = $data['tmp_name'];
$fileName = $data['name'];
$fileSize = $data['size'];
$fileType = $data['type'];
$fileNameCmps = explode(".", $fileName);
$fileExt = strtolower(end($fileNameCmps));
$newFileName = $uid . '.' . $fileExt;
//check file ext
$okEXT = array('jpg', 'jpeg', 'png','doc','docx','pdf');
if (in_array($fileExt, $okEXT)) {
$fileDir = '/'.$dir.'/';
$dest_path = $fileDir.$newFileName;
if(move_uploaded_file($fileTmpPath, $dest_path)){
try{
$stmt2=$mysqli->prepare("insert into job_file (jfile_id, job_id, jfile_name, jfile_size, jfile_type, jfile_ext) valies(?,?,?,?,?,?)");
$stmt2->bind_param('iisiss',$zero,$uid,$newFileName,$fileSize,$fileType,$fileExt);
$stmt2->execute();
$result = 'ok';
}catch(mysqli_sql_exception $err){
$result=$err;
}
}else{
$result = 'Cannot upload file!';
}
}//in_array
}//if(isset
return $result;
}
?>
And this is how to use:
//upload file
$job_file=fn_fileUpload($_FILES['job_file'],'uploads',$_POST['passport_id']);
//upload photo
$job_img=fn_fileUpload($_FILES['job_img'],'photos',$_POST['passport_id']);
From here, the function always return : Cannot upload file!. At first I think. It might have something to do with move_uploaded_file but the file was there in /uploads directory but not with /photos. Both directories CHMOD 755 (tried 777 but no luck).
The db went through correctly. Is there any idea how to fix this?
You can only use move_uploaded_file() ONCE on a temporary file that has been uploaded through a form. This function destroys the temporary file after it has been moved, so the for the first upload in the uploads directory you can do it well but in for the second one no.

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;

Change name of uploaded file

I have been trying to change the name of a file after an upload with my script.
I want every file to be named as "testing". Later I am going to change "testing" to a
variable that gets a unique name. Now I just want to change the name to "testing".
Also the script always says error although the file are uploaded.
Can I get some help here please?
Here is my code:
<?php
$uploadDir = 'images/'; //Image Upload Folder
if(isset($_POST['Submit']))
{
$fileName = $_FILES['Photo']['name'];
$tmpName = $_FILES['Photo']['tmp_name'];
$fileSize = $_FILES['Photo']['size'];
$fileType = $_FILES['Photo']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$query = "INSERT INTO $db_table ( Image ) VALUES ('$filePath')";
mysql_query($query) or die('Error, query failed');
}
?>
I think you need
$fileName = "testing"; //maybe add extension
instead of getting original filename from $_FILES. Although after the file is moved you may end up with a situation of overwriting existing files as they all has the same name. To prevent that (for testing purposes) you may add something to $fileName, maybe a short random string.

Categories