3

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;
        }
    }
}
  • You're calling `uploadFile ` on `$dbxClient`, so this error should indicate that `$dbxClient` isn't an object. You attempt to retrieve it using `getClient`, so try debugging your `getClient` method. Perhaps execution is entering that `isset` block. – Greg Sep 08 '16 at 16:48

0 Answers0