I'm using class.upload.php for images. Resizing works correctly with name and extension into the folder, but i have a problem storing the name into mysql database. There's no file extension (.jpg, .gif etc)... why? how can i resolve the problem?
Thanks
/* ========== SCRIPT UPLOAD MULTI IMAGES ========== */
include('class.upload.php');
$dir_dest="../../images/gallery/";
$files = array();
foreach ($_FILES['fleImage'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
foreach ($files as $file) {
$handle = new Upload($file);
if ($handle->uploaded) {
$mainame = $handle->file_dst_name;
$db_name = str_replace(" ","_",$mainame);
$image1 = md5(rand() * time()) . ".$db_name";
$parts = explode(".",$image1);
$extension = end($parts);
$result_big = str_replace("." . $extension,"",$image1);
$handle->file_new_name_body = $result_big;
$handle->image_resize = true;
$handle->image_x = 460;
$handle->image_ratio_y = true;
// $handle->image_y = 400;
$handle->Process($dir_dest);
//Thumbnail
$db_name = str_replace(" ","_",$mainame);
$image1 = md5(rand() * time()) . ".$db_name";
$parts = explode(".",$image1);
$extension = end($parts);
$result_small = str_replace("." . $extension,"",$image1);
$handle->file_new_name_body = $result_small;
$handle->image_resize = true;
$handle->image_x = 180;
$handle->image_ratio_y = true;
// $handle->image_y = 120;
$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 (file_name, pd_image, pd_thumbnail) VALUES('$nome','$result_big', '$result_small')";
$result2 = dbQuery($query_img);
} else {
echo 'error : ' . $handle->error;
}
}
}
// END SCRIPT UPLOAD MULTI IMAGES
header("Location: index.php");
}
You are removing the extension with this code
$result_big = str_replace("." . $extension,"",$image1);
I dont know why you do that. anyway you can add it back by adding following line after the $handle->file_new_name_body = $result_big;
$handle->file_new_name_ext = $extension;
You have replaced the extention with empty string here using str_replace
$result_small = str_replace("." . $extension,"",$image1);
and here
$result_big = str_replace("." . $extension,"",$image1);
update below lines just add .$extension at the end
$handle->file_new_name_body = $result_big.$extension;
and
$handle->file_new_name_body = $result_small.$extension;
just change query like this
$query_img="INSERT into tbl_images (
file_name,
pd_image,
pd_thumbnail
) VALUES (
'$nome',
'{$result_big}.{$extension}',
'{$result_small}.{$extension}')";
I will suggest you to have same filename for pd_image and pd_thumbnail, just prefix thumb with thumb_ that will make your life easier in front end.
this way you can access any image thumbnail just by prefixing it with thumb_ with pd_image and you don't have to store pd_thumbnail in database.
Related
When I upload an image file to the host, why the file repeat filename extension again ? I check the filename in the host is like test.jpg.jpg
Here is the code:
$uploadPath = "../../upload/Image/";
$handle = new Upload($_FILES['pic'], 'zh_TW');
if($handle->uploaded){
$pic=$_FILES['pic']['name'];
if($pic != ''){
$filename = $pic;
}
else{
$microSecond = microtime();
$filename = substr($microSecond, 11, 20).substr($microSecond, 2, 8);
}
$handle->file_new_name_body = $filename;
$handle->image_resize = true;
$handle->image_ratio_y = true;
$handle->image_x = 212;
$handle->image_ratio_fill = true;
$handle->allowed = array('image/*');
$handle->file_overwrite = true;
$handle->process($uploadPath);
if($handle->processed){
$handle->file_dst_name = $filename;
}
else{
echo "<script>";
echo "alert('$handle->error');";
echo "history.back();";
echo "</script>";
die;
}
}
else{
$filename = $_POST['currentPic'];
}
Base on your conditions. you can just get the name onle part by explode function.
if($handle->uploaded){
$pic=$_FILES['pic']['name'];
if($pic != ''){
//$filename = $pic;
$filename = explode(".",$pic)[0];
}
else{
$microSecond = microtime();
$filename = substr($microSecond, 11, 20).substr($microSecond, 2, 8);
}
This is so you dont need to modify your class, also if you modify your class you will get trouble on the "ELSE" side of your condition that will cause additional spending time where to get the extension.
I have codeigniter application, Now i need to Upload excel using the codigniter.
How to do that. I follow some Online tutorials, but there are not complete one. Specially there are no what is the library they use.
if(isset($_POST['Submit']))
{
$mimes = array('application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.oasis.opendocument.spreadsheet','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
if(in_array($_FILES["file"]["type"],$mimes))
{
$uploadFilePath = 'uploads/'.basename($_FILES['file']['name']);
$filename = pathinfo($uploadFilePath);
$f = array("name"=>$filename['filename']);
foreach ($f as $k)
{
$policy = $k;
}
move_uploaded_file($_FILES['file']['tmp_name'], $uploadFilePath);
$Reader = new SpreadsheetReader($uploadFilePath);
$totalSheet = count($Reader->sheets());
//echo "You have total ".$totalSheet." sheets".
/* For Loop for all sheets */
for($i=0;$i<$totalSheet;$i++)
{
$Reader->ChangeSheet($i);
foreach ($Reader as $Row)
{
$treeno ++;
$policyno = isset($Row[0]) ? $Row[0] : '';
$act_treeno = isset($Row[1]) ? $Row[1] : '';
$dbh = isset($Row[2]) ? $Row[2] : '';
$height = isset($Row[3]) ? $Row[3] : '';
$pno = substr($policyno, -6);
$treeno = $pno.'_'.$act_treeno.'_T';
$query = "insert into tbl_trees(policyno,actual_treeno,dbh,height,treeno) values('".$policyno."','".$act_treeno."','".$dbh."','".$height."','".$treeno."')";
echo '</br>';
$mysqli->query($query);
this is work, but i have not idea to use this method in codeigniter.
First think you need upload that file then try open and prepare data for insert-
$fileName = $_FILES['file']['name'];
$uploadData = array();
if (!empty($fileName)) {
$config['upload_path'] = './your location/';
$config['allowed_types'] = 'txt|csv|xls|xlsx';
$config['max_size'] = 2048;
$config['remove_spaces'] = TRUE;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('file')) {
json_error("File Upload Error", $this->upload->display_errors(), 400);
} else {
$uploadData = array('upload_data' => $this->upload->data());
}
}//if
prepare data for insert-
if (!empty($uploadData)) {
$fileName = $uploadData['upload_data']['file_name'];
$data = array(); //empty array;
$fileInfo = fopen(base_url() . 'your file location/' . $fileName, "r");
$i = 0;
while (!feof($fileInfo)) {
$colInfo = fgets($fileInfo); //fgets means read file in line by line.
//prefer data to save
$data[$i]['your_column'] = $colInfo;
$i++;
}//while
fclose($fileInfo);
}
insert batch data-
$this->db->insert_batch('dbtable', $data);
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;
}
I have a script that:
goes through each folder and subfolder of my "./sample/" directory
opens each .docx file
replaces a string such as "##PROPERTY##" with my $_POST['property'] variable
zips the folder content
launches a download
Now, running portions of the code individually, it does what is needed. However, when putting it all together, it dies while scanning the subfolders for docx files.
My folder structure is like this:
./sample/
/IT/it1.docx
/F&B/fb1.docx
/FO/fo1.docx
sample1.docx
The problem seems to occur during the is_dir($dir) part for the level 1 folders.
Any ideas what could cause this?
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// form variables
$holidex = strtoupper($_POST['holidex']);
$property = $_POST['property'];
$brand = $_POST['brand'];
$division = $_POST['division'];
$language = $_POST['language'];
$date_issued = $_POST['date_issued'];
$approved_by = $_POST['approved_by'];
// script variables
//$dir = './Sample_SOP_-_'.$brand.'_('.$language.')'; //dir to scan like ./sample/
$dir = './sample/'; //dir to scan like ./sample/
$archive = date("Y-m-d H-i-s"); //UNIQUE name of zip file to create and download
$zipfile = "./".$holidex." - ".$archive.".zip"; //path to zip file download
$temp = "./temp/"; //directory to temp folder
// string replacements
$find = "##PROPERTY##"; // find and replace property information
$replace = $_POST['property'];
$find2 = "##BRAND##"; // find and replace brand information
$replace2 = $_POST['brand'];
$find3 = "##DATE##"; // find and replace effective date
$replace3 = $_POST['date_issued'];
$find4 = "##APPROVED_BY##"; // find and replace approved by
$replace4 = $_POST['approved_by'];
//read dir
$files = scandir($dir, 1);
//create new archive name
$zip_download = new ZipArchive();
$zip_download->open("$zipfile", ZipArchive::CREATE);
foreach($files as $file) {
//docx
$ext1 = ".docx";
$checkextension = explode($ext1, $file);
if (count($checkextension) > 1) {
$zip = new ZipArchive;
$zip->open("$file");
$word = $zip->getFromName('word/document.xml');
$word2 = str_replace($find, $replace, $word);
$word2 = str_replace($find2, $replace2, $word);
$word2 = str_replace($find3, $replace3, $word);
$word2 = str_replace($find4, $replace4, $word);
$zip->addFromString("word/document.xml", $word2);
$zip->close();
} else {
die("Error - There are no files the directory..");
}
//folders level 1
if (is_dir($file)) {
$sub = $file . '/';
$subfiles = scandir($sub, 1);
if ($subfiles > 1) {
if ($sub == "../" || $sub == "./") {
}
else {
foreach($subfiles as $subfile) {
//docx
$ext1 = ".docx";
$checkextensionsub = explode($ext1, $subfile);
$subsubfile = $sub . $subfile;
if (count($checkextensionsub) > 1) {
$zipsub = new ZipArchive;
$zipsub->open("$subsubfile");
$wordsub = $zipsub->getFromName('word/document.xml');
$word2sub = str_replace($find, $replace, $wordsub);
$word2sub = str_replace($find2, $replace2, $wordsub);
$word2sub = str_replace($find3, $replace3, $wordsub);
$word2sub = str_replace($find4, $replace4, $wordsub);
$zipsub->addFromString("word/document.xml", $word2sub);
$zipsub->close();
}
//folders level 2
$sub2 = $sub . $subfile;
if (is_dir($sub2)) {
$subfiles2 = scandir($sub2, 1);
if ($subfiles2 > 1) {
if ($sub2 == $sub.".." || $sub2 == $sub.".") {
}
else {
foreach($subfiles2 as $subfile2) {
//docx
$ext1 = ".docx";
$checkextensionsub2 = explode($ext1, $subfile2);
$subsubfile2 = $sub2 . '/' . $subfile2;
if (count($checkextensionsub2) > 1) {
$zipsub2 = new ZipArchive;
$zipsub2->open("$subsubfile2");
$wordsub2 = $zipsub2->getFromName('word/document.xml');
$word2sub2 = str_replace($find, $replace, $wordsub2);
$word2sub2 = str_replace($find2, $replace2, $wordsub2);
$word2sub2 = str_replace($find3, $replace3, $wordsub2);
$word2sub2 = str_replace($find4, $replace4, $wordsub2);
$zipsub2->addFromString("word/document.xml", $word2sub2);
$zipsub2->close();
}
//more directories when needed
//****replicate code here****
//add files to archive
$zip_download->addFile($subsubfile2, $subsubfile2);
}
}
}
}
//add files to archive
$zip_download->addFile($subsubfile, $subsubfile);
}
}
}
} else {
die ("Error - No files in the directory");
}
}
//add files to archive
$zip_download->addFile($file, $file);
}
$zip_download->close();
//download zip
if (file_exists($zipfile) && is_readable($zipfile)) {
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($zipfile));
header('Content-Disposition: attachment; filename="'.basename($zipfile).'";');
header('Content-Transfer-Encoding: binary');
$file_download = # fopen($zipfile, 'rb');
if ($file_download) {
fpassthru($file_download);
exit;
}
echo ("ZIP generated successfully, download is starting...");
} else {
echo ("Error creating the ZIP archive!");
}
}
?>
I think it's because Scandir() will produce something like
`Array
(
...
[9] => .
[10] => ..`
at the end of the arrayand when you check those if they are folders maybe an error occurs and dies.
I am using class.upload.php and I have the code all working except I want to extend the my script to work with multiple file uploads I read the documentation on the website and was able to figure it out. However I need my image files output like m_1234_1, m_1234_3, m_1234_4 and so on... How does one make it so that $handle->file_new_name_body = $new_name; starts with $new_name.'1' and continues adding 1 to every iteration?
<?php
$id = $_GET['id'];
if(isset($_POST['submit'])) {
// define variables
$new_name = 'm_'.$id.'_';
$thumb_name = 't_'.$id.'_';
$ext = 'jpg';
$upload_path = 'images/uploads/'.$id.'/'; // will not work with /images/
$full_src = $upload_path.$new_name.'.'.$ext;
// end define variables
$files = array();
foreach ($_FILES['userfile'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
foreach ($files as $file) {
$handle = new upload($_FILES['userfile']);
if ($handle->uploaded) {
// save uploaded image 458 x 332
$handle->file_new_name_body = $new_name;
$handle->image_convert = $ext;
$handle->allowed = array('image/*');
$handle->jpeg_quality = 95;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 458;
$handle->image_y = 332;
$handle->file_overwrite = true;
$handle->auto_create_dir = true;
$handle->process($upload_path);
if ($handle->processed) {
mysql_select_db($db);
mysql_query("UPDATE projects SET last_modified=NOW(), project_image_1 = '".$full_src."' WHERE id = $id") or die(mysql_error());
} else {
echo '<div class="ec-messages messages-error">';
echo 'Error: ' . $handle->error;
echo '</div>';
}
// create thumbnail 104 x 76
$handle->file_new_name_body = $thumb_name;
$handle->image_convert = $ext;
$handle->allowed = array('image/*');
$handle->jpeg_quality = 90;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 104;
$handle->image_y = 76;
$handle->file_overwrite = true;
$handle->auto_create_dir = true;
$handle->process($upload_path);
if ($handle->processed) {
echo '<div class="ec-messages messages-success">Image successfully uploaded and added to database (thumnails created)<br>Redirecting to projects main...</div><br><img src="'.$full_src.'" class="display-image">';
echo "<script>setTimeout(\"location.href='projects.php?msg=insert';\",2000);</script>";
include('Templates/footer_exit.php');
$handle->clean();
exit;
} else {
// no error here, error will be handled by the first script
}
}
}
}
?>
UPDATED (now working):
<?php
$id = $_GET['id'];
if(isset($_POST['submit'])) {
// define variables
$ext = 'jpg';
$upload_path = 'images/uploads/'.$id.'/'; // will not work with /images/
// end define variables
$files = array();
foreach ($_FILES['userfile'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
$counter = 1;
foreach ($files as $file) {
//$append = rand(100,99999);
$new_name = 'm_'.$id;
$thumb_name = 't_'.$id;
$handle = new upload($file);
if ($handle->uploaded) {
// save uploaded image 458 x 332
$count = $counter++;
$nn = sprintf("%s_%d", $new_name, $count);
$full_src = $upload_path.$nn.'.'.$ext;
$handle->file_new_name_body = $nn;
$handle->image_convert = $ext;
$handle->allowed = array('image/*');
$handle->jpeg_quality = 95;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 458;
$handle->image_y = 332;
$handle->file_overwrite = true;
$handle->auto_create_dir = true;
$handle->process($upload_path);
if ($handle->processed) {
mysql_select_db($db);
mysql_query("UPDATE projects SET last_modified=NOW(), project_image_".$count." = '".$full_src."' WHERE id = $id") or die(mysql_error());
} else {
echo '<div class="ec-messages messages-error">';
echo 'Error: ' . $handle->error;
echo '</div>';
}
// create thumbnail 104 x 76
$tn = sprintf("%s_%d", $thumb_name, $count);
$handle->file_new_name_body = $tn;
$handle->image_convert = $ext;
$handle->allowed = array('image/*');
$handle->jpeg_quality = 90;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 104;
$handle->image_y = 76;
$handle->file_overwrite = true;
$handle->auto_create_dir = true;
$handle->process($upload_path);
if ($handle->processed) {
echo 'Done!';
/*
echo '<div class="ec-messages messages-success">Image successfully uploaded and added to database (thumnails created)<br>Redirecting to projects main...</div><br><img src="'.$full_src.'" class="display-image">';
echo "<script>setTimeout(\"location.href='projects.php?msg=insert';\",2000);</script>";
include('Templates/footer_exit.php');
$handle->clean();
exit;
*/
} else {
// no error here, error will be handled by the first script
}
}
}
}
?>
You might define
$new_name = 'm_'.$id.'_';
$counter = 1; // File counter
at the beginning, and replace that line with
$handle->file_new_name_body = sprintf("%s.%d", $new_name, $counter++);
so that 'file' would become 'file.1.jpg', and so on.