I'm trying to upload a edited csv file, but after submission it do not redirect
with valid message. Actually if any error in the edited csv file it should give the error msg, otherwise success msg.
I want to upload the mark sheet of a particular subject, if the entered mark is not in numeric or it is exceeding the maximum mark valid messages will be displayed and redirect back to my view page.
function import_academic_excel()
{
$optional_index = 0;
if ($this->input->post('submit'))
{
$config['upload_path'] = './application/temp_upload/';
$config['allowed_types'] = 'csv';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile'))
{
$data = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('msg_excel','Choose a .csv file to upload.');
redirect(base_url().'import_evaluation_sheet');
}
else
{
$count_numeric = 0;
$count_maximum = 0;
foreach($result as $field)
{
if($standard == 11 || $standard == 12)
{
if($evaluation_name == 'ta1' || $evaluation_name == 'ta2' || $evaluation_name == 'ta3')
{
if($subject_name == 'physics' || $subject_name == 'chemistry' || $subject_name == 'computer_science')
{
$theory_name=$subject_name.'_theory';
$practical_name=$subject_name.'_practical';
if($field[$theory_name] == '' )
{
$field[$theory_name]= 0;
}
if($field[$practical_name] == '' )
{
$field[$practical_name]= 0;
}
if($field[$theory_name] != 'ab')
{
if(!is_numeric($field[$theory_name]))
{
$count_numeric = $count_numeric + 1;
}
if($field[$theory_name] > $theory_mark)
{
$count_maximum = $count_maximum + 1;
}
}
}
}
}
}
}
if($count_numeric > 0)
{
$this->session->set_flashdata('msg_excel','Please check the marks entered in the file, some marks are not numeric.');
redirect(base_url().'import_evaluation_sheet');
}
if($count_maximum > 0)
{
$this->session->set_flashdata('msg_excel','Please check the marks entered in the file, some marks exceeds the maximum marks.');
redirect(base_url().'import_evaluation_sheet');
}
$update_result= $this->data->update_chapter($result,$subject_name,$evaluation_name,$optional_index,$standard,$tool_id);
$this->session->set_flashdata('msg_excel_success','Updated data successfully');
redirect(base_url().'import_evaluation_sheet');
}
}
The loops are working, but it can't enter to the last two if loops.
If I am entering valid csv file it will reflect in the data, but success msg can't displayed.
Related
I have the following script that sends an image, directory name, and possible alternative filename to an action url in a php file.
$(document).ready(function() {
$(".layout-save").click(function(e) {
e.preventDefault();
var form = $(".image_define");
var params = form.serializeArray();
var formData = new FormData();
formData.append('default_image', $('#default_image')[0].files[0]);
$(params).each(function (index, element) {
formData.append(element.name, element.value);
});
$.ajax({
url: form.attr('action'),
method: "post",
data: formData,
contentType: false,
processData: false
})
.done(function(data) {
var obj = JSON.parse(data);
$('.tooltip-imageHandler-<?php echo $products_filter; ?>').tooltipster('close');
var elem = $('.image-<?php echo $products_filter; ?>');
elem.fadeOut('slow', function() {
elem.html(obj.asHtml).fadeIn('slow', function() {
elem.delay(1200).fadeOut('slow', function() {
elem.html(obj.products_image).fadeIn('slow');
});
});
});
})
.fail(function(){
alert('Ajax Submit for New Image Save Failed ...');
});
});
});
What I was trying to achieve was to send back a success message that I can display in the class image-xxx, where xxx is a product id, thus giving unique class names when there are multiple instances on the page.
File upload is working ok, and the tooltip closes correctly. I added the following line of code inside my "save" case, just after the final sql query that updates the database:
echo json_encode(array("products_image"=>$data['defaultFileName'], "asHtml" => '<div class="alert alert-info update-notice update-'.$products_filter.'"><strong>Product image updated</strong></div>'));
I was expecting to be able to use this to display the success message, and then update the div with the newly uploaded image.
However, when testing I am getting the following in the console
"VM3150:2 Uncaught SyntaxError: Unexpected token < in JSON at position 162"
and if I console.log(data) I am seeing the parsed php for the page rather than just "products_image" and "asHtml".
Can anyone offer some pointers as to what I've done wrong here?
Note: Whilst I know I could take the data that was submitted via the form, I really need the information after it has been processed because it makes decisions on the file path and image naming etc depending on if it is a first, or additional image before it writes to the database.
Added the php from the file where if ($action == 'save') is located. The json_encode is approx 12 lines before the end, right after the original (pre ajax modification)success message would be displayed.
if ($action == 'save') {
// -----
// Log the input values on entry, if debug is enabled.
//
$ih_admin->debugLog(
'ih_manager/save, on entry.' . PHP_EOL .
'$_GET:' . PHP_EOL . var_export($_GET, true) . PHP_EOL .
'$_POST:' . PHP_EOL . var_export($_POST, true) . PHP_EOL .
'$_FILES:' . PHP_EOL . var_export($_FILES, true)
);
// -----
// Set some processing flags, based on the type of upload being performed.
//
$editing = (isset($_GET['imgEdit']) && $_GET['imgEdit'] == '1');
$new_image = (isset($_GET['newImg']) && $_GET['newImg'] == '1');
$main_image = (!isset($_GET['imgSuffix']) || $_GET['imgSuffix'] == '');
$keep_name = (isset($_POST['imgNaming']) && $_POST['imgNaming'] == 'keep_name');
$data = array();
$data_ok = true;
// -----
// Determine the extension required for any uploaded images.
//
// 1) A new main-image (and any medium/large) use the extension from the (required) default image suppied.
// 2) A new additional image's files use the extension from the pre-existing main-image.
// 3) Editing an image uses the pre-existing file extension.
//
if ($new_image) {
if ($_FILES['default_image']['name'] == '') {
$messageStack->add(TEXT_MSG_NO_DEFAULT, 'error');
$data_ok = false;
} else {
$data['imgExtension'] = '.' . pathinfo($_FILES['default_image']['name'], PATHINFO_EXTENSION);
}
} else {
$data['imgExtension'] = $_GET['imgExtension'];
}
// -----
// If the file-upload is in support of a new main image or the main image is being edited ...
//
if ($new_image || ($editing && $main_image && !$keep_name && $_FILES['default_image']['name'] != '')) {
// New Image Name and Base Dir
if (isset($_POST['imgBase']) && $_POST['imgBase'] != '') {
$data['imgBase'] = $_POST['imgBase'];
} else {
// Extract the name from the default file
if ($_FILES['default_image']['name'] != '') {
$data['imgBase'] = pathinfo($_FILES['default_image']['name'], PATHINFO_FILENAME);
} else {
$messageStack->add(TEXT_MSG_AUTO_BASE_ERROR, 'error');
$data_ok = false;
}
}
// catch nasty characters
if (strpos($data['imgBase'], '+') !== false) {
$data['imgBase'] = str_replace('+', '-', $data['imgBase']);
$messageStack->add(TEXT_MSG_AUTO_REPLACE . $data['imgBase'], 'warning');
}
if (isset($_POST['imgNewBaseDir']) && $_POST['imgNewBaseDir'] != '') {
$data['imgBaseDir'] = $_POST['imgNewBaseDir'];
} elseif (isset($_POST['imgBaseDir'])) {
$data['imgBaseDir'] = $_POST['imgBaseDir'];
} else {
$data['imgBaseDir'] = $_GET['imgBaseDir'];
}
$data['imgSuffix'] = '';
// -----
// Otherwise, if we're editing an additional product image ...
//
} elseif ($editing) {
$data['imgBaseDir'] = $_GET['imgBaseDir'];
$data['imgBase'] = $_GET['imgBase'];
$data['imgSuffix'] = $_GET['imgSuffix'];
// -----
// Otherwise, we're adding an additional product image ...
//
} else {
// An additional image is being added
$data['imgBaseDir'] = $_GET['imgBaseDir'];
$data['imgBase'] = $_GET['imgBase'];
// Image Suffix (if set)
if ($_POST['imgSuffix'] != '') {
$data['imgSuffix'] = '_' . $_POST['imgSuffix'];
} else {
// -----
// Get additional images' list; the class function takes care of sorting the files
//
$matching_files = array();
$ih_admin->findAdditionalImages($matching_files, $data['imgBaseDir'], $data['imgExtension'], $data['imgBase']);
// -----
// If no additional images exist, use the _01 suffix.
//
$file_count = count($matching_files);
if ($file_count == 1) {
$data['imgSuffix'] = '_01';
} else {
// -----
// Otherwise, find the first unused suffix in the range _01 to _99. Note that the first
// (ignored) element of the find-array "should be" the main image's name!
//
for ($suffix = 1, $found = false; $suffix < 99; $suffix++) {
$suffix_string = sprintf('_%02u', $suffix);
if (!in_array($data['imgBase'] . $suffix_string . $data['imgExtension'], $matching_files)) {
$found = true;
$data['imgSuffix'] = $suffix_string;
break;
}
}
if (!$found) {
$messageStack->add('Could not find an unused additional-image suffix in the range _01 to _99.', 'error');
$data_ok = false;
}
}
}
}
// determine the filenames
if ($data_ok) {
// add slash to base dir
if ($data['imgBaseDir'] != '') {
if (substr($data['imgBaseDir'], -1) != '/' && substr($data['imgBaseDir'], -1) != '\\') {
$data['imgBaseDir'] .= '/';
}
}
$data['defaultFileName'] = $data['imgBaseDir'] . $data['imgBase'] . $data['imgSuffix'] . $data['imgExtension'];
// Check if the file already exists
if ($editing && file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . $data['defaultFileName'])) {
$messageStack->add(TEXT_MSG_FILE_EXISTS, 'error' );
$data_ok = false;
}
}
// -----
// If no previous errors and we're either (a) creating a new main-image or (b) editing the main-image and a new name
// is requested ...
//
if ($data_ok && $new_image || ($editing && $main_image && !$keep_name && $_FILES['default_image']['name'] != '')) {
// -----
// ... first, check to see that the image's name is going to fit into the database field.
//
if (strlen($data['defaultFileName']) > zen_field_length(TABLE_PRODUCTS, 'products_image')) {
$messageStack->add(sprintf(TEXT_MSG_NAME_TOO_LONG_ERROR, $data['defaultFileName'], zen_field_length(TABLE_PRODUCTS, 'products_image')), 'error');
$data_ok = false;
} else {
// update the database
$sql =
"UPDATE " . TABLE_PRODUCTS . "
SET products_image = '" . $data['defaultFileName'] . "'
WHERE products_id = " . (int)$products_filter . "
LIMIT 1";
if (!$db->Execute($sql)) {
$messageStack->add(TEXT_MSG_INVALID_SQL, "error");
$data_ok = false;
}
}
}
if ($data_ok) {
// check for destination directory and create, if they don't exist!
// Then move uploaded file to its new destination
// default image
if ($_FILES['default_image']['name'] != '') {
io_makeFileDir(DIR_FS_CATALOG_IMAGES . $data['defaultFileName']);
$source_name = $_FILES['default_image']['tmp_name'];
$destination_name = DIR_FS_CATALOG_IMAGES . $data['defaultFileName'];
if (!move_uploaded_file($source_name, $destination_name)) {
$messageStack->add(TEXT_MSG_NOUPLOAD_DEFAULT, "error" );
$data_ok = false;
}
} elseif ($_FILES['default_image']['name'] == '' && !$editing) {
// Nigel Hack for special idiots
io_makeFileDir(DIR_FS_CATALOG_IMAGES.$data['defaultFileName']);
$source_name = $_FILES['default_image']['tmp_name'];
$destination_name = DIR_FS_CATALOG_IMAGES . $data['defaultFileName'];
if (!move_uploaded_file($source_name, $destination_name) ) {
$messageStack->add( 'you must select a default image', "error" );
$data_ok = false;
$_FILES['medium_image']['name'] = $_FILES['large_image']['name'] = '';
}
} // End special idiots hack
// medium image
if ($_FILES['medium_image']['name'] != '') {
$data['mediumImgExtension'] = substr( $_FILES['medium_image']['name'], strrpos($_FILES['medium_image']['name'], '.'));
$data['mediumFileName'] ='medium/' . $data['imgBaseDir'] . $data['imgBase'] . $data['imgSuffix'] . IMAGE_SUFFIX_MEDIUM . $data['mediumImgExtension'];
io_makeFileDir(DIR_FS_CATALOG_IMAGES.$data['mediumFileName']);
$source_name = $_FILES['medium_image']['tmp_name'];
$destination_name = DIR_FS_CATALOG_IMAGES . $data['mediumFileName'];
if (!move_uploaded_file($source_name, $destination_name)) {
$messageStack->add( TEXT_MSG_NOUPLOAD_MEDIUM, "error" );
$data_ok = false;
}
}
// large image
if ($_FILES['large_image']['name'] != '') {
$data['largeImgExtension'] = substr( $_FILES['large_image']['name'], strrpos($_FILES['large_image']['name'], '.'));
$data['largeFileName'] = 'large/' . $data['imgBaseDir'] . $data['imgBase'] . $data['imgSuffix'] . IMAGE_SUFFIX_LARGE . $data['largeImgExtension'];
io_makeFileDir(DIR_FS_CATALOG_IMAGES.$data['largeFileName']);
$source_name = $_FILES['large_image']['tmp_name'];
$destination_name = DIR_FS_CATALOG_IMAGES . $data['largeFileName'];
if (!move_uploaded_file($source_name, $destination_name)) {
$messageStack->add( TEXT_MSG_NOUPLOAD_LARGE, "error" );
$data_ok = false;
}
}
}
if (!$data_ok) {
if ($editing) {
$action = "layout_edit";
} else {
$action = "layout_new";
}
} else {
// Data has been saved
// show the new image information
$messageStack->add(TEXT_MSG_IMAGE_SAVED, 'success');
echo json_encode(array("products_image"=>$data['defaultFileName'], "asHtml" => '<div class="alert alert-info update-notice update-'.$products_filter.'"><strong>Product image updated</strong></div>'));
// we might need to clear the cache if filenames are kept
if ($editing) {
$error = bmz_clear_cache();
if (!$error) {
$messageStack->add(IH_CACHE_CLEARED, 'success');
}
}
$_GET['imgName'] = $data['imgBase'] . $data['imgSuffix'];
$action = "layout_info";
}
}
One point I would make is that when looking at console log in dev tools, it is highlighting the first character of the file the form resides in, which IS NOT the file that the json_encode is in. Code structure has the form in file A, which is actioned in file B. File B contains the json_encode response I want to send, but the error is showing the html content of file A, as well as the son data. A snippet of it is here.
{"products_image":"Teal-Shirt-min_01.jpg","asHtml":"<div class=\"alert alert-info update-notice update-310\"><strong>Product image updated<\/strong><\/div>"}
<div class="container-fluid">
<div id="ih-head">
<h1>Image Handler<sup>5</sup></h1>
</div>
<div id="defaultContent">
<div class="row">
<div class="col-md-6 col-sm-12 no-padding">
<div class="ih-heading pull-left">Product</div>
<div class="ih-info pull-left"> #310 — Teal T-Shrt</div>
</div>
<div class="col-md-6 col-sm-12 no-padding">
<div class="ih-heading pull-left">Image Directory</div>
<div class="ih-info pull-left"> images/</div>
</div>
</div>
<hr>
Given you are getting back the contents of the current page, my guess is that your ajax request is NOT setup right.
"url" should be set to the url of the script that you want to process the data and return the response. If "url" is not set it defaults to the "CURRENT URL".
So I am thinking you want something like below for your URL...
.ajax({
url: "/myapp/myJsonResponseScript.php",
....
Pass your action value in a data option for the ajax call.
This application creates a new folder every time a new files are uploaded and insert these files inside the created folder.
The code below works fine but Im a bit confused. Because of multiple uploading I can not check if something was uploaded or not
and I lose a control with the created folder, because it is created even if I do not upload files (only submit the form).
Why is that the folder is created when I only submit form? Because the "UPLOAD_ERR_OK" is checking the form after the folder is crated (first is "mkdir" and after "UPLOAD_ERR_OK" (but it have to be this way, because of loop ([$i]!))).
What I want to do is to put UPLOAD_ERR_OK at the start, but i can not, because it must contains an array [$i]! In a single upload "if ($_FILES['img']['error'] == UPLOAD_ERR_OK)" works fine, but
does not in multi , because of the array.
The script below has stages:
create folder
if files havent errors
upload files to folder
It is wrong, because the folder is created at the start even if we upload empty form and the form is checked after, so it creates a folder and make error "UPLOAD_ERR_NO_FILE". But it is impossible to first check errors and then create folder, because arrors are checking with an array after loop.
if (!file_exists($pre_path)) // if no folder
{
if (mkdir($pre_path, 0777)) // create folder
{
for ($i=0; $i < count($_FILES['img']['name']) $i++) //LOOP
{
if ($_FILES['img']['error'][$i] == UPLOAD_ERR_OK) //if no error
{
//MOVE UPLOADED FILES[$i], QUERIES AND FUNCTIONS
}
elseif ( $img_error[$i] == UPLOAD_ERR_INI_SIZE) { }//show error
elseif ( $img_error[$i] == UPLOAD_ERR_FORM_SIZE) {} //show error
elseif ( $img_error[$i] == UPLOAD_ERR_PARTIAL) { } //show error
elseif ( $img_error[$i] == UPLOAD_ERR_NO_FILE) {} //show error
elseif ( $img_error[$i] == UPLOAD_ERR_NO_TMP_DIR) { } //show error
elseif ( $img_error[$i] == UPLOAD_ERR_CANT_WRITE) { } //show error
elseif ( $img_error[$i] == UPLOAD_ERR_EXTENSION) { }//show error
else { }//show error
}
}
}
I want it to be like:
1. if files havent errors (was not "UPLOAD_ERR_NO_FILE")
2. create folder
3. upload files to folder
if ($_FILES['img']['error'][$i] == UPLOAD_ERR_OK)
{
if (mkdir($pre_path, 0777))
{
for ($i=0; $i < count($_FILES['img']['name']) $i++)
{
//MOVE UPLOADED FILES[$i], QUERIES AND FUNCTIONS
}
}
}
elseif ( $img_error[$i] == UPLOAD_ERR_INI_SIZE) { }//show error
elseif ( $img_error[$i] == UPLOAD_ERR_FORM_SIZE) {} //show error
elseif ( $img_error[$i] == UPLOAD_ERR_PARTIAL) { } //show error
elseif ( $img_error[$i] == UPLOAD_ERR_NO_FILE) {} //show error
elseif ( $img_error[$i] == UPLOAD_ERR_NO_TMP_DIR) { } //show error
elseif ( $img_error[$i] == UPLOAD_ERR_CANT_WRITE) { } //show error
elseif ( $img_error[$i] == UPLOAD_ERR_EXTENSION) { }//show error
else { }//show error
What should I do to put "if ($_FILES['img']['error'][$i] == UPLOAD_ERR_OK)" with the [$i] array at the start and to create a folder after errros are checked? We cannot put mkdir inside the loop, because loop will create many folders. What do I need is only 1 folder, so it must be before the loop. :/ That's crazy.
Full code:
if (isset($_SESSION['admin'], $_POST['upload_images']))
{
$img_tmp_name = $_FILES['img']['tmp_name'];
$img_name = $_FILES['img']['name'];
$img_error = $_FILES['img']['error'];
$img_type = $_FILES['img']['type'];
$img_size = $_FILES['img']['size'];
$image_quantity = count($img_name);
$error_text = array (
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
4 => 'No file was uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk.',
8 => 'A PHP extension stopped the file upload.',
9 => 'file couldnt be moved!',
10 => 'file isnt uploaded',
11 => 'za duzy rozmiar pliku',
12 => 'obrazek musi byc w formacie JPEG',
13 => 'nie mozna stworzyc folderu',
14 => 'Query has not started, but folder has created with number: ',
15 => 'Unknown upload error'
);
$conn = lacz_bd();
if ($q = $conn->prepare('SELECT MAX(gallery_id) FROM galleries'))
{
$q->execute();
$q->bind_result($gallery_id);
$q->store_result();
while($q->fetch())
{
$improved_gallery_id = $gallery_id + 1;
}
$pre_path = ('./galerie/'.$improved_gallery_id);
//------------------------------- START UPLOAD ----------------------------------
if (!file_exists($pre_path))
{
if (mkdir($pre_path, 0777))
{
for ($i=0; $i < $image_quantity; $i++)
{
if ($img_error[$i] == UPLOAD_ERR_OK)
{
if ($img_type[$i] = 'image/jpeg') //to do: preg match instead
{
if ($img_size[$i] <= 2621440) //2,5MiB
{
if (is_uploaded_file($img_tmp_name[$i]))
{
$path = $pre_path.'/'.basename($img_name[$i]);
if (move_uploaded_file($img_tmp_name[$i], $path))
{
if ($q = $conn->prepare('INSERT INTO galleries (path, gallery_id) VALUES (?, ?)'))
{
$q->bind_param('si', $path, $improved_gallery_id);
$q->execute();
if ($q->affected_rows > 0)
{
image_compression($path, 800, 536);
echo '<a href="ustaw_miniature.php?m='.urlencode($img_name[$i]).'&gid='.urlencode($improved_gallery_id).'">';
echo '<img src="'. htmlspecialchars($path, ENT_QUOTES).'" width="80%" height="80%"></img></a><br />';
}
}
} else { echo $error_text[9]; }
} else { echo $error_text[10]; }
} else { echo $error_text[11]; }
} else { echo $error_text[12]; }
}
elseif ( $img_error[$i] == UPLOAD_ERR_INI_SIZE) { echo $error_text[1]; }
elseif ( $img_error[$i] == UPLOAD_ERR_FORM_SIZE) { echo $error_text[2]; }
elseif ( $img_error[$i] == UPLOAD_ERR_PARTIAL) { echo $error_text[3]; }
elseif ( $img_error[$i] == UPLOAD_ERR_NO_FILE) { echo $error_text[4]; }
elseif ( $img_error[$i] == UPLOAD_ERR_NO_TMP_DIR) { echo $error_text[6]; }
elseif ( $img_error[$i] == UPLOAD_ERR_CANT_WRITE) { echo $error_text[7]; }
elseif ( $img_error[$i] == UPLOAD_ERR_EXTENSION) { echo $error_text[8]; }
else { echo $error_text[15]; }
} // END FOR
}
} else { echo $error_text[14].' '.htmlspecialchars($improved_gallery_id, ENT_QUOTES);}
$q->free_result();
$q->close();
}
$conn->close();
}
I am sitting at the computer and waiting for help. Thanks. It is important for me, because I make a site for developer.
You can reorganise your conditionals so it checks and creates the folder only on the first loop $i == 0. You will need to check and probably change the error message $error_text[14] in the below example of one way to change your conditionals.
if (isset($_SESSION['admin'], $_POST['upload_images']))
{
$img_tmp_name = $_FILES['img']['tmp_name'];
$img_name = $_FILES['img']['name'];
$img_error = $_FILES['img']['error'];
$img_type = $_FILES['img']['type'];
$img_size = $_FILES['img']['size'];
$image_quantity = count($img_name);
$error_text = array (
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
4 => 'No file was uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk.',
8 => 'A PHP extension stopped the file upload.',
9 => 'file couldnt be moved!',
10 => 'file isnt uploaded',
11 => 'za duzy rozmiar pliku',
12 => 'obrazek musi byc w formacie JPEG',
13 => 'nie mozna stworzyc folderu',
14 => 'Query has not started, but folder has created with number: ',
15 => 'Unknown upload error'
);
$conn = lacz_bd();
if ($q = $conn->prepare('SELECT MAX(gallery_id) FROM galleries'))
{
$q->execute();
$q->bind_result($gallery_id);
$q->store_result();
while($q->fetch())
{
$improved_gallery_id = $gallery_id + 1;
}
$pre_path = ('./galerie/'.$improved_gallery_id);
//------------------------------- START UPLOAD ----------------------------------
for ($i=0; $i < $image_quantity; $i++)
{
if ($img_error[$i] == UPLOAD_ERR_OK)
{
if ($img_type[$i] = 'image/jpeg') //to do: preg match instead
{
if ($img_size[$i] <= 2621440) //2,5MiB
{
if (is_uploaded_file($img_tmp_name[$i]))
{
if ($i == 0) // only the first loop create directory
{
if (!file_exists($pre_path) && !is_dir($pre_path))
{
if (mkdir($pre_path, 0777))
{
// todo: handle the error
exit();
}
}
}
if (is_dir($pre_path))
{
$path = $pre_path.'/'.basename($img_name[$i]);
if (move_uploaded_file($img_tmp_name[$i], $path))
{
if ($q = $conn->prepare('INSERT INTO galleries (path, gallery_id) VALUES (?, ?)'))
{
$q->bind_param('si', $path, $improved_gallery_id);
$q->execute();
if ($q->affected_rows > 0)
{
image_compression($path, 800, 536);
echo '<a href="ustaw_miniature.php?m='.urlencode($img_name[$i]).'&gid='.urlencode($improved_gallery_id).'">';
echo '<img src="'. htmlspecialchars($path, ENT_QUOTES).'" width="80%" height="80%"></img></a><br />';
} // end affected_rows
} // end prepare
} // end move_uploaded_file
else { echo $error_text[9]; }
} // end is_dir
else { echo $error_text[14].' '.htmlspecialchars($improved_gallery_id, ENT_QUOTES);}
} // end is_uploaded_file
else { echo $error_text[10]; }
} // end image size
else { echo $error_text[11]; }
} // end image type
else { echo $error_text[12]; }
} // end error check
elseif ( $img_error[$i] == UPLOAD_ERR_INI_SIZE) { echo $error_text[1]; }
elseif ( $img_error[$i] == UPLOAD_ERR_FORM_SIZE) { echo $error_text[2]; }
elseif ( $img_error[$i] == UPLOAD_ERR_PARTIAL) { echo $error_text[3]; }
elseif ( $img_error[$i] == UPLOAD_ERR_NO_FILE) { echo $error_text[4]; }
elseif ( $img_error[$i] == UPLOAD_ERR_NO_TMP_DIR) { echo $error_text[6]; }
elseif ( $img_error[$i] == UPLOAD_ERR_CANT_WRITE) { echo $error_text[7]; }
elseif ( $img_error[$i] == UPLOAD_ERR_EXTENSION) { echo $error_text[8]; }
else { echo $error_text[15]; }
} // end for loop
$q->free_result();
$q->close();
} // end prepare
$conn->close();
} // end isset
You can rearrange your code using functions. Your code is really difficult to understanding.
First you can upload file to temporary folder, then call function to check it, and if everything is ok, you can call a function to prepare folder (create if not exist) and then copy file from temporary folder to a new one.
i've problem with my code here.
The case is, i have multiple input file form, i need to get name of current array (which contain database id) and upload the file from it.
Here's in my views
foreach($result2 as $result3)
{
print "
<tr>
<td><input type=file name=baddismantling[".$result3['iddeployment']."] size=20></td>
</tr>
";
}
so, there'll be various of upload form and name too, but it always unique.
and after user click submit button, that form will call function in my controller, and here's
the function that handled it
private function _ready_to_start($sessiondata)
{
if($post['doSubmitDismantlingAction'] == 'uploadbad')
{
while ($fruit_name = current($_FILES['baddismantling']['name']))
{
if($fruit_name != false)
{
//GET ID FROM DEPLOYMENT DB
$deploymentid = key($_FILES['baddismantling']['name']);
$file = "baddismantling[$deploymentid]";
if(!$this->upload->do_upload($file))
{
$check3[] = $this->upload->display_errors()." target: ".$file;
}
$check2 = $this->upload->data();
}
next($_FILES['baddismantling']['name']);
}
//SHOW RESULT WHILE UPLOADING
print implode($check3);
}
}
as you see,i've successful with getting the
$deploymentid = 1
as i wish...but, browser give me :
You did not select a file to upload. target: baddismantling[1]
anyone can give me suggestion about that problem?or there's something wrong with my code?
as note :
there's no problem with configuration $this->upload-> because i've
successfull with a single upload form only
thanks for your time with my question, and i've "luckily" got my own solving from question above with this code :
$check3 = array();
$count = 0;
$check = ($_FILES == true ? count($_FILES['baddismantling']['name']) : (0));
while ($fruit_name = ($check == true && $check > 0 ? current($_FILES['baddismantling']['name']) : (false)) || $count <= $check){
$count++;
if($fruit_name == true && key($_FILES['baddismantling']['name']) == true)
{
$iddeployment = key($_FILES['baddismantling']['name']);
/*THIS PART WAS HELPING ME*/if($_FILES['baddismantling']['name'][$iddeployment] == true)
{
$_FILES['userfile']['name'] = $_FILES['baddismantling']['name'][$iddeployment];
$_FILES['userfile']['type'] = $_FILES['baddismantling']['type'][$iddeployment];
$_FILES['userfile']['tmp_name'] = $_FILES['baddismantling']['tmp_name'][$iddeployment];
$_FILES['userfile']['error'] = $_FILES['baddismantling']['error'][$iddeployment];
$_FILES['userfile']['size'] = $_FILES['baddismantling']['size'][$iddeployment];
if (!$this->upload->do_upload())
{
$check3[] = $this->upload->display_errors();
}
else
{
$uploaddata = $this->upload->data();
$result['badfilename'] = $uploaddata['full_path'];
$result['id'] = $iddeployment;
$sql = $this->sql->updatedismantlingBAD($result);
}
}
}
next($_FILES['baddismantling']['name']);}
Hi this is a simple question, however I have now stared at it long enough to realise im simply not seeing the error. If anyone can see where this is going wrong I would be very thankful.
public function create()
{
$this->load->model('ticket_model');
if($_POST)
{
// validate form
if($this->_validate())
{
// save updates
foreach($_POST as $key => $value){if(!is_array($value)) $_POST[$key] = htmlspecialchars($value);}
if ($_POST['subject'] == '') $body_data['error'][] = "You did not enter a subject.";
if ($_POST['priority'] == '') $body_data['error'][] = "You did not select a priority.";
if ($_POST['status'] == '') $body_data['error'][] = "You did not select a status.";
if ($_POST['ipAddress'] == '') $body_data['error'][] = "You did not enter a ipAddress.";
if ($_POST['text_area'] == '') $body_data['error'][] = "You did not enter a message.";
else
{
if (filter_var($_POST['ipAddress'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) == FALSE) $body_data['error'][] = "IP Address is not valid IPV4 Address.";
if (filter_var($_POST['ipAddress'], FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE) == FALSE) $body_data['error'][] = "IP Address cannot be from RFC1918 private space.";
if (filter_var($_POST['ipAddress'], FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) == FALSE) $body_data['error'][] = "IP Address cannot be from reserved range.";
}
if ($_FILES['filename']['name'] != '')
{
if ($_FILES['filename']['size'] > '1024000')
{
$body_data['error'][] = "The file you uploaded is too large.";
unlink($_FILES['filename']['tmp_name']);
$body_data['ticket_list'] = $this->ticket_model->list_ticket();
$body_data['ticket_details'] = $this->ticket_model->get_ticket($ticket_id);
$body_data['ticket_summary'] = $this->ticket_model->list_ticket_summary($ticket_id);
$body_data['precan_list'] = $this->ticket_model->list_messages();
$body_data['users_list'] = $this->ticket_model->list_users();
$foot_data['accordian_active'] = 5;
$this->load->view('head',$head_data);
$this->load->view('sidebar/service',$head_data);
$this->load->view('ticket/edit',$body_data);
$this->load->view('foot',$foot_data);
return;
}
else
{
//the file is under the specified size. so copy it from temp to import folder and proccess
$thisFileHumanName = $_FILES['filename']['name'];
$thisFileSize = $_FILES['filename']['size'];
$thisServerFileName = strtoupper(uniqid('A'));
$thisFileType = $_FILES['filename']['type'];
$temp_file_location = $this->config->item('rootpath').'/assets/ticketuploads/'.$thisServerFileName;
if (!move_uploaded_file($_FILES['filename']['tmp_name'], $temp_file_location))
{
$body_data['error'][] = "File could not be moved due to a permissions error.";
unlink($_FILES['filename']['tmp_name']);
$body_data['ticket_list'] = $this->ticket_model->list_ticket();
$body_data['ticket_details'] = $this->ticket_model->get_ticket($ticket_id);
$body_data['ticket_summary'] = $this->ticket_model->list_ticket_summary($ticket_id);
$body_data['precan_list'] = $this->ticket_model->list_messages();
$body_data['users_list'] = $this->ticket_model->list_users();
$foot_data['accordian_active'] = 5;
$this->load->view('head',$head_data);
$this->load->view('sidebar/service',$head_data);
$this->load->view('ticket/edit',$body_data);
$this->load->view('foot',$foot_data);
return;
}
}
}
//clean error array
$body_data['error'] = array_filter($body_data['error']);
if ($body_data['error'])
{
$body_data['ticket_list'] = $this->ticket_model->list_ticket();
$body_data['ticket_details'] = $this->ticket_model->get_ticket($ticket_id);
$body_data['ticket_summary'] = $this->ticket_model->list_ticket_summary($ticket_id);
$body_data['precan_list'] = $this->ticket_model->list_messages();
$body_data['users_list'] = $this->ticket_model->list_users();
unlink($_FILES['filename']['tmp_name']);
$foot_data['accordian_active'] = 5;
$this->load->view('head',$head_data);
$this->load->view('sidebar/service',$head_data);
$this->load->view('ticket/edit',$body_data);
$this->load->view('foot',$foot_data);
return;
}
else
{
$_POST['userId'] = $this->session->get_user_id();
$thisMessageId = $this->ticket_model->save_message($_POST);
if ($_FILES['filename']['name'] != '')
{
//set variables for save
$_POST['file_path'] = $temp_file_location;
$_POST['file_name'] = $thisFileHumanName;
$_POST['file_size'] = $thisFileSize;
$_POST['file_type'] = $thisFileType;
$_POST['messageId'] = $thisMessageId;
$this->ticket_model->save_upload($_POST);
}
$this->ticket_model->save_ticket($_POST);
redirect(base_url().'ticket/');
return;
}
}
}
$body_data['ticket_list'] = $this->ticket_model->list_ticket();
$body_data['message_list'] = $this->ticket_model->list_message($ticket_id);
$body_data['customer_list'] = $this->ticket_model->list_customers();
$body_data['users_list'] = $this->ticket_model->list_users();
$foot_data['accordian_active'] = 5;
$foot_data['contact_search'] = true;
$this->load->view('head',$head_data);
$this->load->view('sidebar/service',$head_data);
$this->load->view('ticket/create',$body_data);
$this->load->view('foot',$foot_data);
return;
}
This is my code, and everything is going well, except for the section where i save the upload, as nothing seems to be firing the model, even thought there is a file being posted from the from submit and there for the filename being posted is != ''......
e.g
if ($_FILES['filename']['name'] != '')
{
//set variables for save
$_POST['file_path'] = $temp_file_location;
$_POST['file_name'] = $thisFileHumanName;
$_POST['file_size'] = $thisFileSize;
$_POST['file_type'] = $thisFileType;
$_POST['messageId'] = $thisMessageId;
$this->ticket_model->save_upload($_POST);
}
my apologies if this is silly mistake.
Why are you doing it this way? Codeigniter has a built in class for uploading files. You also should be using the input class instead of $_POST.
It will make it a lot easier!
As for your code. You're actually setting the $_POST variable and trying to use that in save_ticket. You can't do that.
The predefined $_POST variable is used to collect values from a form
sent with method="post"
You're trying to use it the other way around.
So to make it work, change the $_POST into $something and it should work, but it's still not the way to go.
//set variables for save
$something['file_path'] = $temp_file_location;
$something['file_name'] = $thisFileHumanName;
$something['file_size'] = $thisFileSize;
$something['file_type'] = $thisFileType;
$something['messageId'] = $thisMessageId;
$this->ticket_model->save_upload($something);
didn't have this set.......enctype="multipart/form-data"
red face on this end.
How can I check if a file extension and mime type are in an array this is the code I currently have.
$upload_project_thum = $_FILES['upload_project_thum']['name'];
$upload_project_thum_ext = substr($upload_project_thum, strrpos($upload_project_thum, '.') + 1);
$upload_permitted_types= array('image/jpeg:jpg','image/pjpeg:jpg','image/gif:gif','image/png:png');
Then down where i'm checking if the file is a valid type I have this foreach loop
foreach ($upload_permitted_types as $image_type) {
$type = explode(":", $image_type);
if (($type[0] != $_FILES['upload_project_thum']['type']) && ($upload_project_thum_ext != $type[1]) ) {
$errmsg_arr[] = 'Please select a jpg, jpeg, gif, or png image to use as the project thumbnail'. $type[1] . " Type: ". $type[0];
$errflag = true;
}
The problem is that if the file type isn't ALL of the types in the array (which is impossible) I get an error. It works to the point where if the upload file is in the array that error message won't trigger.
if (!in_array($_FILES['upload_project_thum']['type'], $upload_permitted_types)){
exit("Unsupported file type");
}
if( !in_array( $_FILES['upload_project_thum']['type'] . ':' . $upload_project_thum_ext, $upload_permitted_types) ) {
Trigger-error-here;
}
This should look for a proper string glued from both the type and extension.
Another way is to modify your loop like that:
$is_allowed = false;
foreach ($upload_permitted_types as $image_type) {
$type = explode(":", $image_type);
if (($type[0] == $_FILES['upload_project_thum']['type']) && ($type[1] == $upload_project_thum_ext ) ) {
$is_allowed = true;
break;
}
}
if( !$is_allowed ) {
$errmsg_arr[] = 'Please select a jpg, jpeg, gif, or png image to use as the project thumbnail'. $type[1] . " Type: ". $type[0];
$errflag = true;
}
The way I am doing this now is:
$upload_permitted_types['mime']= array('image/jpeg','image/gif','image/png');
$upload_permitted_types['ext']= array('jpeg','jpg','gif','png');
if(!in_array($_FILES['upload_project_thum']['type'],$upload_permitted_types['mime']) || !in_array($upload_project_thum_ext,$upload_permitted_types['ext'])
{
$errmsg_arr[] = 'Please select a jpg, jpeg, gif, or png image to use as the project thumbnail';
$errflag = true;
}
The advantage to this is that it will allow a .gif file with a mime of jpeg. So it doesn't force the mine and the extension to match but does make sure they are both image types.
I like to get the files array and then use a foreach loop literating over possible conditions
$is_error = TRUE;
$allowFileTypes = array(
"image/png","image/jpg","image/jpeg"
);
$UserBaseFolder = 'userfiles/'.$_SESSION['user_id'];
if(!file_exists($UserBaseFolder)) {
mkdir("userfiles/".$_SESSION['user_id']."/");
}
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
foreach($_FILES as $dat => $f) {
if($f['size'] == "0") {
$msg .= '<p><span class="alert alert-danger">You must upload a file.</span></p>';
$is_error = FALSE;
}
if($f['size'] > "2000000") {
$msg .= '<p><span class="alert alert-danger">Your file size is too big.</span></p>';
$is_error = FALSE;
}
if(!in_array($f['type'],$allowFileTypes)){
$msg .= '<p><span class="alert alert-danger">Your file has invalid format. Please try again...</span></p>';
$is_error = FALSE;
} else {
$filepath = $UserBaseFolder.'/'.time().'-'.$f['name'];
move_uploaded_file($f["tmp_name"], $filepath);
}
return $msg;