I wrote a utility (w/CodeIgniter 3.0.5) for a client that allows him to upload photos, and they're resized for the web. The script has been working fine for several months, but all of a sudden he's getting out-of-memory errors, along the lines of this:
FILE NAME: IMG_0047.JPG test
Resizing image...
New image: /homepages/20/d153810528/htdocs/toolbox/stuff/images/tool_photos/IMG_0047_resized.JPG
New filename: IMG_0047_resized.JPG
Fatal error: Out of memory (allocated 35389440) (tried to allocate
4032 bytes) in
/homepages/20/d153810528/htdocs/toolbox/cat/libraries/Image_lib.php on
line 1455
The "resized" images aren't actually saved.
I know the first choice solution is to allocate more memory with php_ini, but it appears that the hosting provider -- 1and1 . com -- doesn't allow that; it's set at a hard 120M; I'm guessing they don't want customers screwing with their shared servers.
Any thoughts?
Here's the code that handles the resizing:
public function uploadapicture() {
$status = '';
$msg = '';
$file_element_name = 'picture';
if ($status !== 'error') {
$config['upload_path'] = 'stuff/images/tool_photos/';
$config['allowed_types'] = 'gif|jpeg|png|jpg';
$config['max_size'] = 1024 * 50;
$config['encrypt_name'] = FALSE;
$this->load->library('upload',$config);
if (!$this->upload->do_upload($file_element_name)) {
$status = 'error';
$msg = $this->upload->display_errors('','');
} else {
$data = $this->upload->data();
$image_path = $data['full_path'];
if (file_exists($image_path)) {
$status = 'success';
$msg = 'Main picture "' . $_FILES[$file_element_name]['name'] . '" successfully uploaded';
} else {
$status = 'error';
$msg = 'There was a problem saving the main picture.';
}
}
#unlink($_FILES[$file_element_name]);
$file_element_name = 'thumbnail';
if ((strlen($_FILES[$file_element_name]['name']) > 0) && !$this->upload->do_upload($file_element_name)) {
$status = 'error';
$msg .= $this->upload->display_errors('','');
} else if (strlen($_FILES[$file_element_name]['name']) > 0) {
$data = $this->upload->data();
$image_path = $data['full_path'];
if (file_exists($image_path)) {
$status = 'success';
$msg .= 'Thumbnail successfully uploaded';
} else {
$status = 'error';
$msg .= 'There was a problem saving the thumbnail.';
}
}
if ($status === 'success') {
echo "<br><pre>Post stuff:" . print_r($_POST,1);
$toolToInsert = array(
'picture_filename' => $_FILES['picture']['name'],
'name' => $this->input->post('name'),
'purchase_price' => $this->input->post('purchase_price'),
'public_notes' => $this->input->post('public_notes'),
'public_misc' => $this->input->post('public_misc'),
'purchased_from' => $this->input->post('purchased_from'),
'private_purchase_date' => $this->input->post('private_purchase_date'),
'private_purchase_price' => $this->input->post('private_purchase_price'),
'purchase_location' => $this->input->post('purchase_location'),
'sold_by' => $this->input->post('sold_by'),
'date_sold' => $this->input->post('date_sold'),
'sale_price' => $this->input->post('sale_price'),
'sold_to_name' => $this->input->post('sold_to_name'),
'sold_to_phone' => $this->input->post('sold_to_phone'),
'sold_to_email' => $this->input->post('sold_to_email'),
'private_notes' => $this->input->post('private_notes'),
'private_misc' => $this->input->post('private_notes'),
'entered_this_year' => $this->input->post('entered_this_year'),
'year_entered' => date('Y')
);
if (isset($_FILES['thumbnail']['name'])) {
$toolToInsert['thumbnail_filename'] = $_FILES['thumbnail']['name'];
}
foreach($_POST as $pKey => $pVal) {
if (substr($pKey,0,9) === 'category_') {
error_log("Found a category: ".print_r($pVal,1)." for key of ".print_r($pKey,1));
$post_category[] = substr($pKey,9);
}
}
if (isset($post_category)) {
$toolToInsert['category'] = implode(',',$post_category);
}
if (isset($_POST['active'])) {
$toolToInsert['active'] = 1;
}
$this->load->model('Letme_model');
$result = $this->Letme_model->insertTool('tool_db',$toolToInsert);
echo "Result: \n";
echo print_r($result,1);
}
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}
one way to increase memory in php 5.x for uploading images is in your .htaccess
just add this lines:
## I need more memory to upload large image
<IfModule mod_php5.c>
php_value memory_limit 256M ## or whatever you need
</IfModule>
Related
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.
public function addAppdetails()
{ $dev_id = $this->sessionStart();
$this->load->library('form_validation');
$this->form_validation->set_rules('appname', 'App Name', 'required');
$this->form_validation->set_rules('platform', 'Platform', 'required');
//$this->form_validation->set_rules('category','App Category','required');
$this->form_validation->set_rules('description', 'App Description', 'required');
//$this->form_validation->set_rules('app_pic','App Pic','required');
//$this->form_validation->set_rules('file','App File','required');
if ($this->form_validation->run())
{
$appname = $this->input->post('appname');
$platform = $this->input->post('platform');
$category1 = $this->input->post('category');
$descripton = $this->input->post('description');
$category = implode(",", $category1);
echo "l";
$data1=$this->appFileupload();
echo "Break";
$data2=$this->appImageupload();
die;
foreach ($data1 as $dataArray)
{
$fileName=$dataArray['file_name'];
}
foreach ($data2 as $dataArray)
{
$imageName=$dataArray['file_name'];
}
$data = array('name' => $appname, 'platform' => $platform, 'description' => $descripton, 'category' => $category,'file_name'=>$fileName,'image_name'=>$imageName,'dev_id'=>$dev_id);
$this->Dev_model->addApp($data);
//$this->appImageupload();
echo "yolo";
}
else
{
$data['dataArray'] = $this->sessionStart();
$category = $this->input->post('category');
print_r($category);
$this->load->view('dev/addApp', $data);
}
}
public function appFileupload()
{
$config1['upload_path'] = './uploads/files';
$config1['allowed_types'] = 'apk|exe';
$this->load->library('upload', $config1);
if ( ! $this->upload->appFileUpload('file'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data;
}
}
public function appImageupload()
{
$config2['upload_path'] = './uploads/appImages';
$config2['allowed_types'] = 'gif|jpg|png';
$config2['max_size'] = 1000000000;
$config2['max_width'] = 10240000;
$config2['max_height'] = 76800000;
$this->load->library('upload', $config2);
if ( ! $this->upload->appImageUpload('app_pic'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data;
}
}
The output is as follows:
lBreak
Array ( [error] =>
The filetype you are attempting to upload is not allowed.
)
So, if I exchange the positions of appFileupload() and appImageupload() then it will give the same error for 'apk|exe' file and right now it is giving the error for appImageupload(). If you will ask how do I know about this? Then the answer is, I have checked their folder one gets uploaded but not the other.
CodeIgniter version is: 3.x
Add * in place of another type.
$config['allowed_types'] = '*';
I am just suggesting this for test purpose
Edit:
I am not sure but this will be helpful.
You could try looking at system/libraries/Upload.php line 199:
$this->_file_mime_type($_FILES[$field]);
Change that line to:
$this->_file_mime_type($_FILES[$field]); var_dump($this->file_type); die();
Well Lol, I'm answering my own question.
First, loading the library again with $config2 won't work because the library is already loaded once and $config1 will stay loaded. To load a new config use:
$this->upload->initialize($config2);
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 ma trying to upload multiple images from HTML FORM but on submit only last image uploaded please any one who can figure out this problem
here is my controller
if($_FILES['image']['name'] != "")
{
$data['image'] = $this->MUtils->doUpload('image',270,65,false);
}
if($_FILES['adv_image1']['name']!= "")
{
$data['adv_image1'] = $this->MUtils->doUpload('adv_image1',340,130,false);
}
if($_FILES['adv_image2']['name']!= "")
{
$data['adv_image2'] = $this->MUtils->doUpload('adv_image2',860,100,false);
}
Model is
if($data['image']!="" ){
$arr=array('image' => $data['image']);
}
if($data['adv_image1']!=""){
$arr=array('adv_image1' => $data['adv_image1']);
}
if($data['adv_image2']!=""){
$arr=array('adv_image2' => $data['adv_image2']);
}
if($data['adv_image3']!=""){
$arr['adv_image3'] = $data['adv_image3'];
}
$this->db->where('id',$data['listid']);
$this->db->update('list', $arr);
return 1;
doUpload Functio is here
//Upload file and return url
function doUpload($field, $width, $height, $resize=false)
{
//Configure upload.
$this->upload->initialize(array(
"upload_path" => "../uploads/",
"allowed_types" => "gif|jpg|png",
));
//Perform upload.
if($this->upload->do_upload($field)){
$fileData = $this->upload->data();
if ($resize == true)
{
$width = $fileData['image_width'];
$height = $fileData['image_height'];
}
$img_cfg_thumb['image_library'] = 'gd2';
$img_cfg_thumb['source_image'] = "../uploads/" . $fileData['raw_name'] . $fileData['file_ext'];
$img_cfg_thumb['maintain_ratio'] = FALSE;
$img_cfg_thumb['new_image'] = "../uploads/" . $fileData['raw_name'] . $fileData['file_ext'];
$img_cfg_thumb['width'] = $width;
$img_cfg_thumb['height'] = $height;
$img_cfg_thumb['quality'] = 90;
$this->load->library('image_lib');
$this->image_lib->initialize($img_cfg_thumb);
$this->image_lib->resize();
return $fileData['raw_name'] . $fileData['file_ext'];
}
else
{
return "";
}
}
Note this is working, but from three pics just last one is uploaded on submit
In your model change following lines:
if($data['image']!="" ){
$arr=array('image' => $data['image']);
}
if($data['adv_image1']!=""){
$arr=array('adv_image1' => $data['adv_image1']);
}
if($data['adv_image2']!=""){
$arr=array('adv_image2' => $data['adv_image2']);
}
if($data['adv_image3']!=""){
$arr=array('adv_image3' => $data['adv_image3']);
}
To these lines:
if($data['image']!="" ){
$arr['image'] = $data['image'];
}
if($data['adv_image1']!=""){
$arr['adv_image1'] = $data['adv_image1'];
}
if($data['adv_image2']!=""){
$arr['adv_image2'] = $data['adv_image2'];
}
if($data['adv_image3']!=""){
$arr['adv_image3'] = $data['adv_image3'];
}
You need to clear your config and lib each time.
Try below code at starting of the function:
unset($config)
$this->upload->clear();
Hope this helps
I have a form where multiple files can be uplaoded, along with a name field and a date field. The user can clone the inputs and upload as many certificates as they need. My HTML is below:
HTML:
<input type="file" name="certificate[]" />
<input type="text" name="certificate_name[]" class="right" />
<input type="text" name="expiry_date[]" />
I can upload the files one at a time but as multiple uploads it doesn't work, I get an error
A PHP Error was encountered
Severity: Warning
Message: is_uploaded_file() expects parameter 1 to be string, array given
Filename: libraries/Upload.php
Line Number: 161
PHP:
$uid = 1;
if(isset($_FILES['certificate']))
{
$this->uploadcertificate($uid, $this->input->post('certificate_name'), $this->input->post('expiry_date'));
}
function uploadcertificate($uid, $certificate, $expiry_date)
{
$status = "";
$msg = "";
$file_element_name = 'certificate';
$certificate_name = $certificate;
if ($status != "error")
{
$config['upload_path'] = './certificate_files/';
$config['allowed_types'] = 'pdf|doc|docx|txt|png|gif|jpg|jpeg|';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$status = 'error';
$msg = $this->upload->display_errors();
}
else
{
$data = $this->upload->data();
$file_id = $this->saveCertificate($uid, $data['raw_name'], $data['file_ext'], $certificate_name, $expiry_date);
}
if($file_id)
{
$status = "success";
$msg = "File successfully uploaded";
}
else
{
//unlink($data['full_path']);
$status = "error";
$msg = "Something went wrong when saving the file, please try again.";
}
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}
function saveCertificate($uid, $file_name, $file_ext, $certificate_name, $expiry_date)
{
for ($ix=0; $ix<count($_FILES['certificate']); $ix++)
{
$insert_certificates = array(
'user_ID' => $uid,
'certificate' => $_POST['certificate_name'][$ix],
'certificate_name' => $_POST['child_dob_additional'][$ix],
'expiry_date' => $_POST['expiry_date'][$ix]
);
$insert = $this->db->insert('certificates', $insert_certificates);
//return $insert; //you cant return here. must let the loop complete.
$insert_certificates_history = array(
'user_ID' => $uid,
'certificate' => $_POST['certificate_name'][$ix],
'certificate_name' => $_POST['child_dob_additional'][$ix],
'expiry_date' => $_POST['expiry_date'][$ix]
);
$insert = $this->db->insert('certificates_history', $insert_certificates_history);
}
}
I'm confused as to exactly where I have went wrong. Can anyone point me in the right direction. Many thanks in advance!