Upload image file to server, store name in MySQL DB - php

I'm trying to create a file upload only my current script doesn't seem to work as I believe it should.
I've managed to get the data saved in the MySQL table okay but I can't seem to get the file into the 'uploads' directory?
if(isset($_POST['new']) && $_POST['new']==1){
$folder = "uploads/";
$upload_image = $folder . basename($_FILES["image1"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $upload_image);
$trn_date = date("Y-m-d H:i:s");
$brand =$_REQUEST['brand'];
$user =$_SESSION["username"];
$model = $_REQUEST['model'];
$serial =$_REQUEST['serial'];
$purchasedate = $_REQUEST['purchasedate'];
$img1 =$_REQUEST['image1'];
$ins_query="insert into table
(`user`,`trn_date`,`brand`,`model`,`serial`,`purchasedate`,`image1`)values
('$user','$trn_date','$brand','$model','$serial','$purchasedate','$img1')";
mysqli_query($con,$ins_query)
or die(mysql_error());
$status = "added successfully.
</br></br><a href='home.php'>home</a>";
}

$upload_image = $folder . basename($_FILES["image1"]["name"]);
move_uploaded_file($_FILES["image1"]["tmp_name"], $upload_image);

What if trying directly what the doc said ;)
$uploads_dir = '/uploads';//try over 'uploads' too or create a 'uploads' folder in you app_root
foreach ($_FILES["image1"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["image1"]["tmp_name"][$key];
$name = $_FILES["image1"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}

Possible Link
I have found an issue in your code.
$folder = "uploads/";
$upload_image = $folder . basename($_FILES["image1"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $upload_image);
In this case the file does not have the extension
$folder = "uploads/";
$ext = explode('.', basename( $_FILES['image1']['name']));
$upload_image = $folder . basename($_FILES["image1"]["name"].$ext);
move_uploaded_file($_FILES["image1"]["tmp_name"], $upload_image);
The uploads folder is in the same directory that is the php script?
You also can verify if the file was correctly moved doing the following test
if (file_exists($upload_image)){
echo "true";
}
Provide a file upload validation before uploading into server it will prevent server from malicious files
How to give file validation in php : Link

Related

rename file while uploading with php

I have a php script which uploads files:
for($index = 0;$index < count($_FILES['files']['name']); $index++){
// File name
$filename = $_FILES['files']['name'][$index];
// File path
$path = '../pdf/'.$filename;
// Upload file
if(!move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
// ERROR
exit;
}
This works fine!
But I would like to modify the filename while uploading:
For example:
I uploading a "upload.pdf" file.
But I would like to get the name "upload_2021.pdf"
How can I realize it?
I found a solution !!
$path = '../pdf/'.$filename;
$extension = pathinfo($path, PATHINFO_EXTENSION);
$name = pathinfo($path, PATHINFO_FILENAME);
From what I can see, the only thing you need to do is change the $path variable.
Bare in mind, that what you are showing here is not a safe and secure upload script. You are not doing any file and mime-type validation what so ever. There is nothing preventing your users from uploading harmful files. Together with not checking for duplicate files and some other edge cases, think twice before putting this into production.
for($index = 0;$index < count($_FILES['files']['name']); $index++){
// File name
$filename = $_FILES['files']['name'][$index];
$parts = explode(".", $filename);
$year = date("Y");
// File path
$path = '../pdf/'.$parts[0] . '_' $year . '.' . $parts[count($parts)-1];
// Upload file
if(!move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
// ERROR
exit;
}
}
a short example:
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

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.

Laravel 5.3 photo upload with plupload directory related issue

I have recently migrated my code into laravel. I have faced problem with file upload using plupload with laravel. In pluploaded file is uploaded to server before form submitting. After uploaded file succesfully, file path is put in hidden input field.
My Upload Code is given below.
public function photo(){
$target_file = "";
$this->target_dir = base_path() ."/uploads/";
if($_FILES['file']['name']){
$filename = AppUtils::get_new_filename($this->ext);
$filename = "photo_" . $filename;
$target_file = $this->target_dir . $filename;
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
$photo = $this->target_dir . $filename;
echo $photo;
die();
}
else{
AppUtils::fail();
}
}
Problem is without using base_path() in $target_dir, file is not uploaded properly. But using base_path() preview image not actual location.
For example, After uploading photo output will be /var/www/htm/lar/uploads/xyz.jpg
But in preview image path shows : http://example.com/lar/var/www/html/lar/uploads/xyz.jpg
Try this:
public function photo(){
$target_file = "";
$this->target_dir = "/uploads/";
if($_FILES['file']['name']){
$filename = AppUtils::get_new_filename($this->ext);
$filename = "photo_" . $filename;
$target_file = base_path() . $this->target_dir . $filename;
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
$photo = $this->target_dir . $filename;
echo $photo;
die();
}
else{
AppUtils::fail();
}
}
base_path() should only be used for the upload location.

move_uploaded_file() in php returns true but file not found inside the directory

Please i need help on this.
I was uploading an image to my server using the move_uploaded_file() method, the method returns true bu the uploaded file was not found inside the specified directory on my server. i have checked thoroughly, searched for the file on the server in case it was uploaded to another directory, checked the permission on the directory but all seems perfect. i really dont know what went wrong .
Here is the snippet of the code.
$uploaddir = './upload_dir/';
$allowed = array('gif', 'png', 'jpg','bmp');
$filename = $_FILES['uploadfile']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$data = array();
if (!in_array($ext, $allowed)) {
$data['status'] = 'error';
$data['error_message'] = 'Invalid file type';
}
else{
$file_name = time() . '_' . uniqid() . '_' . basename($_FILES['uploadfile']['name']);
$file_name = preg_replace('/[^a-z0-9_\.\-]+/i', '_', $file_name);
$file = $uploaddir . $file_name;
if (isset($_FILES['uploadfile']['tmp_name']) && move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
$data['status'] = 'success';
$data['file_name'] = $file_name;
} else {
$data['status'] = 'error';
}
echo json_encode($data);
}
Thanks in advance.
Please use is_uploaded_file($_FILES['uploadfile']['tmp_name']) instead of isset($_FILES['uploadfile']['tmp_name']) for security reason check here
And for the upload dir use $uploaddir = $_SERVER['DOCUMENT_ROOT'] . "/upload_dir/"; instead of $uploaddir = './upload_dir/'; to get absolute path instead of relative one.
thanks everyone. I gave the wrong permission to the folder. that seems to be the problem for my own case.

Uploading image to with custom name in Yii framework

I am trying to upload images from registration form in Yii framework. The image will be saved in "img/avatar" folder and the name of the image should be changed to the username. The piece of code I use for this is below:
//uploading avatar to the img/avatar folder
$upload_file = CUploadedFile::getInstance($personModel, 'picture');
$personModel->picture = $upload_file;
$picture_name = $userModel->username;
$personModel->picture = $picture_name;
if(isset($upload_file))
{
$upload_file->saveAs(Yii::app()->basePath.'/../img/avatar'.$picture_name);
}
$personModel->save();
//end of image uploading part
The problem is: the name of the username has been saved in picture row of the database. But the image was not uploaded to the folder. I am trying to find out the problem in the code. but cannot solve it. Any suggestions?
Well first thing you need to do is to prevent database input if the picture is not saved.
if(isset($uploadedfile))
{
if($upload_file->saveAs(Yii::app()->basePath.'/../img/avatar'.$picture_name)
{
$personModel->save();
}
else
{
//throw error
}
}
As far as problems in the code go. Most common problem is directories not existing, path to them not being correct.
$upload_file = CUploadedFile::getInstance($personModel, 'picture');
$ext = pathinfo($upload_file->picture, PATHINFO_EXTENSION);
$picture_name = $userModel->username . '.' . $ext;
$personModel->picture = $picture_name;
if(isset($upload_file))
{
$upload_file->saveAs('/Your_correct_path/.../etc/'.$picture_name);
}
$personModel->save();
$upload_file = CUploadedFile::getInstance($personModel, 'picture');
$picture_name = $userModel->username . '.' . pathinfo($upload_file, PATHINFO_EXTENSION);
$personModel->picture = $picture_name;
if (isset($upload_file)) {
$upload_file->saveAs(Yii::app()->basePath . '/../img/avatar/' . $picture_name);
}
$personModel->save();
You have to check your folder permission.
The problem has been solved through following code:
$uploadFile = CUploadedFile::getInstance($personModel, 'picture');
$extension = pathinfo($uploadFile, PATHINFO_EXTENSION);
$fileName = $userModel->username . '.' . $extension;
if (isset($uploadFile)) {
$personModel->picture = $fileName;
$uploadFile->saveAs(Yii::app()->basePath . '/../img/avatar/' . $fileName);
}

Categories