I'm working on CodeIgniter using XAMPP. When I upload my files on my subdomain, it give me an error but its working on my local machine.
here is my controller
if ($this->session->userdata('admin_email') && $this->session->userdata('admin_id')) {
$data['title'] = $this->session->userdata('admin_name');
$this->load->view('admin/header',$data);
$this->load->view('admin/topbar');
$this->load->view('admin/sidebar');
//$this->load->view('admin/home');
$this->load->view('admin/footer');
}
else
{
$this->session->set_flashdata('adminlogin','please login first..');
redirect('admin/login');
}
here is my error:
A PHP Error was encountered
Severity: Warning
Message: Cannot modify header information - headers already sent by
(output started at
/home/shakzeec/public_html/demo/application/controllers/admin.php:2)
Filename: libraries/Session.php
Line Number: 688 A PHP Error was encountered
Severity: Warning
Message: Cannot modify header information - headers already sent by
(output started at
/home/shakzeec/public_html/demo/application/controllers/admin.php:2)
Filename: libraries/Session.php
Line Number: 688 A PHP Error was encountered
Severity: Warning
Message: Cannot modify header information - headers already sent by
(output started at
/home/shakzeec/public_html/demo/application/controllers/admin.php:2)
Filename: helpers/url_helper.php
Line Number: 542
PHP does not allow you to modify headers once output is already started. Redirecting requires a change to the header. If you want to redirect, do only a redirect and nothing else.
if (!$this->session->userdata('admin_email') && !$this->session->userdata('admin_id')) {
$this->session->set_flashdata('adminlogin','please login first..');
redirect('admin/login');
}
else{
$data['title'] = $this->session->userdata('admin_name');
$this->load->view('admin/header',$data);
$this->load->view('admin/topbar');
$this->load->view('admin/sidebar');
//$this->load->view('admin/home');
$this->load->view('admin/footer');
}
Also, make sure there is nothing else in your controller which could be sending output before you modify the headers.
Here is the controllers/employers.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Employers extends CI_Controller {
public function __construct() {
parent::__construct();
date_default_timezone_set("Asia/Manila");
$this->load->model('_user');
}
public function index()
{
$data['userlist'] = $this->_user->get_user_list();
$this->load->view('employers/index', $data);
$this->template->render();
}
public function registration()
{
$data['userToken'] =$this->scriptor->userToken();
$data['userlist'] = $this->_user->get_user_list();
if(!isset($_REQUEST['msg'])){ $_REQUEST['msg'] = ''; }
$this->load->view('employers/registration', $data);
$this->template->render();
}
public function newregister()
{
$dr = strlen($_SERVER['PHP_SELF']) - 9;
$path = $_SERVER["DOCUMENT_ROOT"] .substr($_SERVER['PHP_SELF'], 0, $dr) .'image/source/employer/' . strtolower($this->input->post('Username'));
if(!is_dir($path)){
//Make Directory
if (!mkdir($path, 0777, true)) {
die('Failed to create folders...');
}
}
$config['upload_path'] = $path;
$config['file_name'] = url_title(strtolower($this->input->post('Username'))) . $this->upload->data('file_ext');
$config['allowed_types'] = 'gif|jpg|png|';
$config['max_size'] = '';
$config['max_width'] = '';
$config['max_height'] = '';
$this->upload->initialize($config);
$err = 'failed_reg';
$ok = true;
if(strlen($this->input->post('Username')) == 0){
$ok = false;
$err = 'err_username';
}
if(strlen($this->input->post('Lastname')) == 0 && $ok){
$ok = false;
$err = 'err_lastname';
}
if(strlen($this->input->post('Firstname')) == 0 && $ok){
$ok = false;
$err = 'err_firstname';
}
if(strlen($this->input->post('Email')) == 0 && $ok){
$ok = false;
$err = 'err_email';
}
if(strlen($this->input->post('Cellphone')) == 0 && $ok){
$ok = false;
$err = 'err_cellphone';
}
if(strlen($this->input->post('Telephone')) == 0 && $ok){
$ok = false;
$err = 'err_telephone';
}
if(strlen($this->input->post('Address')) == 0 && $ok){
$ok = false;
$err = 'err_address';
}
if(strlen($this->input->post('City')) == 0 && $ok){
$ok = false;
$err = 'err_city';
}
if(!$this->upload->do_upload('EmpPic') && $ok){
$ok = false;
if(is_dir($path)){
array_map('unlink', glob($path."/*"));
rmdir($path);
}
$err = 'err_image';
}
if($_FILES['EmpGovID']['size'] > 0){
if(!$this->upload->do_upload('EmpGovID') && $ok){
$ok = false;
if(is_dir($path)){
array_map('unlink', glob($path."/*"));
rmdir($path);
}
$err = 'err_image2';
}
}
if($ok){
$i = array(
'Firstname' => $this->scriptor->_enc($this->input->post('Firstname'))
, 'Middlename' => $this->scriptor->_enc($this->input->post('Middlename'))
, 'Lastname' => $this->scriptor->_enc($this->input->post('Lastname'))
, 'Telephone' => $this->scriptor->_enc($this->input->post('Telephone'))
, 'Cellphone' => $this->scriptor->_enc($this->input->post('Cellphone'))
, 'Email' => $this->scriptor->_enc($this->input->post('Email'))
, 'Address' => $this->scriptor->_enc($this->input->post('Address'))
, 'City' => $this->scriptor->_enc($this->input->post('City'))
, 'EPicture' => base_url('image/employer') . '/'.$config['file_name']
, 'Username' => $this->scriptor->_enc($this->input->post('Username'))
, 'Password' => $this->scriptor->_enc($this->input->post('Password'))
, 'Token' => $this->scriptor->userToken()
, 'Level' => 'user'
, 'Yatype' => $this->scriptor->_enc($this->input->post('Yatype'))
, 'GovID' => base_url('image/employer') . '/'.$config['file_name']
, 'q1' => $this->scriptor->_enc($this->input->post('q1'))
, 'q2' => $this->scriptor->_enc($this->input->post('q2'))
, 'q3' => $this->scriptor->_enc($this->input->post('q3'))
, 'aq1' => $this->scriptor->_enc($this->input->post('aq1'))
, 'aq2' => $this->scriptor->_enc($this->input->post('aq2'))
, 'salary' => $this->scriptor->_enc($this->input->post('salary'))
, 'registeredDate' => date('Y-m-d h:i:s')
, 'Message' => $this->scriptor->_enc($this->input->post('Message'))
);
$this->_user->add($i);
redirect('employers/registration?msg=success_reg');
} else {
redirect('employers/registration?msg='. $err);
}
/******************************************************************/
}//End Class
}
Related
Created an API endpoint I which I am submitted data as the body in postman, but it is always empty on the server whereas it works fine on localhost.
Please look at the request
The same request works on localhost but not online. Here is code on the server side I am using Yii::$app->request->post() to dump the data, here is the full code of that endpoint. I had tried $_POST,$_REQUEST every request is empty on the server,
public function actionSocialcheck()
{
$data = [];
$model = new User();
var_dump(Yii::$app->request->post());
if ($model->load(Yii::$app->request->post(),'')) {
$social = User::findBySocialLogin($model->socialLogin);
if (empty($social)) {
$data['status'] = self::API_OK;
$data['check'] = false;
} else {
if (Yii::$app->request->post('role_id') != $social->role_id) {
$data['error'] = \Yii::t('app', "You don't have permission to login as " . User::getRoleOptions($social->role_id));
return $this->response = $data;
}
$data['error'] = \yii::t('app', "Social ID already exists.");
$data['check'] = true;
$data['status'] = self::API_OK;
$data['detail'] =$social;
$data['access-token'] = $social->access_token;
// $usercl=new User();
$loginarr = array(
'device_name' => Yii::$app->request->post('device_name'),
'device_token' => Yii::$app->request->post('device_token'),
'device_type' => Yii::$app->request->post('device_type'),
);
$data['login_detail']=$loginarr;
}
} else {
$data['error'] = "Data not posted.";
}
$this->response = $data;
}
When I try the same request on the local server it works fine here is the output of that
Can you please help me out in this case. Thanks
public function actionSocialcheck(){
if(Yii::$app->request->isPost){
$data = [];
$social = User::findBySocialLogin(Yii::$app->request->post('socialLogin'));
if (empty($social)){
$data['status'] = self::API_OK;
$data['check'] = false;
}else{
if (Yii::$app->request->post('role_id') != $social->role_id) {
$data['error'] = \Yii::t('app', "You don't have permission to login as " . User::getRoleOptions($social->role_id));
return $this->response = $data;
}
$data['error'] = \yii::t('app', "Social ID already exists.");
$data['check'] = true;
$data['status'] = self::API_OK;
$data['detail'] =$social;
$data['access-token'] = $social->access_token;
$loginarr = array(
'device_name' => Yii::$app->request->post('device_name'),
'device_token' => Yii::$app->request->post('device_token'),
'device_type' => Yii::$app->request->post('device_type'),
);
$data['login_detail']=$loginarr;
}
}else {
$data['error'] = "Data not posted.";
}
$this->response = $data;
}
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.
Fatal Error: call to a member function uploadFile() on a non-object
Getting this error of upload file function on Uploading File to dropbox using PHP API On live Server. Same Code Working fine on localhost and doing it in codeigniter. start of code is**
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
error_reporting(1);
require_once(APPPATH . 'libraries/dropbox/vendor/autoload.php');
use \Dropbox as dbx;
class Knowledge extends CI_Controller
{
public $appInfoFile;
public $requestPath; **
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
$this->load->helper('url');
$this->load->database();
$this->load->library('form_validation');
//load the models
$this->load->model('knowledge_model');
//$this->load->helper('messages');
//$this->load->model('messages_model');
$this->load->model('messages_model', 'send_messages');
// custom library in codeigniter
$this->appInfoFile = APPPATH.'libraries/dropbox/app-info.json';
$redirect_uri ='https://www.domainname.com/knowledge/add/';
$requestPath = $this->init();
session_start();
validate_user();
}
public function index($msg = NULL)
{
$session_data = $this->session->all_userdata();
$data['msg'] = $msg;
if (isset($session_data["validated"]) && $session_data["validated"] == '1') {
$data['title'] = 'Knowledge Center';
$data['records'] = $this->knowledge_model->get_all_rec();
// echo "<pre>".print_r($data['records'],true)."</pre>";exit;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('knowledge', $data);
$this->load->view('includes/footer');
} else {
redirect(base_url());
}
}
public function tag($msg = NULL)
{
$tagname = $this->uri->segment("3");
$tagnamehits = $this->uri->segment("4");
$session_data = $this->session->all_userdata();
$data['msg'] = $msg;
if (isset($session_data["validated"]) && $session_data["validated"] == '1') {
$data['title'] = 'Knowledge Center';
$data['update_rec'] = $this->knowledge_model->update_hits($tagnamehits);
$data['records'] = $this->knowledge_model->get_notifyrec_bytags($tagname);
//echo "<pre>".print_r($data['records'],true)."</pre>";exit;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('knowledge', $data);
$this->load->view('includes/footer');
} else {
redirect(base_url());
}
}
public function add()
{
//validate form input
$this->form_validation->set_rules('subject', 'subject', 'required');
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$seralizedtags = serialize($this->input->post('tagsar'));
//echo "<pre>".print_r($seralizedArray,true)."</pre>";exit;
// drop box upload filess
if (isset($_FILES['attached_file']['name']) && !empty($_FILES['attached_file']['name'])) {
$file_name= $_FILES['attached_file']['name'];
$return_result=$this->upload_to_dropbox($file_name);
$rev=$return_result['rev'];
$mime_type=$return_result['mime_type'];
$path=$return_result['path'];
$size=$return_result['size'];
$revision=$return_result['revision'];
}
if ($this->form_validation->run() == true) {
$session_data = $this->session->all_userdata();
$user_id = $session_data["userid"];
$data = array(
'user_id' => $user_id,
'edit_by_userid' => $user_id,
'subject' => $this->input->post('subject'),
'tags' => $seralizedtags,
'description' => $this->input->post('description'),
'dropbox_rev'=>$rev,
'dropbox_mim_type'=>$mime_type,
'dropbox_path'=>$path,
'dropbox_filesize'=>$size,
'dropbox_revision'=>$revision,
);
$message=$this->input->post('subject');
//for slack call
if(isset($message)){
$message=$message;
$messageType = "Knowledge_center";
$this->send_messages->send_message_on_slack($messageType);
}
//echo "<pre>" . print_r($data, true) . "</pre>";
$insert_res = $this->knowledge_model->insert_rec($data);
if ($insert_res != "conf") {
if ($insert_res == "subject") {
$this->session->set_flashdata('message', "<p>Subject Name already exist.Please change Subject</p>");
} else {
$this->session->set_flashdata('message', "<p>Error in Insertion.</p>");
}
echo '<script>window.location.href = "' . base_url() . 'knowledge/add";</script>';
} else {
$this->session->set_flashdata('message', "<p>Record added successfully.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
}
} else {
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$this->data['subject'] = array(
'name' => 'subject',
'class' => 'form-control round-input',
'id' => 'subject',
'placeholder' => 'Subject',
'type' => 'text',
'autofocus' => 'true',
'data-required' => '1',
'value' => $this->form_validation->set_value('subject'),
);
$this->data['tagdata'] = array(
'name' => 'tagsar',
'class' => 'form-control tags tags-input',
'id' => 'tagsar',
'type' => 'text',
'autofocus' => 'true',
'data-type' => 'tags',
'value' => $this->form_validation->set_value('tagsar'),
);
$data['desc'] = $this->form_validation->set_value('description');
// $data['dropbox']=$this->dropbox->dp();
$msg = "";
$data['title'] = 'Knowledge Center';
$data['msg'] = $msg;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('add_knowledge', $this->data);
$this->load->view('includes/footer');
}
}
public function view($id)
{
$update_rec = $this->knowledge_model->get_rec_byid($id);
$data['dropbox_detail']=array(
"dropbox_rev"=> $update_rec[0]->dropbox_rev,
"dropbox_mim_type"=> $update_rec[0]->dropbox_mim_type,
"dropbox_path"=> $update_rec[0]->dropbox_path,
"dropbox_filesize"=> $update_rec[0]->dropbox_filesize,
"dropbox_revision"=> $update_rec[0]->dropbox_revision,
);
$data['subject_data'] = $update_rec[0]->subject;
$data['tags_data'] = unserialize($update_rec[0]->tags);
$data['desc'] = $update_rec[0]->description;
$data['title'] = 'Knowledge Center';
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('view_knowledge', $this->data);
$this->load->view('includes/footer');
}
public function manage_notify()
{
$notifyid = $_POST["elid"];
$notifytext = $_POST["notifytext"];
$notify_rec = $this->knowledge_model->get_notifyrec_byid($notifytext);
$ret_res = "<ul>";
foreach ($notify_rec as $notify_record) {
$ret_res .= "<li>" . $notify_record->subject . "</li>";
}
$ret_res .= "</ul>";
echo $ret_res;
exit;
}
public function update($id)
{
//validate form input
$this->form_validation->set_rules('subject', 'subject', 'required');
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$update_rec = $this->knowledge_model->get_rec_byid($id);
//echo "<pre>".print_r($update_rec[0],true)."</pre>";exit;
$seralizedtags = serialize($this->input->post('tagsar'));
if ($this->form_validation->run() == true) {
$session_data = $this->session->all_userdata();
$user_id = $session_data["userid"];
$data = array(
'edit_by_userid' => $user_id,
'subject' => $this->input->post('subject'),
'tags' => $seralizedtags,
'description' => $this->input->post('description')
);
$recid = $this->input->post('recid');
// echo "<pre>".print_r($data,true)."</pre>";exit;
$update_res = $this->knowledge_model->update_rec($recid, $data);
if ($update_res > 0) {
$this->session->set_flashdata('message', "<p>Record Updated successfully.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
} else {
$this->session->set_flashdata('message', "<p>Error in Updation.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge/update/' . $recid . '";</script>';
}
} else {
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
if (isset($update_rec)) {
$this->data['recid'] = array(
'name' => 'recid',
'class' => 'form-control',
'id' => 'recid',
'type' => 'hidden',
'autofocus' => 'true',
'data-required' => '1',
'value' => $update_rec[0]->id,
);
$this->data['subject'] = array(
'name' => 'subject',
'class' => 'form-control round-input',
'id' => 'subject',
'placeholder' => 'Subject',
'type' => 'text',
'autofocus' => 'true',
'data-required' => '1',
'value' => $update_rec[0]->subject,
);
$tags_data = unserialize($update_rec[0]->tags);
$this->data['tagdata'] = array(
'name' => 'tagsar',
'class' => 'form-control tags tags-input',
'id' => 'tagsar',
'type' => 'text',
'autofocus' => 'true',
'data-type' => 'tags',
'value' => $tags_data,
);
$data['desc'] = $update_rec[0]->description;
} else {
$this->session->set_flashdata('message', "<p>Update Record not found.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
}
$msg = "";
$data['title'] = 'Knowledge Center';
$data['msg'] = $msg;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('edit_knowledge', $this->data);
$this->load->view('includes/footer');
}
}
public function download_dbx_file(){
$file_path = $_POST['dropbox_path'];
$mime_type = $_POST['dropbox_mim_type'];
$this->download_file($file_path,$mime_type);
}
public function del($id)
{
$this->knowledge_model->del_rec($id);
$this->session->set_flashdata('message', "<p>Record Deleted successfully.</p>");
redirect(base_url() . 'knowledge');
}
// for upload to dropbox //
function getAppConfig()
{
global $appInfoFile;
try {
$appInfo = dbx\AppInfo::loadFromJsonFile($this->appInfoFile);
}
catch (dbx\AppInfoLoadException $ex) {
throw new Exception("Unable to load \"$this->appInfoFile\": " . $ex->getMessage());
}
$clientIdentifier = "examples-web-file-browser";
$userLocale = null;
return array($appInfo, $clientIdentifier, $userLocale);
}
function getClient()
{
if (!isset($_SESSION['access-token'])) {
return false;
}
list($appInfo, $clientIdentifier, $userLocale) = $this->getAppConfig();
$accessToken = $_SESSION['access-token'];
return new dbx\Client($accessToken, $clientIdentifier, $userLocale,$appInfo->getHost());
}
function getWebAuth()
{
list($appInfo, $clientIdentifier, $userLocale) = $this->getAppConfig();
$redirectUri = getUrl("dropbox-auth-finish");
$csrfTokenStore = new dbx\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token');
return new dbx\WebAuth($appInfo, $clientIdentifier, $redirectUri, $csrfTokenStore, $userLocale);
}
function respondWithError($code, $title, $body = "")
{
$proto = $_SERVER['SERVER_PROTOCOL'];
header("$proto $code $title", true, $code);
echo renderHtmlPage($title, $body);
}
function getUrl($relative_path)
{
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
$scheme = "https";
} else {
$scheme = "http";
}
$host = $_SERVER['HTTP_HOST'];
$path = getPath($relative_path);
return $scheme."://".$host.$path;
}
function getPath($relative_path)
{
if (PHP_SAPI === 'cli-server') {
return "/".$relative_path;
} else {
return $_SERVER["SCRIPT_NAME"]."/".$relative_path;
}
}
function init()
{
global $argv;
// If we were run as a command-line script, launch the PHP built-in web server.
if (PHP_SAPI === 'cli') {
launchBuiltInWebServer($argv);
assert(false);
}
if (PHP_SAPI === 'cli-server') {
// For when we're running under PHP's built-in web server, do the routing here.
return $_SERVER['SCRIPT_NAME'];
}
else {
// For when we're running under CGI or mod_php.
if (isset($_SERVER['PATH_INFO'])) {
return $_SERVER['PATH_INFO'];
} else {
return "/";
}
}
}
function launchBuiltInWebServer($argv)
{
// The built-in web server is only available in PHP 5.4+.
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
fprintf(STDERR,
"Unable to run example. The version of PHP you used to run this script (".PHP_VERSION.")\n".
"doesn't have a built-in web server. You need PHP 5.4 or newer.\n".
"\n".
"You can still run this example if you have a web server that supports PHP 5.3.\n".
"Copy the Dropbox PHP SDK into your web server's document path and access it there.\n");
exit(2);
}
$php_file = $argv[0];
if (count($argv) === 1) {
$port = 5000;
} else if (count($argv) === 2) {
$port = intval($argv[1]);
} else {
fprintf(STDERR,
"Too many arguments.\n".
"Usage: php $argv[0] [server-port]\n");
exit(1);
}
$host = "localhost:$port";
$cmd = escapeshellarg(PHP_BINARY)." -S ".$host." ".escapeshellarg($php_file);
$descriptors = array(
0 => array("pipe", "r"), // Process' stdin. We'll just close this right away.
1 => STDOUT, // Relay process' stdout to ours.
2 => STDERR, // Relay process' stderr to ours.
);
$proc = proc_open($cmd, $descriptors, $pipes);
if ($proc === false) {
fprintf(STDERR,
"Unable to launch PHP's built-in web server. Used command:\n".
" $cmd\n");
exit(2);
}
fclose($pipes[0]); // Close the process' stdin.
$exitCode = proc_close($proc); // Wait for process to exit.
exit($exitCode);
}
public function upload_to_dropbox($filename){
if($filename != ''){
try {
$dbxClient = $this->getClient();
$remoteDir = "/";
if (isset($_POST['folder'])) $remoteDir = $_POST['folder'];
$remotePath = rtrim($remoteDir, "/")."/".$filename;
$fp = fopen($_FILES['attached_file']['tmp_name'], "rb");
$result = $dbxClient->uploadFile($remotePath, dbx\WriteMode::add(), $fp);
fclose($fp);
//$str = print_r($result, true);
return $result;
} catch (Exception $e) {
echo $e->getMessage();
exit;
}
}
else{
echo "File does not exists";
exit;
}
}
public function download_file($file_path,$file_mime_type){
if($file_path != '' && $file_mime_type != '' ) {
try {
$dbxClient = $this->getClient();
$path = $file_path;
$fd = tmpfile();
$metadata = $dbxClient->getFile($path, $fd);
header("Content-Type: $metadata[mime_type]");
fseek($fd, 0);
fpassthru($fd);
fclose($fd);
} catch (Exception $e) {
echo $e->getMessage();
exit;
}
}
else{
echo "Invalid Request";
exit;
}
}
}
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>
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!