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);
Related
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'];
}
}
}
I have a code
if(count($_FILES) > 0) {
foreach($_FILES['fileAttach']['error'] as $status){
if($status === UPLOAD_ERR_OK) {
$fname[] = $_FILES['fileAttach']['name'][$Ccount];
$tmp_path[] = $_FILES['fileAttach']['tmp_name'][$Ccount];
$ftype[] = $_FILES['fileAttach']['type'][$Ccount];
}
$Ccount++;
}
} else { $fname[] = "0"; $tmp_path[] = "0"; $ftype[] = "0"; } // this not working
Then i want to use variables in function
SendEmails($ReCEmail,$strSubject,$strMessage,$txtFormName,$txtFormEmail,$fname,$ftype,$tmp_path);
It works until files is attached, but if no i got error Notice: Undefined variable: fname in ... on line ..
function SendEmails($vasia,$strSubject,$strMessage,$txtFormName,$txtFormEmail,$fname,$ftypes,$tmp_path) {
if(count($fname) == 0)
{ code without variables $fname,$ftypes,$tmp_path }
else {code with variables $fname,$ftypes,$tmp_path}
}
How to fix that?
if(count(array_filter($_FILES['fileAttach']['name'])) > 0) {
foreach($_FILES['fileAttach']['error'] as $key => $status){
if($status === 0) {
$fname[] = $_FILES['fileAttach']['name'][$key];
$tmp_path[] = $_FILES['fileAttach']['tmp_name'][$key];
$ftype[] = $_FILES['fileAttach']['type'][$key];
}
}
} else { $fname[] = "0"; $tmp_path[] = "0"; $ftype[] = "0"; }
and in your function change
if(count(array_filter($fname)) == 0)
If all $_FILES are error, then files array will be zero. So this error is printed
$fname[] = array();
$tmp_path[] = array();
$ftype[] = array();
foreach($_FILES['fileAttach']['error'] as $key => $status){
if($status === 0) {
$fname[] = $_FILES['fileAttach']['name'][$key];
$tmp_path[] = $_FILES['fileAttach']['tmp_name'][$key];
$ftype[] = $_FILES['fileAttach']['type'][$key];
}
}
if(count($fname)==0)
{ $fname[] = "0";$tmp_path[] = "0"; $ftype[] = "0"; }
Initialize your $fname array before the if:
$fname = array();
if($status === UPLOAD_ERR_OK) {
Confirm that your upload process is working by putting and echo after the if:
if($status === UPLOAD_ERR_OK) {
echo "Upload Status: " . $status . "<br>";
$fname[] = $_FILES['fileAttach']['name'][$Ccount];
If the echo output shows that $status != UPLOAD_ERR_OK, then $fname was not getting initialized, hence the Undefined variable error.
If the upload is failing, create another question containing the corresponding code snippets for that issue.
I have the code below.
It first create a dynamic folder with name like v3_12-02-2012-12873547839. Then it creates a subfolder called "image" and saves some jpeg images in the subfolder. Then it create a csv file and put it in "v3_12-02-2012-12873547839"
Then it creates a zip folder in the project folder with name "v3_12-02-2012-12873547839.zip"
function create_csv($version,$ctg,$cnt,$nt,$api)
{
$folder = $version."-".date('d-m-Y')."-".time();
if(!file_exists('./'.$folder))
{
mkdir('./'.$folder);
mkdir('./'.$folder.'/image/');
}
$cnt_table = "aw_countries_".$version;
$ctg_table = "aw_categories_".$version;
$off_table = "aw_offers_".$version;
$sizeof_ctg = count($ctg);
$cond_ctg = " ( ";
for($c = 0; $c < $sizeof_ctg ; $c++)
{
$cond_ctg = $cond_ctg." $ctg_table.category = '".$ctg[$c]."' ";
if($c < intval($sizeof_ctg-1))
$cond_ctg = $cond_ctg." OR ";
else if($c == intval($sizeof_ctg-1))
$cond_ctg = $cond_ctg." ) ";
}
$sizeof_cnt = count($cnt);
$cond_cnt = " ( ";
for($cn = 0; $cn < $sizeof_cnt ; $cn++)
{
$cond_cnt = $cond_cnt." $cnt_table.country = '".$cnt[$cn]."' ";
if($cn < intval($sizeof_cnt-1))
$cond_cnt = $cond_cnt." OR ";
else if($cn == intval($sizeof_cnt-1))
$cond_cnt = $cond_cnt." ) ";
}
$sizeof_nt = count($nt);
$cond_nt = " ( ";
for($n = 0; $n < $sizeof_nt ; $n++)
{
$cond_nt = $cond_nt." $off_table.network_id = '".$nt[$n]."' ";
if($n < intval($sizeof_nt-1))
$cond_nt = $cond_nt." OR ";
else if($n == intval($sizeof_nt-1))
$cond_nt = $cond_nt." ) ";
}
$sizeof_api = count($api);
$cond_api = " ( ";
for($a = 0; $a < $sizeof_api ; $a++)
{
$cond_api = $cond_api." $off_table.api_key = '".$api[$a]."' ";
if($a < intval($sizeof_api-1))
$cond_api = $cond_api." OR ";
else if($a == intval($sizeof_api-1))
$cond_api = $cond_api." ) ";
}
$output = "";
$sql = "SELECT DISTINCT $off_table.id,$off_table.name
FROM $off_table,$cnt_table,$ctg_table
WHERE $off_table.id = $cnt_table.id
AND $off_table.id = $ctg_table.id
AND ".$cond_api."
AND ".$cond_nt."
AND ".$cond_cnt."
AND ".$cond_ctg;
$result = mysql_query($sql);
$columns_total = mysql_num_fields($result);
for ($i = 0; $i < $columns_total; $i++)
{
$heading = mysql_field_name($result, $i);
$output .= '"'.$heading.'",';
}
$output .= '"icon"';
$output .="\n";
while ($row = mysql_fetch_array($result))
{
for ($i = 0; $i < $columns_total; $i++)
{
$output .='"'.$row["$i"].'",';
}
$sql_icon = "SELECT $off_table.icon FROM $off_table WHERE id = '".$row['id']."'";
$result_icon = mysql_query($sql_icon);
while($row_icon = mysql_fetch_array($result_icon))
{
$image = $row_icon["icon"];
$id = $row["id"];
$icon = "./$folder/image/{$id}.jpg";
$icon_link = "$folder/image/{$id}.jpg";
file_put_contents($icon, $image);
}
$output .= '"'.$icon_link.'"';
$output .="\n";
}
$filename = "myFile.csv";
$fd = fopen ( "./$folder/$filename", "w");
fputs($fd, $output);
fclose($fd);
$source = $folder;
$destination = $folder.'.zip';
$flag = '';
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', $source);
if($flag)
{
$flag = basename($source) . '/';
}
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file)
{
if (strpos($flag.$file,$source) !== false) { // this will add only the folder we want to add in zip
if (is_dir($file) === true)
{
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $flag.$file), file_get_contents($file));
}
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString($flag.basename($source), file_get_contents($source));
}
$zip->close();
if (is_dir($folder))
{
$objects = scandir($folder);
foreach ($objects as $object)
{
if ($object != "." && $object != "..")
{
if (filetype($folder."/".$object) == "dir")
{
$object_inner = scandir($folder."/".$object);
foreach ($object_inner as $object_inner)
{
if ($object_inner != "." && $object_inner != "..")
{
unlink($folder."/".$object."/".$object_inner);
}
}
rmdir($folder."/".$object);
}
else
unlink($folder."/".$object);
}
}
reset($objects);
}
rmdir("./".$folder);
}
Now the problem is, when I am trying to delete the folder, the folder somehow doesn't seem to delete, though I can recursively delete all its contents. Even though the folder becomes empty at the end, it doesn't get deleted.
Error I am getting:
Warning: rmdir(./v3-02-12-2014-1417512727): Permission denied in C:\xampp\htdocs\projecthas2offer\appwall_dev\frontend\ajax.php on line 265
Instances of ZipArchive and/or RecursiveIteratorIterator still live and might still have their hands on your directory, so free them using unset( $zip, $files );
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP - Upload multiple images
I want to upload multiple images using PHP and I am stuck. I have the code but it uploads only 1 image.
<?php
if (isset($_POST['newuser'])) {
if ((!empty($_POST['year'])) AND (!empty($_POST['make'])) AND (!empty($_POST['model'])) AND (!empty($_POST['engine'])) AND (!empty($_POST['mileage'])) AND (!empty($_POST['exterior'])) AND (!empty($_POST['interior'])) AND (!empty($_POST['transmission'])) AND (!empty($_POST['body'])) AND (!empty($_POST['fuel'])) AND (!empty($_POST['drive'])) AND (!empty($_POST['doors'])) AND (!empty($_POST['description']))) {
$year = htmlspecialchars($_POST['year']);
$make = htmlspecialchars($_POST['make']);
$model = htmlspecialchars($_POST['model']);
$engine = htmlspecialchars($_POST['engine']);
$mileage = htmlspecialchars($_POST['mileage']);
$exterior = htmlspecialchars($_POST['exterior']);
$interior = htmlspecialchars($_POST['interior']);
$transmission = htmlspecialchars($_POST['transmission']);
$body = htmlspecialchars($_POST['body']);
$fuel = htmlspecialchars($_POST['fuel']);
$drive = htmlspecialchars($_POST['drive']);
$doors = htmlspecialchars($_POST['doors']);
$description = htmlspecialchars($_POST['description']);
$target = "images/default.jpg";
$msg = "";
if (!empty($_FILES['fisier']['name'])) {
$target = "images/";
$target = $target . basename($_FILES['fisier']['name']);
$file_size = $_FILES['fisier']['size'];
$file_type = $_FILES['fisier']['type'];
$ok = 1;
if ($file_size > 2048000) {
echo "Too large";
$ok = 0;
}
if ($file_type == "application/octet-stream") {
echo "no PHP";
$ok = 0;
}
if ($ok == 0) {
echo "No file saved";
} else {
if (!move_uploaded_file($_FILES['fisier']['tmp_name'],$target)) {
$target = "images/default.jpg";
$msg = "No file saved. ";
}
}
}
require_once("mysql_connect.php");
$sql = "INSERT INTO astonmartin VALUES('','$year','$make','$model','$engine','$mileage','$exterior','$interior','$transmission','$body','$fuel','$drive','$doors','$description','$target','$target2','$target3','$target4','$target5','$target6')";
mysql_query($sql) or die(mysql_error());
$msg .= "";
header("Location: add_user.php?msg=$msg");
} else {
$error = "Complete form";
}
}
?>
I think you need first this function assoc, here: multidimensional for loops in php
And continue;
<?php
$allowed_types = array(
'image/gif',
'image/jpeg',
// add your mime types more
);
if (isset($_POST['newuser'])) {
if ((!empty($_POST['year'])) AND ...
// that gives an associative array
// i think it's more handy in your case
$files = assoc($_FILES['fisier']);
// now you have a files like
// tmp_name => d:\tmp\abs123, name => cats.jpg, size => 128 ..
// tmp_name => d:\tmp\abs254, name => dogs.jpg, size => 211 ..
// ... more code here
// and here, remove this line
if (!empty($_FILES['fisier']['name'])) {
// put this. yes 6, cos you want 6 pics
if (count($files) == 6) {
// loop over files
foreach ($files as $i => $file) {
// create targets, securely
$targets[$i] =
'images/'. preg_replace('~[^\w\d\.]~i', '',
basename($file['name']));
// check some errors
if ($file['error'] == 0 && $file['size'] < 2048000
// check file type
&& in_array($file['type'], $allowed_types)) {
if (!move_uploaded_file(
$file['tmp_name'], 'images/'. $file['name'])) {
$targets[$i] = 'images/default.jpg';
// collect messages
$messages[] = $file['name'] . ' not saved!';
}
}
}
}
// and creating target 1 2 3 ...
$targets_string = '';
if (!empty($targets)) {
// this provides: '$target', '$target2', '$target3' ...
$targets_string = "'". join("', '", $targets) ."'";
}
// ... more code here
// and sql part
$sql = "INSERT INTO astonmartin VALUES('', '$year', '$make', ..."
// add target string
. "'$description', $targets_string";
// ... more code here
// msg part
$msg = empty($messages) ? '' : join('', $messages);
header("Location: add_user.php?msg=$msg");
?>
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