error in upload form - php

hello i copyed 1 upload file source code with upload progress bar
its work if i delete foreach and make 1 file for upload
but i want have 5 file field in my form
this is my code now:
$upload_directory = "$fUllp/";
//5M
$allowsize = 5242880;
foreach($_FILES as $file) {
$n = $file['name'];
$s = $file['size'];
$t = $file['type'];
$tmp = $file['tmp_name'];
if (is_array($n)) {
$c = count($n);
for ($i=0; $i < $c; $i++) {
if($s <= $allowsize){
$filename = explode('.',$n);
$filetype = $filename[1];
if(!isset($filename[2])){
$glast = mysql_query("select id from up_guest order by id desc limit 1");
$flast = mysql_fetch_array($glast);
if($flast['id'] == '' or $flast['id'] <= 0){
$flast = 1;
}
else{
$flast = $flast['id'] + 1;
}
$time = time();
$filename = $flast.'.'.$filename[1];
if(in_array($t,$allow)){
if (move_uploaded_file($tmp, $upload_directory . $filename)) {
//insert db
//img full
$fullurl = $siteurl.'/'.$upload_directory.$filename;
//for sql
$fullurlsq = '/'.$upload_directory.$filename;
$fullurlsqt = '/'.$upload_directory.'t/'.$filename;
//img resize
$image = new SimpleImage();
$image->load($upload_directory.'/'.$filename);
$image->resizeToHeight(100);
$image->resizeToWidth(100);
$image->save($upload_directory.'/t/'.$filename);
//img koochik
$imgt = $upload_directory.'/t/'.$filename;
mysql_query("insert into up_guest(name,name_t,type,time,ip) values('$fullurlsq','$fullurlsqt','$filetype',$time,'$ip')");
print '<br><div class="system-message"><ul class="index_info"><li>توضیح: <span>فایل با موفقیت آپلود شد<bR /><div class="thumb_img">';
print "<img src=\"$imgt\"></div>";
//tbl1
print '<table border="0" width="100%" cellspacing="0" cellpadding="0" class="up_box_input"><tbody><tr><td class="btitle">لینک تصویر کوچک</td><td class="all_box_link"><textarea readonly="readonly" rows="2" cols="40" class="up_input" tabindex="1" onclick="this.select();">';
print "[url=$siteurl/][img]$imgt [/img][/url]</textarea></td></tr></tbody></table>";
//tbl2
print 'echo file detaid for user';
}//file upload she
else{
echo '<div class="site_error_msg">cant up</div>';
}
}//age allow bood un file
else{
echo '<div class="site_error_msg">extention not allowed</div>';
}
}//if noghte vasatesh nabood
else{
echo '<div class="site_error_msg">you not must have . in file name</div>';
}
}//if sizesh mojaz bood
else{
echo '<div class="site_error_msg">uploaded file is more than 5 MB</div>';
}//end my code
but
its run else in first IF
i mean
if(in_array($t,$allow)){
and run this else
else{
echo '<div class="site_error_msg">uploaded file is more than 5 MB</div>';
}//end my code
so its must something wrong with
these lines and its set file name size incorect
foreach($_FILES as $file) {
$n = $file['name'];
$s = $file['size'];
$t = $file['type'];
$tmp = $file['tmp_name'];
if (is_array($n)) {
$c = count($n);
for ($i=0; $i < $c; $i++) {

ok find my nooblish problem ! i must inter my file size and name under For like this
foreach($_FILES as $file) {
$n = $file['name'];
$s = $file['size'];
$t = $file['type'];
$tmp = $file['tmp_name'];
if (is_array($n)) {
$c = count($n);
for ($i=0; $i < $c; $i++) {
$ss = $s[$i];
$tmpp = $tmp[$i];
$nn = $n[$i];
$tt = $t[$i];
if($ss <= $allowsize){
$filename = explode('.',$nn);
$filetype = $filename[1];
if(!isset($filename[2])){
$glast = mysql_query("select id from up_guest order by id desc limit 1");
$flast = mysql_fetch_array($glast);
if($flast['id'] == '' or $flast['id'] <= 0){
$flast = 1;
}
else{
$flast = $flast['id'] + 1;
}
$time = time();
$filename = $flast.'.'.$filename[1];
if(in_array($tt,$allow)){
thank you all :D

Related

PHP uploads the first TWO images only

I'm trying to upload images to my database, but it's acting really weird, because it uploads the first two images only. I have no idea why the first 2 and not the first only. The code is a little bit long because I'm executing another insert and then inserting the images. It's requested by an AJAX call, don't know if it's important or not. This is how it looks like:
if ($ok) {
//IMAGE UPLOAD
$filesize_error = 0;
$filesTempName = $_FILES['images']['tmp_name'];
$counted = count($filesTempName);
$allowed_types = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
if ($counted > $maxImage) {
$errorMsg[] = "Maximum 5 képet lehet feltölteni!";
} else {
for ($i = 0; $i < $counted; $i++) {
if (empty($filesTempName[$i])) {
$errorMsg[] = "Legalább egy képet ki kell választani!";
} else {
$detectedType = exif_imagetype($filesTempName[$i]);
if ($_FILES["images"]["size"][$i] > $maxSize) {
$filesize_error = 1;
$errorMsg[] = "Minden képnek 2 Mb-nál kisebbnek kell lennie!";
} elseif (!in_array($detectedType, $allowed_types)) {
$errorMsg[] = "A képek csak PNG/JPG/JPEG/GIF formátumban elfogadottak!";
} elseif ($filesize_error == 0) {
if (isset($_POST['mainimage']) && $_POST['mainimage'] != '') {
$placeholder = $_POST['mainimage'];
$mainimage = 'uploads/' . time() . $placeholder;
$stmt->execute();
$stmt->close();
$productid = $link->insert_id;
$statement = $link->prepare("INSERT INTO images(thumbnailimage, productid) VALUES(?, ?)");
for ($i = 0; $i < $counted; $i++) {
$file = $filesTempName[$i];
if (is_uploaded_file($file) && !empty($file)) {
$data = "uploads/" . time() . $_FILES["images"]["name"][$i];
move_uploaded_file($file, $data);
$statement->bind_param("si", $data, $productid);
$statement->execute();
}
}
$statement->close();
$link->close();
$success = true;
$_SESSION['successad'] = true;
} else {
$errorMsg[] = "Kérjük válassza ki a fő képet!";
$ok = false;
}
}
}
}
}
}
count($_FILES["images"]);
try count before temp name, try one var_dump on $_FILES
var_dump($_FILES);

How to select image sized between 100-500 kb?

I have a short PHP code to help me display random images from a specific folder. But now it seems to select any image in any size. I want those selected images are between 100-500 kb. If it's less than 100 kb or over 500 kb, the function won't select and display it.
Could you please tell me how to modify this code? Probably need to add some function.
<?php $randomdir = dir('images/random');
$count = 1;
$pattern="/(gif|jpg|jpeg|png)/";
while($file = $randomdir->read()) {
$ext = pathinfo($file, PATHINFO_EXTENSION);
if (preg_match($pattern, $ext)) {
$imagearray[$count] = $file;
$count++;
}
}
$random = mt_rand(1, $count - 1);
echo '<img src="images/random/'.$imagearray[$random].'" alt />';
?>
Try this one We have to set 2 conditions
$min = 100; //KB
$max = 500; //KB
if($_FILES['myfile']['size'] < $min * 1024 || $_FILES['myfile']['size'] > $max * 1024){
echo 'error';
}
Try now
<?php
$dir_name = 'images/random/';
$pattern="/(gif|jpg|jpeg|png)/";
$min = 100;
$max = 500;
$imagearray = array();
$scanned_directory = array_diff(scandir($dir_name), array('..', '.'));
$count = count($scanned_directory);
$ids = array_keys($scanned_directory);
$s = TRUE;
$stop = $count;
while( ($s === TRUE) && ($stop >=0))
{
$random = mt_rand(0, $count - 1);
$full_path_to_file = $dir_name.$scanned_directory[$ids[$random]];
$ext = pathinfo($full_path_to_file, PATHINFO_EXTENSION);
$file_size_kb = round(filesize($full_path_to_file)/1024);
if (preg_match($pattern, $ext) && ($file_size_kb>=$min && $file_size_kb<=$max))
{
$s = FALSE;
echo '<img src="'.$full_path_to_file.'" alt />';
}
$stop--;
}
?>

Rename files while uploading with php

I have a html form + php for uploading 3 pdfs similarly. while uploading i have to cut the names of the files. For instance instead of AB_2020_02_02.pdf i want to have it changed in AB.pdf - for all three files simultaneously. I tried with rename($original_filename, substr($original_filename, 2) . '.pdf'); Any other ideas?
This is the entire code:
<?php
// Set Upload Path
$target_dir = '';
$_FILES = substr($_FILES, 2, strlen($_FILES) - 12);
if( isset($_FILES['fileUpload']['name'])) {
$total_files = count($_FILES['fileUpload']['name']);
for($key = 0; $key < $total_files; $key++) {
// Check if file is selected
if(isset($_FILES['fileUpload']['name'][$key])
&& $_FILES['fileUpload']['size'][$key] > 0) {
$original_filename = $_FILES['fileUpload']['name'][$key];
rename($original_filename, substr($original_filename, 2) . '.pdf');
$target = $target_dir . basename($original_filename);
$tmp = $_FILES['fileUpload']['tmp_name'][$key];
move_uploaded_file($tmp, $target);
}
}
}
?>
$target_dir = '';
if( isset($_FILES['fileUpload']['name'])) {
$total_files = count($_FILES['fileUpload']['name']);
for($key = 0; $key < $total_files; $key++) {
// Check if file is selected
if(isset($_FILES['fileUpload']['name'][$key])
&& $_FILES['fileUpload']['size'][$key] > 0) {
$original_filename = $_FILES['fileUpload']['name'][$key];
$rename = explode('_',$original_filename);
$target = $target_dir . $rename[0].".pdf";
$tmp = $_FILES['fileUpload']['tmp_name'][$key];
move_uploaded_file($tmp, $target);
}
}
}
Rename directly in move_uploaded_file(...)
<?php
// Set Upload Path
$target_dir = '';
$_FILES = substr($_FILES, 2, strlen($_FILES) - 12);
if( isset($_FILES['fileUpload']['name'])) {
$total_files = count($_FILES['fileUpload']['name']);
for($key = 0; $key < $total_files; $key++) {
// Check if file is selected
if(isset($_FILES['fileUpload']['name'][$key])
&& $_FILES['fileUpload']['size'][$key] > 0) {
$original_filename = $_FILES['fileUpload']['name'][$key];
$target = $target_dir . substr($original_filename, 2).'.pdf' ;
$tmp = $_FILES['fileUpload']['tmp_name'][$key];
move_uploaded_file($tmp, $target);
}
}
}
?>

Codeigniter File Upload Permit Only For Images not For Others

I have to file upload operation consecutive, first for images like gif|jpg|jpeg|png|svg and the second psd|rar|zip|doc|word|txt|xlsx|pdf
First one is working just fine, i can upload all images but the second, i can not upload any of these types but when i try to upload image on second segment it works.
if (isset($_FILES['content_images']['name'])) {
$count_files = count($_FILES['content_images']['name']);
for ($i = 0; $i < $count_files; $i++) {
$_FILES['image']['name'] = $_FILES['content_images']['name'][$i];
$_FILES['image']['type'] = $_FILES['content_images']['type'][$i];
$_FILES['image']['tmp_name'] = $_FILES['content_images']['tmp_name'][$i];
$_FILES['image']['error'] = $_FILES['content_images']['error'][$i];
$_FILES['image']['size'] = $_FILES['content_images']['size'][$i];
$config_images['upload_path'] = "./public/site/images/contents";
$config_images['allowed_types'] = 'gif|jpg|jpeg|png|svg';
$config_images['max_size'] = 5000;
$config_images['max_width'] = 7680;
$config_images['max_height'] = 4320;
$this->load->library("upload", $config_images);
if (!$this->upload->do_upload('image')) {
echo $this->upload->display_errors();
exit;
} else {
$data = $this->upload->data();
$path_images[] = "public/site/images/contents/".$data['file_name'];
}
}
}
if (isset($_FILES['content_files']['name'])) {
$count_files=count($_FILES['content_files']['name']);
for ($i = 0; $i < $count_files; $i++) {
$_FILES['file']['name'] = $_FILES['content_files']['name'][$i];
$_FILES['file']['type'] = $_FILES['content_files']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['content_files']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['content_files']['error'][$i];
$_FILES['file']['size'] = $_FILES['content_files']['size'][$i];
$config_files['upload_path'] = "./public/site/files/contents";
$config_files['allowed_types'] = 'psd|rar|zip|doc|word|txt|xlsx|pdf';
$config_files['max_size'] = 5000;
$config_files['max_width'] = 7680;
$config_files['max_height'] = 4320;
$this->load->library("upload",$config_files);
if (!$this->upload->do_upload('file')) {
foreach($path_images as $p){
unlink($p);
}
echo $this->upload->display_errors();
exit;
} else {
$data=$this->upload->data();
$path_files[] = "public/site/files/contents/".$data['file_name'];
}
}
}
I found the solution
For help :
You should load the library at the top for 1 time only, and then u should initialize it inside 'if condition'.
When you load upload library and config array inside first condition, when you pass to second condition upload library had already loaded and uses the first condition's config array.
$this->load->library("upload");
if(isset($_FILES['content_images']['name'])){
$count_files=count($_FILES['content_images']['name']);
for($i = 0;$i<$count_files;$i++){
$_FILES['image']['name'] = $_FILES['content_images']['name'][$i];
$_FILES['image']['type'] = $_FILES['content_images']['type'][$i];
$_FILES['image']['tmp_name'] = $_FILES['content_images']['tmp_name'][$i];
$_FILES['image']['error'] = $_FILES['content_images']['error'][$i];
$_FILES['image']['size'] = $_FILES['content_images']['size'][$i];
$config_images['upload_path'] = "./public/site/images/contents";
$config_images['allowed_types'] = 'gif|jpg|jpeg|png|svg';
$config_images['max_size'] = 5000;
$config_images['max_width'] = 7680;
$config_images['max_height'] = 4320;
$this->upload->initialize($config_images);
if(!$this->upload->do_upload('image')){
echo $this->upload->display_errors();
exit;
}else{
$data=$this->upload->data();
$path_images[] = "public/site/images/contents/".$data['file_name'];
}
}
}
if(isset($_FILES['content_files']['name'])){
$count_files=count($_FILES['content_files']['name']);
for($i = 0;$i<$count_files;$i++){
$_FILES['file']['name'] = $_FILES['content_files']['name'][$i];
$_FILES['file']['type'] = $_FILES['content_files']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['content_files']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['content_files']['error'][$i];
$_FILES['file']['size'] = $_FILES['content_files']['size'][$i];
$config_files['upload_path'] = "./public/site/files/contents";
$config_files['allowed_types'] = 'psd|rar|zip|doc|word|txt|xlsx|pdf';
$config_files['max_size'] = 5000;
$config_files['max_width'] = 7680;
$config_files['max_height'] = 4320;
$this->upload->initialize($config_files);
if(!$this->upload->do_upload('file')){
foreach($path_images as $p){
unlink($p);
}
echo $this->upload->display_errors();
exit;
}else{
$data=$this->upload->data();
$path_files[] = "public/site/files/contents/".$data['file_name'];
}
}
}

An uncaught Exception was encountered Type: ImagickException Message: Failed to read the file in Codeigniter

The following php pdf to image code with imagick in codeigniter framework has a problem in the controller, imagick cannot read my file pdf.
error:
[codeigniter] An uncaught Exception was encountered Type: ImagickException Message: Failed to read the file in Codeigniter.
controller:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Files_upload extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('files');
}
function index(){
$data['gallery'] = $this->db->query("select * from gallery order by id desc limit 10")->result();
$data = array();
if($this->input->post('submitForm') && !empty($_FILES['upload_Files']['name'])){
$filesCount = count($_FILES['upload_Files']['name']);
for($i = 0; $i < $filesCount; $i++){
$_FILES['upload_File']['name'] = $_FILES['upload_Files']['name'][$i];
$_FILES['upload_File']['type'] = $_FILES['upload_Files']['type'][$i];
$_FILES['upload_File']['tmp_name'] = $_FILES['upload_Files']['tmp_name'][$i];
$_FILES['upload_File']['error'] = $_FILES['upload_Files']['error'][$i];
$_FILES['upload_File']['size'] = $_FILES['upload_Files']['size'][$i];
$uploadPath = 'uploads/files/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png|pdf|mp4|avi';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('upload_File')){
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['created'] = date("Y-m-d H:i:s");
$uploadData[$i]['modified'] = date("Y-m-d H:i:s");
}
}
if(!empty($uploadData)){
//Insert file information into the database
$insert = $this->files->insert($uploadData);
$statusMsg = $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
$this->session->set_flashdata('statusMsg',$statusMsg);
}
$this->load->helper('url');
$ImageName = $_FILES['upload_File']['name'];
$loc = base_url().$uploadPath.$ImageName;
echo $ImageName;
echo $loc;
$im = new imagick($loc);
$noOfPagesInPDF = $im->getNumberImages();
if ($noOfPagesInPDF) {
for ($i = 0; $i < 1; $i++) {
$url = $loc.'['.$i.']';
$image = new Imagick($url);
$image->setImageFormat("jpg");
$image->setImageCompressionQuality(80);
$image->writeImage("uploads/files/img/".($i+1).'-'.$ImageName.'.jpg');
}
}
for($i = 0; $i<1;$i++) {
$img = "uploads/files/img/".($i+1).'-'.$ImageName.'.jpg';
$display .= "<img src='$img' title='Page-$i' /><br>";
}
$message = "PDF converted to JPEG sucessfully!!";
}
//Get files data from database
$data['gallery'] = $this->files->getRows();
//Pass the files data to view
$this->load->view('files_upload/index', $data);
}
}
Solved
Is Correct Code
$ImageName= $fileData['file_name'];
$loc = realpath(APPPATH.'../uploads/files/').'/'.$ImageName;
Or you can just do
$loc = $fileData['full_path'];
This will work (tested):
//$data['gallery'] = $this->db->query("select * from gallery order by id desc limit 10")->result(); // same at bottom??
$message = '';
$display = '';
if ($this->input->post('submitForm') && !empty($_FILES['userfile']['name'])) {
$uploadPath = FCPATH . 'uploads/files/';
if (!is_dir($uploadPath) && mkdir($uploadPath, DIR_WRITE_MODE, true) == false) {
show_error('Folder cannot be made!');
}
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png|pdf|mp4|avi';
$this->load->library('upload', $config);
// change input field to <input type="file" name="userfile">
if (!$this->upload->do_upload()) {
$this->session->set_flashdata('statusMsg', $this->upload->display_errors());
} else {
$fileData = $this->upload->data();
$uploadData['file_name'] = $fileData['file_name'];
$uploadData['created'] = date("Y-m-d H:i:s");
$uploadData['modified'] = date("Y-m-d H:i:s");
$insert = $this->files->insert($uploadData);
$insert = true;
if (!$insert) {
#unlink($fileData['full_path']); // remove orphan
$this->session->set_flashdata('statusMsg', 'Database error. Please try again');
} else {
$this->session->set_flashdata('statusMsg', 'Files uploaded successfully.');
if ($fileData['file_ext'] == '.pdf') {
try {
$newPath = $uploadPath . 'img/';
if (!is_dir($newPath) && mkdir($newPath, DIR_WRITE_MODE, true) == false) {
throw new Exception('Folder cannot be made!');
}
$ImageName = $fileData['raw_name'];
$loc = $fileData['full_path'];
$im = new Imagick($loc);
$pdfPageCount = $im->getNumberImages();
if ($pdfPageCount > 0) {
for ($i = 0; $i < $pdfPageCount; $i++) {
$url = $loc . '[' . $i . ']';
$image = new Imagick($url);
$image->setImageFormat("jpg");
$image->setImageCompressionQuality(80);
$image->writeImage($newPath . ($i + 1) . '-' . $ImageName . '.jpg');
$img = base_url("uploads/files/img/" . ($i + 1) . '-' . $ImageName . '.jpg');
$display .= "<img src='$img' title='Page-$i' /><br>";
}
echo $display; // debugging
$this->session->set_flashdata('statusMsg', "PDF converted to JPEG(s) sucessfully!");
}
} catch (Exception $e) {
#unlink($fileData['full_path']); // remove orphan
$this->session->set_flashdata('statusMsg', $e->getMessage());
}
} else {
echo 'not a pdf'; // debugging only
}
}
}
}
//Get files data from database
$data['gallery'] = $this->files->getRows();
//Pass the files data to view
$this->load->view('files_upload/index', $data);
Please note the input file field should now look like this:
<input type="file" name="userfile" />
You will also have to revise:
$this->files->insert($uploadData) function

Categories