Compress image php with move_uploaded_files - php

I have a php script which upload a photo from an Ajax call, and i want to upload the photo two times, one with standard size and another one compressed. Does anyone know how to do it with this following code? I tried to compress the image with scripts that I found on stackoverflow, but I can't do it correctly. Everytime appears an black photo.
I got this code:
$data = array();
if (isset($_GET['files'])) {
$error = false;
$files = array();
$uniqid = uniqid();
$uploaddir = '../../images/'.$uniqid;
foreach($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir.basename($file['name']))) {
$files[] = $uploaddir.$file['name'];
} else {
$error = true;
}
}
$data = ($error) ? array('error' = > 'There was an error uploading your files') : array('files' = > $files);
} else {
$arr - > image = $file['name'];
$_SESSION['image'] = "img-".$file['name'];
$arr - > ok = "ok";
$data = array('success' = > 'Form was submitted', 'formData' = > $file['name']);
}
Thank you all!

Try using basename() also in your $files[] array insertion:
Change this:
foreach($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir.basename($file['name']))) {
$files[] = $uploaddir.$file['name'];
} else {
$error = true;
}
}
To this:
foreach($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir.basename($file['name']))) {
$files[] = $uploaddir.basename($file['name']);
} else {
$error = true;
}
}

Related

Why doesn't my file upload function work properly? PHP

Hi I have a file upload function. Controls file size and file type. If the file is in PDF format and is smaller than 10MB, everything works as it should.
If the file is not PDF, it should show me the message: "ERROR: You can just upload PDF files." but no message.
If the file size is larger than 10MB, it should show me the message: "ERROR: Max file size 10MB." but no message.
If the file is PDF but larger than 10MB, it shows me: "ERROR: All fields must be filled."
What is wrong with my code?
Function :
<?php
function file_create($file) {
if(isset($file)){
$errors = array();
$target_dir = "../files/";
$file_name = uniqid();
$file_size = $file['size'];
$file_tmp = $file['tmp_name'];
$file_type = $file['type'];
$file_ext = strtolower(end(explode('.',$file['name'])));
if($file_type != "application/pdf") {
$error = "ERROR : You can upload just PDF files.";
array_push($errors, $error);
}
if($file_size > 1024*1024*10) {
$error = "ERROR : Max file size 10MB.";
array_push($errors, $error);
}
if(empty($errors) == true) {
move_uploaded_file($file_tmp,$target_dir.$file_name.".".$file_ext);
$errors['status'] = true;
$errors['patch'] = substr($target_dir.$file_name.".".$file_ext, 3);
} else {
$errors['status'] = false;
}
return $errors;
}
}
?>
Another File :
<?php
$errors = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$notice_title = secured_post("notice-title");
$notice_content = secured_post("notice-content");
// if there is empty field in form.
if (multi_empty($notice_title, $notice_content)) {
// if a file submitted.
if (isset($_FILES['notice-file'])) {
$notice_file = $_FILES['notice-file'];
// upload the file.
$upload = file_create($notice_file);
if ($upload['status'] == false) {
$size = count($upload);
for ($i=0; $i < $size; $i++) {
array_push($errors, $upload[$i]);
}
}
notice_create($conn, $notice_title, $notice_content, $upload['patch']);
} else {
notice_create($conn, $notice_title, $notice_content);
}
} else {
$error = "ERROR : All fields must be filled.";
array_push($errors, $error);
}
}
if ($errors) {
foreach ($errors as $error) {
echo "<div class='error'>".$error."</div></br>";
}
}
?>
Here's the problem. If your file is larger than 10MB then it can take some time to upload the file so you have to check if the $_FILES array is empty or not.
Try this:
<?php
$errors = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_FILES)) { //I've made changes to this line
$notice_title = secured_post("notice-title");
$notice_content = secured_post("notice-content");
// if there is empty field in form.
if (multi_empty($notice_title, $notice_content)) {
// if a file submitted.
if (isset($_FILES['notice-file'])) {
$notice_file = $_FILES['notice-file'];
// upload the file.
$upload = file_create($notice_file);
if ($upload['status'] == false) {
$size = count($upload);
for ($i=0; $i < $size; $i++) {
array_push($errors, $upload[$i]);
}
}
notice_create($conn, $notice_title, $notice_content, $upload['patch']);
} else {
notice_create($conn, $notice_title, $notice_content);
}
} else {
$error = "ERROR : All fields must be filled.";
array_push($errors, $error);
}
}
if ($errors) {
foreach ($errors as $error) {
echo "<div class='error'>".$error."</div></br>";
}
}
?>
And:
<?php
function file_create($file) {
if(!empty($file)){ //I've made changes to this line
$errors = array();
$target_dir = "../files/";
$file_name = uniqid();
$file_size = $file['size'];
$file_tmp = $file['tmp_name'];
$file_type = $file['type'];
$file_ext = strtolower(end(explode('.',$file['name'])));
if($file_type != "application/pdf" || $file_ext != ".pdf") { //I've made changes to this line
$error = "ERROR : You can upload just PDF files.";
array_push($errors, $error);
}
if($file_size > (1024*1024*10)) {
$error = "ERROR : Max file size 10MB.";
array_push($errors, $error);
}
if(empty($errors) == true) {
move_uploaded_file($file_tmp,$target_dir.$file_name.".".$file_ext);
$errors['status'] = true;
$errors['patch'] = substr($target_dir.$file_name.".".$file_ext, 3);
} else {
$errors['status'] = false;
}
return $errors;
}
}
?>
Note: The $_FILES array can be set and empty at the same time so isset() can't help you here.

Multiple Upload sometimes doesn't uploaded successfully

I have a function to upload multiple files, but sometimes file(s) is not uploaded but path is successfully added to database. i am not sure what is the ptoblem. i use function 'times()' to make it unique is this the root of the problem ?
i already tested it and it work successfully, but when its implemented sometimes the file doesnt uploaded successfully
if ($_FILES["lampiran"]["name"] != NULL) {
$config = array();
$ext = array();
$records = array();
$file_name = "Plan_".time();
$files = $_FILES['lampiran'];
$config['upload_path'] = "./uploads/Planning/attachment";
$config['allowed_types'] = '*';
foreach ($_FILES['lampiran']['name'] as $key => $value) {
$ext[]= pathinfo($_FILES['lampiran']['name'][$key], PATHINFO_EXTENSION);
}
$cpt = count ($_FILES['lampiran']['tmp_name']);
for($i=0; $i<$cpt; $i++){
$_FILES['lampiran']['name']= $file_name.$i.'.'.$ext[$i];
$_FILES['lampiran']['type']= $files['type'][$i];
$_FILES['lampiran']['tmp_name']= $files['tmp_name'][$i];
$_FILES['lampiran']['error']= $files['error'][$i];
$_FILES['lampiran']['size']= $files['size'][$i];
$records[] = $config['upload_path'].'/'.$_FILES['lampiran']['name'];
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('lampiran'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
// $this->load->view('upload_form', $error);
}
}
$pile = implode(";", $records);
} else {
$pile = NULL;
}
Use $records in else condition also make error array than, Like
if ( ! $this->upload->do_upload('lampiran'))
{
$error[] = $this->upload->display_errors();
}else{
$upload_data = $this->upload->data();
$records[] = $config['upload_path'].'/'.$upload_data['file_name'];
}
Here you will get all errors in $error and uploaded files in records.

PHP/MySQL - Data entered twice when doing single upload

I am trying to upload image to database MySQL. But I have a problem, when I am trying to upload one image, the image inserted twice.
For example:
I have "A.jpg" if I try to upload it
the inserted data will be like "A.jpg,A.jpg"
What I want in database "A.jpg"
and if I try to upload multiple images like "A.jpg,B.jpg and C.jpg"
the inserted data will be like "B.jpg,B.jpg,C.jpg,C.jpg"
What I want in database "A.jpg,B.jpg,C.jpg"
I've tried to search on google but no results, anyone can help me to resolve this problem ? Thanks
Here is my code :
include('koneksi.php');
date_default_timezone_set('Asia/Jakarta');
$id_user = $_POST['id_user'];
$caption = $_POST['caption'];
$files = [];
foreach($_FILES['files']['name'] as $i => $name) {
$name = $_FILES['files']['name'][$i];
$size = $_FILES['files']['size'][$i];
$type = $_FILES['files']['type'][$i];
$tmp = $_FILES['files']['tmp_name'][$i];
$explode = explode('.', $name);
$ext = end($explode);
$updatdName = $explode[0] . time() .'.'. $ext;
$path = 'gallery/';
$path = $path . basename( $updatdName );
if(empty($_FILES['files']['tmp_name'][$i])) {
$errors[] = 'Please choose at least 1 file to be uploaded.';
}else {
$allowed = array('jpg','JPG','jpeg','JPEG','gif','GIF','bmp','BMP','png','PNG');
$max_file_size = 1024*1024*2;; // 2MB
if(in_array($ext, $allowed) === false) {
$errors[] = 'The file <b>'.$name.'</b> extension is not allowed.';
}
if($size > $max_file_size) {
$errors[] = 'The file <b>'.$name.'</b> size is too hight.';
}
}
if(empty($errors)) {
// if there is no error then set values
$files['file_name'][] = $updatdName;
$files['size'][] = $size;
$files['type'][] = $type;
$errors = array();
if(!file_exists('gallery')) {
mkdir('gallery', 0777);
}
if(move_uploaded_file($tmp, $path)) {
echo '<script>window.history.back()</script>';
}else {
echo 'Something went wrong while uploading
<b>'.$name.'</b>';
}
}else {
foreach($errors as $error) {
echo '<p>'.$error.'<p>';
}
}
}
if(!empty($files)) {
$files['file_name'][] = $updatdName;
$files['size'][] = $size;
$files['type'][] = $type;
$names = implode(',', $files['file_name']);
$sizes = implode(',', $files['size']);
$types = implode(',', $files['type']);
$sql="INSERT into status VALUES(NULL, '$id_user', '$names','$caption','foto',NOW()); ";
mysqli_query($koneksi, $sql);
}
You're setting $files['file_name'][] in the while loop and also right before inserting into the DB. You just need to remove 2nd call to $files['file_name'][] = $updatdName;
Here is a simplified version of what you're doing.
<?php
$_FILES[] = ['name' => 'A'];
$_FILES[] = ['name' => 'B'];
$_FILES[] = ['name' => 'C'];
$files = [];
foreach ($_FILES as $file) {
$updatdName = $file['name'];
// You're setting it here
$files['file_name'][] = $updatdName;
}
if (!empty($files)) {
// And also here.
$files['file_name'][] = $updatdName;
$names = implode(',', $files['file_name']);
echo $names;
}

move_uploaded_file() function doesn't save uploaded file on server

I've been working on a php script which creates a folder and saves posted images in the created folder, the folders get created but the images I aren't saved.
Below is the script:
if (isset($_FILES['images'])) {
mkdir("files/test/".$new."/", 0755, true);
foreach ($_FILES['images']['tmp_name'] as $key => $value) {
if (!(empty($_FILES['images']['tmp_name'][$key]) || $_FILES['images']['tmp_name'][$key] == 'none')) {
$i_slika = 1;
$extenzion = strtolower(end(explode(".", $_FILES['images']['name'][$key])));
$file = "files/nekretnina/".$new."/".$i_slika.".".$extenzion;
while (file_exists($file)) {
$i_slika++;
$file = "files/nekretnina/".$new."/".$i_slika.".".$extenzion;
}
if (!#move_uploaded_file($_FILES['images']['tmp_name'][$key], $file)) {
$err_text = $err_text. 'Error: '.$_FILES['images']['name'][$key].'<br />';
} else {
include_once "thumbz.class.php";
$pic = new thumbz($file);
$pic->dimensionImage("resize",640);
$pic->addParam('l',0);
$pic->render($file);
}
}
}
}
You need to use $_FILES['images']['tmp_name'][$key] instead of $_FILES['slika']['tmp_name'][$key].
You have the wrong index name!
Try Using:
if (isset($_FILES['images'])) {
mkdir("files/test/".$new."/", 0755, true);
foreach ($_FILES['images']['tmp_name'] as $key => $value) {
if (!(empty($_FILES['images']['tmp_name'][$key]) || $_FILES['images']['tmp_name'][$key] == 'none')) {
$i_slika = 1;
$extenzion = strtolower(end(explode(".", $_FILES['images']['name'][$key])));
$file = "files/test/".$new."/".$i_slika.".".$extenzion;
while (file_exists($file)) {
$i_slika++;
$file = "files/test/".$new."/".$i_slika.".".$extenzion;
}
if (!#move_uploaded_file($_FILES['images']['tmp_name'][$key], $file)) {
$err_text = $err_text. 'Error: '.$_FILES['images']['name'][$key].'<br />';
} else {
include_once "thumbz.class.php";
$pic = new thumbz($file);
$pic->dimensionImage("resize",640);
$pic->addParam('l',0);
$pic->render($file);
}
}
}
}

Saving data in the database in yii2 during file upload action

I have a upload controller where by am also performing saving other data to the database. The file uploading to the folder is okay but saving the other details in the table doesn't happen
controller code
$images = $_FILES['evidence'];
$success = null;
$paths= ['uploads'];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
//$ext = explode('.', basename($filenames[$i]));
$target = "uploads/cases/evidence".DIRECTORY_SEPARATOR . md5(uniqid()); //. "." . array_pop($ext);
if(move_uploaded_file($images['name'], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
echo $success;
}
// check and process based on successful status
if ($success === true) {
$evidence = new Evidence();
$evidence->case_ref=$id;
$evidence->saved_on=date("Y-m-d");
$evidence->save();
$output = [];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
After doing var_dump($evidence->save()) I get an error of Boolean false
You could have validation errors. Check $errors property
// check and process based on successful status
if ($success === true) {
$evidence = new Evidence();
$evidence->case_ref=$id;
$evidence->saved_on=date("Y-m-d");
$retSave = $evidence->save();
if($retSave == false)
{
var_dump($evidence->errors);
}
$output = [];
}
....

Categories