I'm having trouble figuring out why it is that when an image size is too big, I get the error 'Invalid File Type' 'Uploaded file is not an image' instead of getting 'File is too big' (The image validation/upload script I didn't completely write myself- I found the code and made it work with for my needs). Everything else seems to work fine except for this. Also I get the following warning
Warning: getimagesize(): Filename cannot be empty in C:\xampp\htdocs\minnow\includes\create-post.php on line 75
Here is my code
<?php
require_once('../dbconnect.php');
include_once( INCLUDES_PATH .'functions.php');
$body = $_POST["body"];
$image = 'image';
$user_id = $_SESSION['user_id'];
if( empty($_FILES[$image]['name']) ){
$has_image = 0;
}else{
$has_image = 1;
}
$postEmpty = 0;
$imageError = 0;
if( empty($_FILES[$image]['name']) && empty($body) ){
$postEmpty = 1;
die();
}
// validate post
if( $postEmpty == 0 && !empty($body) ){
$cleanBody = clean_input($body);
}
// validate image (if any)
if( $has_image == 1 ){
//check if directory exist if not create it
if (!file_exists(HOME_PATH ."users/user_".$user_id)) {
mkdir(HOME_PATH ."users/user_".$user_id, 0777, true);
}
if (!file_exists(HOME_PATH ."users/user_".$user_id."/posts")) {
mkdir(HOME_PATH ."users/user_".$user_id."/posts", 0777, true);
}
//Set file upload path
$path = "../users/user_".$user_id."/posts/"; //with trailing slash
//Set max file size in bytes
$max_size = 2000000;
//Set default file extension whitelist
$whitelist_ext = array('jpeg','jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/jpg', 'image/png','image/gif');
// Create an array to hold any output
$errors = array();
// Get filename
$file_info = pathinfo($_FILES[$image]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$errors[] = "Invalid file Extension";
}
//Check that the file is of the right type
if (!in_array($_FILES[$image]["type"], $whitelist_type)) {
$errors[] = "Invalid file Type";
}
//Check that the file is not too big
if ($_FILES[$image]["size"] > $max_size) {
$errors[] = "File is too big";
}
//If $check image is set as true
if ( !getimagesize($_FILES[$image]['tmp_name']) ) {
$errors[] = "Uploaded file is not a valid image";
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
}
// if no errors:
// upload image (if any) and retrieve filename
if( $imageError == 1 ){
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}else{
//Create full filename including path
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}
if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {
$uploadSuccesfull = 1;
}else {
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}
}
}
// if no errors:
// save post (with filename if any); if it fails, delete image (if any)
if( $has_image == 1 ){
$query = "INSERT INTO posts
(user_id, body, image, has_image, date)
VALUES
('$user_id', '$body', '$newname', '$has_image', now())";
}else{
$query = "INSERT INTO posts
(user_id, body, has_image, date)
VALUES
('$user_id', '$body', '$has_image', now())";
}
$result = $db->query($query);
// send response
//check to make sure the user was added
if( $db->affected_rows == 1 ){
$user_id = $_SESSION['user_id'];
$post_id = $db->insert_id;
$query = "SELECT post_id, body, image, has_image
FROM posts
WHERE post_id = $post_id
LIMIT 1";
$result = $db->query($query);
if($result->num_rows == 1){
$row = $result->fetch_assoc();
}
$queryuser = "SELECT *
FROM users
WHERE user_id = $user_id
LIMIT 1";
$resultuser = $db->query($queryuser);
if($resultuser->num_rows == 1){
$rowuser = $resultuser->fetch_assoc();
}
if(!empty($row['avatar'])){ $userpic = $row['avatar']; }else{ $userpic = HOME_URL . 'img/avatar.jpg'; }
if($row['has_image'] == 1){
$data = "<article class='post'><div class='post-head cf'><a class='userpic' href=''><img src='$userpic' alt='".$rowuser['username']."'></a><a href='' class='username'>".$rowuser['username']."</a></div><img src='users/user_".$rowuser['user_id']."/posts/".$row['image']."' alt=''><div class='post-body'><div class='post-options'><a class='likes' href=''>156 likes</a></div><p><a class='username' href=''>".$rowuser['username']."</a>".$row['body']."</p><hr /><div class='cf'><a class='like hide-text' href='javascript:;'>Like This Post</a><form action='' class='comment'><input type='text' placeholder='Add a comment'></form></div></div></article>";
echo json_encode($data, JSON_UNESCAPED_SLASHES);
}else{
$data = "<article class='post no-img'><div class='post-head cf'><a class='userpic' href=''><img src='$userpic' alt='".$rowuser['username']."'></a><a href='' class='username'>".$rowuser['username']."</a></div><div class='post-body'><p><a class='username' href=''>".$rowuser['username']."</a>".$row['body']."</p><div class='post-options'><a class='likes' href=''>1 like</a></div><hr /><div class='cf'><a class='like hide-text' href='javascript:;'>Like This Post</a><form action='' class='comment'><input type='text' placeholder='Add a comment'></form></div></div></article>";
echo json_encode($data, JSON_UNESCAPED_SLASHES);
}
}else{
$errors[] = "Server Error!";
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
}
die();
It could be that the file was just not uploaded to the server.
Check $_FILES[$image]['error'] to see what may have gone wrong.
Refer to the error messages here.
Edit: After these lines:
$body = $_POST["body"];
$image = 'image';
$user_id = $_SESSION['user_id'];
Do this:
// check for error greater than zero
if($_FILES[$image]['error'] > 0) {
// something went wrong with the upload, handle the error
echo $_FILES[$image]['error']; exit; // as an example to find out what the error was
}
Then refer to http://php.net/manual/en/features.file-upload.errors.php to find out the reason.
Related
I'm receiving an error with the email form not going through and receiving an error message. I've checked for parse and syntax errors and didn't come across any. I think that I need to upgrade the email form from php to smtp email settings, but not sure where exactly to start. Has anyone navigated this before and any tips on troubleshooting this issue? Could it be something else that is causing the error message?
<?php
/*
=== Copyright (c) x2cms.com 2011 === BUILDER_VERSION:12
*/
if (!defined("BASE_PATH")) define('BASE_PATH', isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : substr(str_replace('\\\\','\\',$_SERVER['PATH_TRANSLATED']),0, -1*strlen($_SERVER['SCRIPT_NAME'])));
/* initialize a session. */
session_start();
require("mailer.php");
require("template-loader.php");
require("settings-loader.php");
$settings['captcha_required'] = array_key_exists('captcha',$_POST);
// disable magic quotes
// --------------------------------------------------------------------------------------------
// languages
// --------------------------------------------------------------------------------------------
// load language
read_language_xml(BASE_PATH.'/emaileverything.php.xml');
// add default language for form
add_language_def('email_message','The following information was posted from your %s form');
add_language_def('email_subject','%s form results');
add_language_def('error_required','is a required field');
add_language_def('mail_sender','Mail sender IP address:');
add_language_def('go_back','« back');
add_language_def('error_captcha','The validation code you entered was invalid');
add_language_def('error_no_email_to','You must enter an email address');
add_language_def('error_no_email_from','You must enter an email address to send to.');
add_language_def('error_no_message','You must enter a message');
add_language_def('success_message','Thank you, the form has been processed successfully.');
add_language_def('error_message','The following error(s) occured: ');
// uploader
add_language_def('error_file_size','%s file is too big, the maximum file size is (%smb)');
add_language_def('file_link','File Link');
add_language_def('error_upload','Unable to save uploaded file, please check site uploaded directory and permissions.');
add_language_def('error_file_type','allowed files are %s. Yours was %s.');
// settings
// --------------------------------------------------------------------------------------------
$settings['form_id'] = ''; // form identifier
$settings['form_name'] = $_SERVER['HTTP_HOST']; // the name of the form used, defaults to the script address
$settings['confirmation_message'] = ''; // the confirmation message used with the template
$settings['confirmation_url'] = ''; // if specified we redirect to a confirmation page
$settings['email_subject'] = ''; // the email subject
$settings['email_to'] = ''; // who do we send the email to
$settings['email_from'] = ''; // the customer's email submitting the form
$settings['copy_mail_to_sender'] = 'false'; // whether we copy the form email to the mail sender $email_from
$settings['required_fields'] = ''; // required field names seperated by |
$settings['email_template'] = ''; // the email template to use
$settings['upload_max_size'] = '20'; // size in mb per file
$settings['upload_check_extension'] = 'false';
$settings['upload_allowed_extensions'] = 'jpg|jpeg|gif|png|doc|docx|txt|rtf|pdf|xls|xlsx|ppt|pptx|zip'; // allowed file extensions
// general functions
// --------------------------------------------------------------------------------------------
if(!function_exists('str_ireplace'))
{
function str_ireplace($needle, $str, $haystack)
{
$needle = preg_quote($needle, '/');
return preg_replace("/$needle/i", $str, $haystack);
}
}
// ensure filename is in friendly format
function safe_filename($filename)
{
$filename = trim($filename);
$filename = str_replace("/", "", $filename);
$filename = str_replace("\\", "", $filename);
$filename = str_replace(">", "", $filename);
$filename = str_replace("<", "", $filename);
return $filename;
}
// check for required fields
function isRequired($field_name)
{
global $required_fieldsarr;
if(is_array($required_fieldsarr))
{
foreach ($required_fieldsarr as $required_field_name)
{
if(strtoupper($required_field_name) == strtoupper($field_name))
{
return true;
}
}
}
return false;
}
function get_file_extension($filename)
{
return end(explode(".", $filename));
}
// uploaded files
function uploadedFiles()
{
$returnStr = '';
$returnStr .= uploadFile("userfile");
for($i = 0; $i<10; $i++)
{
$returnStr .= uploadFile("userfile".$i);
}
return $returnStr;
}
function uploadFile($fieldName)
{
global $error_message, $_FILES, $language, $settings;
if(!isset($_FILES[$fieldName]))
{
return;
}
$allowed_file_ext_arr = explode("|", $settings['upload_allowed_extensions']);
$returnStr = '';
// try array of files first
if(is_array($_FILES[$fieldName]))
{
foreach ($_FILES[$fieldName]["error"] as $key => $error)
{
if ($error == UPLOAD_ERR_OK)
{
$file_type = $_FILES[$fieldName]['type'][$key];
$file_size = $_FILES[$fieldName]['size'][$key];
$tmp_name = $_FILES[$fieldName]["tmp_name"][$key];
$name = $_FILES[$fieldName]["name"][$key];
$error = "";
// check file size
if ($file_size > ((int)$settings['upload_max_size'] * 1024 * 1024))
{
$error .= sprintf($language['error_file_size'], $name, $settings['upload_max_size']).'<br/>';
}
// check file type
if($settings['upload_check_extension'] == 'true')
{
if (!in_array(get_file_extension($name),$allowed_file_ext_arr))
{
$error .= sprintf($language['error_file_type'], $settings['upload_allowed_extensions'], $file_type).'<br/>';
}
}
if ($error == "")
{
if(is_uploaded_file($tmp_name))
{
// sanatize file name
$name = preg_replace(array("/\s+/", "/[^-\.\w]+/"), array("_", ""), trim($name));
if(move_uploaded_file($tmp_name, "uploaded/$name"))
{
$returnStr .= "<tr><td>".$language['file_name']."</td><td><a href='http://".$_SERVER['HTTP_HOST']."/uploaded/$name'>$name</a></td></tr>";
}
else
{
$error_message = $language['error_upload'].'<br/>';
}
}
}
else
{
$error_message .= $error;
}
}
}
}
else // try single file
{
if($_FILES[$fieldName]["error"] == UPLOAD_ERR_OK)
{
$file_type = $_FILES[$fieldName]['type'][$key];
$file_size = $_FILES[$fieldName]['size'][$key];
$tmp_name = $_FILES[$fieldName]["tmp_name"][$key];
$name = $_FILES[$fieldName]["name"][$key];
$error = "";
// check file size
if ($file_size > ((int)$settings['upload_max_size'] * 1024 * 1024))
{
$error .= sprintf($language['error_file_size'], $key, ($maxSize/1000)).'<br/>';
}
// check file type
if($settings['upload_check_extension'] == 'true')
{
if (!in_array(get_file_extension($name),$allowed_file_ext_arr))
{
$error .= $key." Allowed files are ".$settings['upload_allowed_extensions'].". Yours was ".$file_type."<br/>";
}
}
if ($error == "")
{
if(is_uploaded_file($tmp_name))
{
// sanatize file name
$name = preg_replace(array("/\s+/", "/[^-\.\w]+/"), array("_", ""), trim($name));
if(move_uploaded_file($tmp_name, "uploaded/$name"))
{
$returnStr .= "<tr><td>".$language['file_name']."</td><td><a href='http://".$_SERVER['HTTP_HOST']."/uploaded/$name'>$name</a></td></tr>";
}
else
{
$error_message = $language['error_upload'].'<br/>';
}
}
}
else
{
$error_message .= $error;
}
}
}
return $returnStr;
}
// read POST and GET data
// --------------------------------------------------------------------------------------------
// did we specify a form name in either GET OR POST
// get the form id
if(trim($_POST['id']) != '')
{
$settings['form_id'] = trim($_POST['id']);
}
if(trim($_GET['id']) != '')
{
$settings['form_id'] = trim($_GET['id']);
}
// 5.1 get parameters from XML
load_config('emaileverything-settings.xml');
load_config($settings['form_id'].'.xml');
// parse_settings_xml(safe_filename($settings['form_id']).'-settings.xml');
// check_referrer();
// get parameters from POST, POST overwrites settings from XML
if(trim($_POST['FormName']) != '')
{
$settings['form_name'] = trim($_POST['FormName']);
}
if(trim($_POST['EmailSubject']) != '')
$settings['email_subject'] = trim($_POST['EmailSubject']);
if(trim($_POST['EmailTo']) != '')
$settings['email_to'] = trim($_POST['EmailTo']);
if(trim($_POST['email']) != '')
$settings['email_from'] = trim($_POST['email']);
if(trim($_POST['OKMessage']) != '')
$settings['confirmation_message'] = trim($_POST['OKMessage']);
if(trim($_POST['OKURL']) != '')
$settings['confirmation_url'] = trim($_POST['OKURL']);
if(trim($_POST['CopyToSender']) != '')
$settings['copy_mail_to_sender'] = trim($_POST['CopyToSender']);
if(trim($_POST['UseTemplate']) != '')
$settings['email_template'] = trim($_POST['UseTemplate']);
if(trim($_POST['TemplateID']) != '')
$settings['template_id'] = trim($_POST['TemplateID']);
if(trim($_POST['RequiredFields']) != '')
$settings['required_fields'] = trim($_POST['RequiredFields']);
// alternative field names from trellix
if(trim($_POST['tlx_Subject']) != '')
$settings['email_subject'] = trim($_POST['tlx_Subject']);
if($_POST['tlx_EmailTo'] != '')
$settings['email_to'] = trim($_POST['tlx_EmailTo']);
if($_POST['tlx_OKMessage'] != '')
$settings['confirmation_message'] = trim($_POST['tlx_OKMessage']);
// build the email
// --------------------------------------------------------------------------------------------
// now we do some work with our required fields, split on | to get each required field name
$required_fieldsarr = explode("|", $settings['required_fields']);
$error_message = '';
// check required fields
foreach ($_POST as $key => $val)
{
// see if field is required
if(isRequired($key) && ($val == ''))
{
$error_message .= $key." ".$language['error_required'].".<br/>";
}
}
// build email message
if($settings['email_template'] != '') // are we using a email template
{
// safe file name
$settings['email_template'] = safe_filename($settings['email_template']);
// check to see if template exists
if(file_exists($settings['email_template']))
{
$email_message = file_get_contents($settings['email_template']);
// replace key with value
foreach ($_POST as $key => $val)
{
$email_message = str_ireplace('{'.$key.'}', $val, $email_message);
}
// remove remaining
$email_message = preg_replace('/\{(\w*)\}/', '', $email_message);
}
}
else
{
$email_message = sprintf($language['email_message'],$settings['form_name']);
$email_message .= '<br/><br/><table cellpadding="5" cellspacing="5" border="1"><tr><th>Field Name</th><th>Value</th></tr>';`
foreach ($_POST as $key => $val)
Problem
I am trying to send push notification through PHP, to both Android and iOS, but I have lots of devices to send the notification, and you can see the code that it sends the notification to all of them in a loop. It's really not optimized as my dashboard gets stuck for more than a minute due to the running loop, also somehow it is not even sending a notification to all active accounts.
Can anyone here help me out?
Code
public function insert()
{
// Set the validation rules
$this->form_validation->set_rules('title', 'Title', 'required|trim');
// If the validation worked
if ($this->form_validation->run())
{
$get_post = $this->input->get_post(null,true);
$get_post['tags'] = is_array($this->input->get_post('tags')) ? $this->input->get_post('tags') : [];
if(count($get_post['tags']) == 0)
{
$_SESSION['msg_error'][] = "Tags is a required field";
redirect('admin/newsfeed/insert');
exit;
}
# File uploading configuration
$upload_path = './uploads/newsfeeds/';
$config['upload_path'] = $upload_path;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['encrypt_name'] = true;
$this->load->library('upload', $config);
$image = '';
# Try to upload file now
if ($this->upload->do_upload('image'))
{
# Get uploading detail here
$upload_detail = $this->upload->data();
$image = $upload_detail['file_name'];
} else {
$uploaded_file_array = (isset($_FILES['image']) and $_FILES['image']['size'] > 0 and $_FILES['image']['error'] == 0) ? $_FILES['image'] : '';
# Show uploading error only when the file uploading attempt exist.
if( is_array($uploaded_file_array) )
{
$uploading_error = $this->upload->display_errors();
$_SESSION['msg_error'][] = $uploading_error;
}
}
# File uploading configuration
$upload_path = './uploads/newsfeeds/';
$config['upload_path'] = $upload_path;
$config['allowed_types'] = '*';
$config['encrypt_name'] = true;
$config['max_size'] = 51200; //KB
$this->upload->initialize($config);
$audio = '';
# Try to upload file now
if ($this->upload->do_upload('audio'))
{
# Get uploading detail here
$upload_detail = $this->upload->data();
$audio = $upload_detail['file_name'];
}
else
{
$uploaded_file_array = (isset($_FILES['audio']) and $_FILES['audio']['size'] > 0 and $_FILES['audio']['error'] == 0) ? $_FILES['audio'] : '';
# Show uploading error only when the file uploading attempt exist.
if( is_array($uploaded_file_array) )
{
$uploading_error = $this->upload->display_errors();
$_SESSION['msg_error'][] = $uploading_error;
}
}
$get_post['image'] = $image;
$get_post['audio'] = $audio;
if($id = $this->newsfeed_model->insert($get_post))
{
if($get_post['status'])
{
// send push notification to all users
$notification = $this->newsfeed_model->get_newsfeed_by_id($id);
$notification->notification_type = 'article';
$notification->title = $get_post['n_title'];
$notification->body = $get_post['n_description'];
$query = $this->db->get_where('users', ['device_id !=' => '']);
foreach ($query->result() as $row) {
if ($row->device == 'IOS') {
$this->notification_model->sendPushNotificationIOS($row->device_id, $notification);
}
if ($row->device == 'ANDROID') {
$this->notification_model->sendPushNotificationAndroid($row->device_id, $notification);
}
}
}
$_SESSION['msg_success'][] = 'Record added successfully...';
if($image){
redirect('admin/newsfeed/crop_image?id='.$id);
} else {
redirect('admin/newsfeed/');
}
}
}
$this->data['selected_page'] = 'newsfeed';
$this->load->view('admin/newsfeed_add', $this->data);
}
Description
The method is adding a newsfeed, its checks for the validations, then it inserts the feed to the db, once thats done, it sends out the notification to all devices.
Problematic Chunk
if($id = $this->newsfeed_model->insert($get_post))
{
if($get_post['status'])
{
// send push notification to all users
$notification = $this->newsfeed_model->get_newsfeed_by_id($id);
$notification->notification_type = 'article';
$notification->title = $get_post['n_title'];
$notification->body = $get_post['n_description'];
$query = $this->db->get_where('users', ['device_id !=' => '']);
foreach ($query->result() as $row) {
if ($row->device == 'IOS') {
$this->notification_model->sendPushNotificationIOS($row->device_id, $notification);
}
if ($row->device == 'ANDROID') {
$this->notification_model->sendPushNotificationAndroid($row->device_id, $notification);
}
}
}
$_SESSION['msg_success'][] = 'Record added successfully...';
if($image) {
redirect('admin/newsfeed/crop_image?id='.$id);
} else{
redirect('admin/newsfeed/');
}
}
Thank you in advance.
I read similar query on google, there I read about checking whether file is writable and then setting permissions using chmod() function, but I tried that too, it didnt work. I want to store the image path in database, and move the image to the uploads folder. The path of the image would be as :
C:/xampp/htdocs/konnect1/uploads/Hydrangeas1.jpg
On using chmod(), I get Warning as "Message: chmod(): No such file or directory".
please help as what should I change now.
Controller page->admin_c.php
Posting the function, where image upload code is written.
public function create_event1()
{
if($this->input->post('counter') || !$this->input->post('counter'))
{
$count = $this->input->post('counter');
$c = $count;
//echo $c;
if($this->input->is_ajax_request())
{
$vardata = $this->input->post('vardata');
echo $vardata;
}
$g = $_POST['results'];
$configUpload['upload_path'] = '/konnect1/uploads/'; #the folder placed in the root of project
$configUpload['allowed_types'] = 'gif|jpg|png|bmp|jpeg'; #allowed types description
$configUpload['max_size'] = '0'; #max size
$configUpload['max_width'] = '0'; #max width
$configUpload['max_height'] = '0'; #max height
$configUpload['encrypt_name'] = false; #encrypt name of the uploaded file
$this->load->library('upload', $configUpload);
$this->upload->initialize($configUpload); #init the upload class
if( chmod($configUpload['upload_path'], 0755) )
{
// more code
chmod($configUpload['upload_path'], 0777);
}
else
echo "Couldn't do it.";
if ( ! is_writable($this->upload->do_upload('picture')))
{
$uploadedDetails = $this->upload->display_errors('upload_not_writable');
echo $uploadedDetails;
}
else if(!$this->upload->do_upload('picture'))
{
$uploadedDetails = $this->upload->display_errors();
}
else
{
$uploadedDetails = $this->upload->data();
//print_r($uploadedDetails);die;
$etype = $this->input->post('etype');
$ecategory = $this->input->post('ecategory');
$ename = $this->input->post('ename');
$edat_time = $this->input->post('edat_time');
$evenue = $this->input->post('evenue');
$sch_name0 = $this->input->post("sch_name0");
$speaker_name0 = $this->input->post("speaker_name0");
$sch_stime0 = $this->input->post("sch_stime0");
$sch_etime0 = $this->input->post("sch_etime0");
$sch_venue0 = $this->input->post("sch_venue0");
$sch_name = $this->input->post("sch_name");
$speaker_name = $this->input->post("speaker_name");
$sch_stime = $this->input->post("sch_stime");
$sch_etime = $this->input->post("sch_etime");
$sch_venue = $this->input->post("sch_venue");
$agenda_desc = $this->input->post("agenda_desc");
if ((!empty($etype)) || (!empty($uploadedDetails)) || (!empty($ecategory)) || (!empty($ename)) || (!empty($edat_time)) || (!empty($evenue)) || (!empty($sch_name0)) || (!empty($speaker_name0)) || (!empty($sch_stime0)) || (!empty($sch_etime0)) || (!empty($sch_venue0)) || (!empty($sch_name)) || (!empty($speaker_name)) || (!empty($sch_stime)) || (!empty($sch_etime)) || (!empty($sch_venue)) || (!empty($agenda_desc)))
{
$res1 = $this->admin_m->insert($uploadedDetails);
if($res1 == true)
{
$res2 = $this->admin_m->insert1($c);
$lastid = $this->db->insert_id();
$data['h'] = $this->admin_m->select($lastid);
//return the data in view
$this->load->view('admin/event', $data);
}
else
echo "error";
}
}
}
}
Model Page->admin_m.php
<?php
class Admin_m extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
public function insert($image_data = array())
{
//$data1 = explode('/',$imge_data);
//$data2 = in_array("konnect1", $data1);
$data = array(
'ename' => $this->input->post('ename'),
'eimg' => $this->input->post('eimg'),
'edat_time' => $this->input->post('edat_time'),
'evenue' => $this->input->post('evenue'),
'sch_name' => $this->input->post('sch_name0'),
'speaker_name' => $this->input->post('speaker_name0'),
'sch_stime' => $this->input->post('sch_stime0'),
'sch_etime' => $this->input->post('sch_etime0'),
'sch_venue' => $this->input->post('sch_venue0'),
'etype' => $this->input->post('etype'),
'ecategory' => $this->input->post('ecategory'),
'agenda_desc' => $this->input->post('agenda_desc'),
'eimg' => $image_data['full_path']
);
$result = $this->db->insert('event',$data);
if($result == true)
return true;
else
echo "Error in first row";
}
public function insert1($c)
{
for($i=0; $i<=$c; $i++)
{
$sql = array(
'sch_name' => $this->input->post('sch_name')[$i],
'speaker_name' => $this->input->post('speaker_name')[$i],
'sch_stime' => $this->input->post('sch_stime')[$i],
'sch_etime' => $this->input->post('sch_etime')[$i],
'sch_venue' => $this->input->post('sch_venue')[$i]
);
//$sql = "INSERT INTO event(sch_name,speaker_name,sch_stime,sch_etime,sch_venue) VALUES(($this->input->post('sch_name')[$i]),($this->input->post('speaker_name')[$i]),($this->input->post('sch_stime')[$i]),($this->input->post('sch_etime')[$i]),($this->input->post('sch_venue')[$i]))";
$res = $this->db->insert('event',$sql);
}
if ($res == true)
return true;
else
echo "Error from first row";
}
public function select($lastid)
{
//data is retrive from this query
$query = $this->db->get('event');
return $query;
}
}
?>
for reference, attached model code also.
According to the error message, it seems PHP is unable to find the directory.
Please use PHP function is_dir() to first validate if PHP can recognize the path as a folder.
Once it returns true, you can proceed to use it.
Also in your upload path, you have started with / which would mean that your project is placed in root of OS and I don't think that location would be correct.
From the terminal cd to your project directory and run command pwd and get the current working directory and then use the proper upload path after taking into consideration the location of the project.
I have coded this far but the only issue i have is that i can't save multiple rows for the same user id when the user uploads several pictures. the code works perfectly fine, I mean the multiple files gets inserted into the file system folder/root directory but the reference in the database doesn't quit work. It only inserts the first file uploaded image not the the second file upload.
Here is my code:
<?php
if(isset($_POST['go'])) {
if(isset($_FILES['file_array'])){
$errors= array();
foreach($_FILES['file_array']['tmp_name'] as $key => $tmp_name ) {
$user = $_SESSION['user_id'];
$file_name = $key.$_FILES['file_array']['name'][$key];
$file_size =$_FILES['file_array']['size'][$key];
$file_tmp =$_FILES['file_array']['tmp_name'][$key];
$file_type=$_FILES['file_array']['type'][$key];
}
$extensions = array("jpeg","jpg","png");
$file_ext=explode('.',$_FILES['file_array']['name'][$key]);
$file_ext=end($file_ext);
$file_ext=strtolower(end(explode('.',$_FILES['file_array']['name'][$key])));
if(in_array($file_ext,$extensions ) === false) {
$errors[]="extension not allowed";
}
if($_FILES['file_array']['size'][$key] > 2097152) {
$errors[]='File size must be less tham 2 MB';
}
$query = array();
$myarray = '';
if(is_array($query)) {
foreach ($query as $row) {
$query[] = '('.$row['ID'].',"'.$row['FILE_NAME'].'", "'.$row['FILE_TYPE'].'", "'.$row['FILE_SIZE'].'")';
}
}
$dir = "users_data/profile/users_posted_data/";
if(empty($errors)==true) {
if(is_dir($dir)==false){
mkdir("$dir/", 0700);
}
if(is_dir("$dir/".$file_name)==false) {
move_uploaded_file($file_tmp,"$dir/".$file_name);
} else {
$new_dir="$dir/".$file_name.time();
rename($file_tmp, "$dir/".$file_name);
}
$query_run = mysqli_query($mysqli, 'INSERT INTO table (ID, FILE_NAME,FILE_SIZE, FILE_TYPE) VALUES '.implode(',', $query));
} else {
print_r($errors);
}
if(empty($error)) {
echo "Success";
}
}
}
?>
You are trying to iterate over an empty array. Not sure what you were actually trying to do but this will do nothing.
$query = array(); // init array
$myarray = '';
if(is_array($query)) { // test that its an array which it obviously is see 2 lines previous
foreach ($query as $row) { // iterate over empty array
// add to the array we are **not** iterating over
$query[] = '('.$row['ID'].',"'.$row['FILE_NAME'].'", "'.$row['FILE_TYPE'].'", "'.$row['FILE_SIZE'].'")';
}
}
I currently have this script where users (using a form where they can upload up to seven images) can upload multiple images to a folder and the image name to my database, without any success. Please help.
if (isset($_POST['submit'])) { $ref_49 = $_POST['ref_49'];
$name = $_POST['name'];
$contact = $_POST['contact'];
$email = $_POST['email'];
$rent_sell = $_POST['rent_sell'];
$heading = $_POST['heading'];
$price = $_POST['price'];
$limitedtextarea = $_POST['limitedtextarea'];
$type = $_POST['type'];
$where = $_POST['where'];
$address = $_POST['address'];
$bedroom = $_POST['bedroom'];
$bathroom = $_POST['bathroom'];
$garages = $_POST['garages'];
$carports = $_POST['carports'];
$granny_flat = $_POST['granny_flat'];
$ref_99 = $_POST['ref_99'];
$fulldesc = $_POST['full_desc'];
if ($ref_99=="") {
$full_ad = "yes";
} else {
$full_ad = "no";
}
$todays_date = date("Y-m-d");
mkdir("gallery/" . $_POST["name"], 0777);
for ($i = 0; $i < 7; $i++)
{
$file_name = $_FILES['uploadFile' . $i]['name'];
// strip file_name of slashes
$file_name = stripslashes($file_name);
$file_name = str_replace("'", "", $file_name);
// $copy = copy($_FILES['uploadFile'. $i]['tmp_name'], "gallery/" . $_POST["name"] . "/" . $file_name);
if ((($_FILES['uploadFile' . $i]["type"] == "image/gif")
|| ($_FILES['uploadFile' . $i]["type"] == "image/jpeg")
|| ($_FILES['uploadFile' . $i]["type"] == "image/pjpeg"))
&& ($_FILES['uploadFile' . $i]["size"] < 200000000))
{
if ($_FILES['uploadFile' . $i]["error"] > 0)
{
$message = "Return Code: " . $_FILES['uploadFile' . $i]["error"] . "<br />";
}
else
{
$query = "INSERT INTO property (
name, contact, email, type_of_listing, rent_sell, address, prop_desc, area, price, main_image, image_1, image_2, image_3, image_4, image_5, image_6, heading, bathroom, bedroom, garages, carports, granny_flat, full_description, full_ad, 49_ref, 99_ref, listed
) VALUES (
'{$name}', '{$contact}', '{$email}', '{$type}', '{$rent_sell}', '{$address}', '{$limitedtextarea}', '{$where}', '{$price}', '{$photo_1}', '{$photo_2}', '{$photo_3}', '{$photo_4}', '{$photo_5}', '{$photo_6}', '{$photo_7}', '{$heading}', '{$bathroom}', '{$bedroom}', '{$garages}', '{$carports}', '{$granny_flat}', '{$fulldesc}', '{$full_ad}', 'ref_49_{$ref_49}', 'ref_99_{$ref_99}', ''
)";
$result = mysql_query($query, $connection);
if (file_exists("gallery/" . $_POST["name"] . "/" . $_FILES['uploadFile' . $i]["name"]))
{
$message = "<h3>" . $_FILES['uploadFile' . $i]["name"] . " already exists.</h3>";
}
else
{
move_uploaded_file($_FILES['uploadFile' . $i]["tmp_name"], "gallery/" . $_POST["name"] . "/" . $_FILES['uploadFile' . $i]["name"]);
$message = "File: " . $_FILES['uploadFile' . $i]["name"] . " uploaded.";
}
}
}
else
{
$message = "<h3>Invalid file or no file selected.</h3><br />• Only JPEG OR GIF allowed.<br />• Size limited may not exceed 200KB.<br />Return";
}
}
}
}
There could be a lot of things going wrong here. Have you tried to break this up into pieces? Are you sure the DB is connecting? Are you sure php has access to write to the directories it's attempting to write to? Are you sure those directories exist...etc. etc.
Comment out the vast majority of the code, and start testing all the components piece by piece, or wrap stuff in try/catch and see what errors are produced.
[edit]
If the problem only occurs when you upload < 7 files then the problem is in that you've hard coded a 7 into your loop!
Loop through how many files are actually being uploaded, not a fixed number.
Assuming they're all being named sequentially (and starting at 0) you can test for the existence of your hashed FILE value in the loop and just keep ingesting until it comes up null (probably good to add a limiter to make sure it can't go on for ever)
something like this...
[edit 2] modified the condition to include a test for file size
for($i=0; $_FILES['uploadFile' . $i] && $_FILES['uploadFile' . $i]['size'] > 0 && $i<100 ; $i++){
try{
//do your upload stuff here
}catch(e){}
}
[EDIT]
To modify your page to include a dynamic number of fields do this:
check out this fiddle: http://jsfiddle.net/RjcHY/2/
Click the plus and minus buttons on the right side to see how it works. I made it so that it's naming the file buttons as per your php's expectations.
While dealing with common tasks like file uploading, write some library for handling those tasks and call necessary function wherever needed . If you create an uploader class file , you can simply invoke one of the methods you created to handle file uploads .
Here i will give you a Uploader class
<?php
//Save file as Uploader.php
//File Uploading Class
class Uploader
{
private $destinationPath;
private $errorMessage;
private $extensions;
private $allowAll;
private $maxSize;
private $uploadName;
private $seqnence;
public $name='Uploader';
public $useTable =false;
function setDir($path){
$this->destinationPath = $path;
$this->allowAll = false;
}
function allowAllFormats(){
$this->allowAll = true;
}
function setMaxSize($sizeMB){
$this->maxSize = $sizeMB * (1024*1024);
}
function setExtensions($options){
$this->extensions = $options;
}
function setSameFileName(){
$this->sameFileName = true;
$this->sameName = true;
}
function getExtension($string){
$ext = "";
try{
$parts = explode(".",$string);
$ext = strtolower($parts[count($parts)-1]);
}catch(Exception $c){
$ext = "";
}
return $ext;
}
function setMessage($message){
$this->errorMessage = $message;
}
function getMessage(){
return $this->errorMessage;
}
function getUploadName(){
return $this->uploadName;
}
function setSequence($seq){
$this->imageSeq = $seq;
}
function getRandom(){
return strtotime(date('Y-m-d H:iConfused')).rand(1111,9999).rand(11,99).rand(111,999);
}
function sameName($true){
$this->sameName = $true;
}
function uploadFile($fileBrowse){
$result = false;
$size = $_FILES[$fileBrowse]["size"];
$name = $_FILES[$fileBrowse]["name"];
$ext = $this->getExtension($name);
if(!is_dir($this->destinationPath)){
$this->setMessage("Destination folder is not a directory ");
}else if(!is_writable($this->destinationPath)){
$this->setMessage("Destination is not writable !");
}else if(empty($name)){
$this->setMessage("File not selected ");
}else if($size>$this->maxSize){
$this->setMessage("Too large file !");
}else if($this->allowAll || (!$this->allowAll && in_array($ext,$this->extensions))){
if($this->sameName==false){
$this->uploadName = $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$this->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
}else{
$this->uploadName= $name;
}
if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.$this->uploadName)){
$result = true;
}else{
$this->setMessage("Upload failed , try later !");
}
}else{
$this->setMessage("Invalid file format !");
}
return $result;
}
function deleteUploaded(){
unlink($this->destinationPath.$this->uploadName);
}
}
?>
Using Uploader.php
<?php
$uploader = new Uploader();
$uploader->setDir('uploads/images/');
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list//
$uploader->setMaxSize(.5); //set max file size to be allowed in MB//
if($uploader->uploadFile('txtFile')){ //txtFile is the filebrowse element name //
$image = $uploader->getUploadName(); //get uploaded file name, renames on upload//
}else{//upload failed
$uploader->getMessage(); //get upload error message
}
?>
For handling multiple uploads , ex 3 images uploading
repeat the block as follows
<?php
for($i=1;$i<=3;$i++){
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list//
$uploader->setMaxSize(.5); //set max file size to be allowed in MB//
$uploader->setSequence($i);
if($uploader->uploadFile('txtFile'.$i)){ //txtFile is the filebrowse element name //
$image = $uploader->getUploadName(); //get uploaded file name, renames on upload//
}else{//upload failed
$uploader->getMessage(); //get upload error message
}
}
?>
in above example , file browse components are named as txtFile1,txtFile2,txtFile3
Hope you will understand my explanation .