php - Codeigniter 3.1.0文件上传有效,但图像“full_path”信息从未插入数据库

标签 php mysql codeigniter

我设法将一个用户配置文件页面拼凑在一起,该页面将所有当前/相关的users表输出到表单文本输入中(通过set_value()),并且具有用于图像上传的文件上传输入(将显示)到更新后的页面)。表单上传过程确实很简单;

Profile.php(控制器文件)

function update() //"action" method from submission form 
{
      if ($this->input->server('REQUEST_METHOD') == 'POST') 
      {
          $this->form_validation->set_rules('website', 'Website');
          $this->form_validation->set_rules('password', 'Password', 'trim|min_length[4]|max_length[32]');
          $this->form_validation->set_rules('avatar', 'Profile Image', 'callback_image_upload');

          $this->form_validation->set_message('min_length', 'This %s must have at least %s characters');
          $this->form_validation->set_message('max_length', 'This %s must have at least %s characters');

           if($this->form_validation->run() == TRUE)
           {
              //Get the info from the form
              $website = $this->input->post('website');
              $password = $this->input->post('password');
              $temp = $this->upload->data('full_path');
              $avatar = $temp['file_name']; // to get image file name from upload script to be stored in the database

              //load the model
              $this->load->model('profile_model');
              $this->Profile->updateProfile($id,$avatar,$website, $password);
           }
           else
           {
              redirect('profile', 'refresh');           
           }
     }
}

function image_upload() //callback for previous update function
{ 
  if($this->ion_auth->logged_in())
  {
  if($_FILES['avatar']['size'] != 0)
  {
     $id = $this->ion_auth->get_user_id('id');

     $config['upload_path']   = './assets/images/avatars/'; 
     $config['allowed_types'] = 'gif|jpg|jpeg|png'; 
     $config['file_name']     = 'avatar_'.substr(md5(rand()),0,7);
     $config['overwrite']     = true; 
     $config['max_size']  = 10400; 

     $this->load->library('upload', $config);
     $this->upload->initialize($config);

      if (!$this->upload->do_upload('avatar'))
      { 
         $error = array('error' => $this->upload->display_errors());
         $this->load->view('profile_view', $error);  
      }    
      else
      {
         $avatar = $this->upload->data();

         $data = array(
            'path' => $avatar['full_path'],
            'avatar' => $avatar['file_name'],
            'maintain_ratio' => true,
            'width' => 300,
            'height' => 300

         );
         $fname = $avatar['file_name'];
         $fpath=$avatar['full_path'].$fname;

         return $avatar;
      }    
  }    
 }
}


对于一个事实,我知道在将$avatar['full_path'] CI数据数组原型元素自己插入到名为usersavatar表中的db列中时,我在第二个函数的末尾开始感到迷惑和崩溃。重写了前两个转录的函数以及模型;

//function to update user_profile    
function updateProfile($id, $avatar, $website, $password)
{
  if($this->ion_auth->logged_in())
  {
    if($_FILES['avatar']['error'] == 0)
    {       
      $avatar = $this->input->post('avatar');
      $website = $this->input->post('website');
      $password = $this->input->post('password');

      $data = array(
          'avatar' => $this->input->post('avatar'),
          'website' => $this->input->post('website'),
          'password' => $this->input->post('password')             
      );
      $this->db->set('avatar', $avatar);
      $this->db->set('website', $website);
      $this->db->set('password', $password);
      $this->db->where('id', $id);
      $this->db->update('users', $data);
      redirect('profile', 'refresh');
      exit;       
    }
  }
}


我越来越眼疲劳,想看看确切的地方在破坏数据提交过程。不使用$this->db->insert(),因为我需要允许用户更新其网站,密码和个人资料图像。充满了替换和插入的思想,以及解决问题的原生PHP方法;

if ($_FILES["file"]["error"] > 0)
{
   echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
    echo "File: ".$_FILES["file"]["name"]." Uploaded in:".$_FILES["file"]["tmp_name"];
}

move_uploaded_file($_FILES['uploaded_file']['tmp_name'], 
$image_path. $_FILES['uploaded_file']['name']);
$full_image_path = '/images/'.$_FILES['uploaded_file']['name']; 
$sql="insert into table_name(image) values( '$full_image_path')";


但这是原生传播效果不理想的时候之一。我检查过的与我有关的每个问题都让我质疑变量值来自/到达何处,或者试图寻找一种替代方法来牺牲已经起作用的上传机制。奇怪的是,我什至设法弄清了我认为会更难的东西。

<div class="row">
      <!-- left column -->
      <div class="col-md-3">
        <div class="text-center">
        <?php
        if(isset($user->avatar)){ // if the avatar has been uploaded then display it ?>
        <img src="<?php echo base_url().'assets/images/avatars/'.$user->avatar; ?>" class="avatar img-circle" alt="Profile Image" width="300px">
        <?php } else { ?>
        <img src="<?php echo base_url().'assets/images/avatars/default.jpg'; ?>" class="avatar img-circle" alt="Profile Image" width="300px">                       
        <?php } ?>      
          <?php echo '<h3 class="text-info">'.$user->first_name.' '.$user->last_name.'</h3>.'; ?>
          <h6>Upload a different photo...</h6>
          <input id="avatar" name="avatar" type="file" class="form-control" /><br>
        </div>
      </div>


在新招募者没有用户头像的情况下,使个人资料图像显示为default.jpg

User Profile Edit Page

当然,如果我不能让用户更改这些(有限的)详细信息,那么配置文件编辑套件有什么用处(大声笑!)?大约9个小时后(并发),我觉得有必要对此另外加关注。

事后更新

甚至尝试使用upload image and insert text in codeigniter中列出的代码,因为看起来好像是回调使事情变糟了。我的结果是我可以更改文本输入(刷新PHPMyAdmin视图(?!?)时未注册更改),但是我失去了上传功能。花了最后45分钟尝试同时进行编码和发布(大声笑!)。发布此内容后,将努力整合两种方法。再次感谢任何能看到我绊倒的人...

更新2:变得陌生人...

因此,我对单个代码块(profile/update)进行了重做,并直接从探查器中检查CI PostData结果,尽管显示了这一点,但我仍然没有任何表更新。
Current CI Profiler Output

即使探查器输出表明上传的图像位于我的WAMP解决方案的tmp目录中,在浏览时还是出现了一个大而肥的鹅蛋(除非上传被某种方式破坏了,不过看不到任何证据) )。我的下一步是将realpathAPPPATH(或两者的组合)放在$config['upload_path']上,以查看是否使某些东西松动了。至于文本输入,我一直不愿意触摸password,直到我看到其他两个元素都将自己插入第一个。目前,仍在尝试弄清楚如何将我的两个单独的功能集成到一个代码块中。那就是我在ATM上的高原...伴随着(cc)列的一个(琐碎的)问题,它会自动将其自身更新为当前日期时间,而不是实际创建用户的时间。可能是由于我翻译了该专栏中提供的Unix时间的方法的结果-但在我尝试压平的卡纸旁边,它显得苍白。

有时候,我越努力...

我非常喜欢以前提供的可运行的链接解决方案,因为我看到的是双红色ATM(大声笑!)。在整理这个问题的过程中,我经历了很多排列,而我又遇到了许多新问题。除了使用created_on链接提交过程外,我真的不确定是否有其他方案(特别是因为我现在觉得链接的解决方案是针对CI 2.x安装的)。只是证明了文档批准的编码;

$error = array('error' => $this->upload->display_errors());
$this->load->view('profile_view', $error);

     OR

$data['error'] = array('error' => $this->upload->display_errors());
$this->load->view('profile_view', $data);

    BOTH == 0  


置换的水平只是代码训练有素的版本,这仅仅是一个乏味的事情。

function update() //solid code block - 1st attempt
{
   if($this->ion_auth->logged_in())
   {
      if ($this->input->server('REQUEST_METHOD') == 'POST') 
      {
          $this->load->library('form_validation');

          $this->form_validation->set_rules('website', 'Website', 'trim');
          $this->form_validation->set_rules('password', 'Password', 'trim|min_length[4]|max_length[32]');

          $this->form_validation->set_message('min_length', 'This %s must have at least %s characters');
          $this->form_validation->set_message('max_length', 'This %s must have at least %s characters');

           if($this->form_validation->run() == FALSE)
           {
              // failed validation? return to submit form page
              $this->load->view('profile_view');

              // quit here
              return false;
           }
           else
           {
              if($_FILES['avatar']['size'] != 0)
              {
                 $id = $this->ion_auth->get_user_id('id');
                 $config['upload_path']   = './assets/images/avatars/'; 
                 $config['allowed_types'] = 'gif|jpg|jpeg|png'; 
                 $config['file_name']     = 'avatar_'.substr(md5(rand()),0,7);
                 $config['overwrite']     = true; 
                 $config['max_size']  = 10400; 

                 $this->load->library('upload', $config);
                 $this->upload->initialize($config);            
              }
           }

           if ( ! $this->upload->do_upload('avatar'))
           {
              // no file uploaded or failed upload
              $error = array('error' => $this->upload->display_errors());
              $this->load->view('profile_view', $error);
           }
           else
           {
              // success
              $avatar = $this->upload->data('full_path');
              $website = $this->input->post('website');
              $password = $this->input->post('password');

              // a model that deals with your image data (you have to create this)
              $this->Profile->updateProfile($id, $website, $password, $avatar);
           }                 
      }

   }
}

===========================================================================  

function do_upload() //solid code block - 2nd attempt
{
  if($this->ion_auth->logged_in())
  {
     // validate the POST data
     $this->form_validation->set_rules('website', 'Website', 'trim');
     $this->form_validation->set_rules('password', 'Password', 'trim|min_length[4]|max_length[32]');

     $this->form_validation->set_message('min_length', 'This %s must have at least %s characters');
     $this->form_validation->set_message('max_length', 'This %s must have at least %s characters');

       if ($this->form_validation->run() == FALSE)
       {   
          // failed validation
          $this->load->view('profile_view');

          // quit here
          return false;
       }

       $config['upload_path']   = './assets/images/avatars/'; 
       $config['allowed_types'] = 'gif|jpg|jpeg|png'; 
       $config['file_name']     = 'avatar_'.substr(md5(rand()),0,7);
       $config['overwrite']     = true; 
       $config['max_size']  = 10400; 

       $this->load->library('upload', $config);
       $this->upload->initialize($config);

       if ( ! $this->upload->do_upload('avatar'))
       {
           // no file uploaded or failed upload
          $data['error'] = array('error' => $this->upload->display_errors());
          $this->load->view('profile_view', $data);
}
else
{
    // success
    $avatar = array('upload_data' => $this->upload->data());
    $website = $this->input->post('website');
    $password = $this->input->post('password');

    // a model that deals with your image data (you have to create this)
    $this->Profile->updateProfile($website, $password, $avatar['full_path']);

    $this->load->view('profile_view', $data);
}}}  

==========================================================================  

  // view
  echo form_open_multipart('update/do_upload');
  echo form_input('website', '');
  echo form_input('password', '');
  echo form_upload('avatar');
  echo form_close


   // controller
   function do_upload()
   {
  $config['upload_path'] = './uploads/';
  $config['allowed_types'] = 'gif|jpg|png';
  $config['max_size'] = '100';
  $config['max_width']  = '1024';
  $config['max_height']  = '768';

  $this->load->library('upload', $config);

  // validate the POST data
  $this->form_validation->set_rules('website', 'Website', 'trim|required');
  $this->form_validation->set_rules('password', 'Password', 'trim|required')

  if ($this->form_validation->run() == FALSE)
  {   
    // failed validation
    $this->load->view('profile_view');
    return false;
   }

   if ( ! $this->upload->do_upload('avatar'))
   {
    // no file uploaded or failed upload
    $error = array('error' => $this->upload->display_errors());
    $this->load->view('profile_view', $error);
   }
   else
   {
    // success
    $data = array('upload_data' => $this->upload->data());
    $website = $this->input->post('website');
    $password = $this->input->post('password');

    // a model that deals with your image data
    $this->your_upload_model->add($website, $password, $data["file_name"]);

    $this->load->view('upload_success', $data);
    }}  


您得到的图片...鉴于所有这些转录尝试都在Profiler输出中都传递了PostData,但最令人讨厌的是,但是我在指定的文件夹中没有头像,也没有从模型中更新db列。我可能只需要为这种精神错乱找一个合适的替代品,并彻底废除这条道路。这种体验实际上说明了我在GitHub和Sourceforge上看到的大多数“用户仪表板”脚本对于潜在成员而言并没有图像上传和数据插入的组合。我要再等几个小时,直到午夜,然后再冲洗一次。

从Crapper救出...实际上几乎在那里...
不用进行表单验证,直到我可以使最后一部分起作用为止。

function update()
{
    if ($this->ion_auth->logged_in() && $this->input->server('REQUEST_METHOD') == 'POST') 
    {
        $avatar = array();

        $this->upload->initialize(array(
           'upload_path' => 'assets/images/avatars/',
           'allowed_types' => 'gif|jpg|jpeg|png',
           'file_name' => $_FILES['avatar']['name'],
           'overwrite' => TRUE,
           'max_size' => 10400,
        ));

         if ($this->upload->do_upload('avatar'))
         {
             if($_FILES['avatar']['error'] == 0)
             {
                $id = $this->ion_auth->get_user_id('id'); 
                $avatar = 'assets/images/avatars/' . $this->upload->data('file_name');
                $website = $this->input->post('website');
                $password = $this->input->post('password');

                 $data = array(
                     'avatar' => $avatar,
                     'website' => $website,
                     'password' => $password               
                 );
                 $this->db->set('avatar', $avatar);
                 $this->db->set('website', $website);
                 $this->db->set('password', $password);
                 $this->db->where('id', $id);
                 $this->ion_auth->update('users', $data);
                 redirect('profile', 'refresh');

             }
         }
         else
             {
                 // no file uploaded or failed upload
                 $this->load->view('edit_profile_view');                   
             }
     }
 }  


我将头像上传到目标文件夹,并将路径信息插入数据库,但是图像不会显示在目标页面上。要使用上传的图片,我正在使用;

<?php
 $user->avatar = !empty($this->upload->data('avatar')) ? $this->upload->data('avatar') : 'default.jpg';
?>
<img height="300px" width="300px" class="avatar img-circle" src="<?php echo base_url().$user->avatar.$this->upload->data('file_name'); ?>">  


我什至没有得到损坏的图像符号,只是应该在图像的空白处。这是我与此过程有关的最后一个问题。我可以将头像重复上传到目标文件夹并插入路径信息(该信息将进入名为callback_image_upload的数据库中的一列);

db table view

在使用avatar作为目标元素ID ion_auth的同时尝试访问头像的时间非常长,由于这种情况我在$user->avatar文档中找不到任何内容,因为那里没有关于图像和个人资料页面的任何处理。即使尝试遵循Avenir的教程,也会让我完全迷失在内陆地区。当我站在刀口上时,我可能会用其他的眼睛,只是勉强地坚持着试图解决这个问题。我离解决方案只有一毫米的距离,周围都是漆黑的(大声笑!)。我可以得到一个线索...有人...任何人...吗?

文档带来更多乐趣...

即使Ion_Auth-https://codeigniter.com/user_guide/helpers/html_helper.html#img-上的文档确实让人大开眼界,但我仍然无法使用条件显示设备来显示化身(如果路径/文件条目位于HTML Helper列,或仅显示已经上传到目标文件夹路径的avatar文件。我正在尝试尽可能优雅地做到这一点(即使用最少的代码),但是它只能归结为两种方法:

  <?php
  // if the avatar has been uploaded then display it 
  if(isset($user->avatar))
  { 
  ?>
  <img src="<?php echo base_url().'assets/images/avatars/'.$user->avatar; ?>" class="avatar img-circle" alt="Profile Image" width="300px">
  <?php
  }
  else 
  { 
  ?>
   <img src="<?php echo base_url().'assets/images/avatars/default.jpg'; ?>" class="avatar img-circle" alt="Profile Image" width="300px">            
  <?php 
  } 
  ?>  


或者,直接从display default image if user have no photo codeigniter外推;

<?php
$user->avatar = !empty($this->upload->data('avatar')) ? $this->upload->data('avatar') : 'default.jpg';
?>
<img height="300px" width="300px" class="avatar img-circle" src="<?php echo base_url().'assets/images/avatars/'.$user->avatar; ?>">  


但是,我只会得到default.jpg文件,而不是已经成功加载到目标文件夹中且路径已成功插入default.jpg列中的相应用户头像。 :sigh:会漫漫长夜...

上次更新

感谢@DFriend对您先前讨论的问题提供的有条理的反馈。我遇到的困难更多与如何将avatar用作辅助安全保护区有关。您所传授的Ion Auth想法与我必须采取的将某些不同的表结果带入相应的控制器视图页面的default.jpg体操相似。

//Controller
$data['resultset1'] = $this->model1->getAll($config['per_page'], $this->uri->segment(3));

//View
echo '<div class="scroll" style="width:100%;height:450px;">';
if (!empty($resultset1) && isset($resultset1) && count($resultset1) > 0)
{ 
   foreach ($resultset1 as $data)
   {
  echo '<h4><a title="Click Here For Content" href="'?><?php echo base_url().'articlelist/view/'.$data['article_id'].'">'. htmlspecialchars($data['title']). '</a><br>Category:&nbsp;'.htmlspecialchars($data['category']).'<br>Publisher:&nbsp;'.htmlspecialchars($data['username']).'<br>Published:&nbsp;'.$data['date'].'</h4><hr>';
   } 
 } 
 else
 { 
    echo '<p><font face="arial black" size="5" color="#0000CC">No Articles.</font></p>';
 }
 echo '</div>';


再次非常感谢@DFriend,但是我可能会搁置这种方法以便以后进行重新检查,因为我主要关心的是将应用程序投放市场,因为其他所有气瓶都经过无情地测试,直到最近2个天。我真的确定我会跳过一些可以帮助我在这个问题范围内实现既定目标的事情。令人不安的是,但我需要对此稍作休息,以便我能以新的眼光审视它并解决这个问题。这绝对还没有结束(大声笑!)...我现在只是喝醉了。也感谢所有对此问题的关注。

最佳答案

该答案假定不需要头像。因此,我没有使用字段验证回调。

控制者

function update() //"action" method from submission form 
{
    if($this->input->server('REQUEST_METHOD') === 'POST')
    {
        //no rules on the next one so what's the point?         
        //$this->form_validation->set_rules('website', 'Website');
        $this->form_validation->set_rules('password', 'Password', 'trim|min_length[4]|max_length[32]');

        $this->form_validation->set_message('min_length', 'This %s must have at least %s characters');
        $this->form_validation->set_message('max_length', 'This %s must have at least %s characters');

        if($this->form_validation->run() == TRUE)
        {
            $id = $this->ion_auth->get_user_id('id'); //$id will be NULL if not logged in   

            //Get the info from the form
            $website = $this->input->post('website');
            $password = $this->input->post('password');

            $is_avatar = $this->image_upload();
            if(is_string($is_avatar))
            {
                $this->load->view('profile_view', ['error' => $is_avatar]);
            }
            elseif($is_avatar === TRUE)
            {
                // to get image file name from upload script to be stored in the database
                $avatar = $this->upload->data('file_name');

                //use the next line if you want the full path instead of just the name
                //$avatar = $this->upload->data('full_path');
            }
            else
            {
                $avatar = NULL;
            }

            $this->load->model('profile_model');
            $this->profile_model->updateProfile($id, $avatar, $website, $password);
        }
        else //validation failed
        {
            //if you do this you loose the form_validation errors
            redirect('profile', 'refresh');
            //what you maybe want instead is something like
            //$this->load->view('profile_view'); //if that is where the form you just processed is
        }
    }
    //Not a POST call - go to profile page
    redirect('profile', 'refresh');
}

/**
 * Does the file upload
 * Returns NULL, boolean or string 
 *    NULL if no file posted, 
 *    TRUE if upload worked, 
 *    string if error
 */
function image_upload() //callback for previous update function
{
    if($_FILES['avatar']['size'] === 0)
    {
        return NULL;
    }
    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'gif|jpg|jpeg|png';
    $config['file_name'] = 'avatar_'.substr(md5(rand()), 0, 7);
    $config['overwrite'] = true; //will never happen because of previous setting
    $config['max_size'] = 10400;

    $this->load->library('upload', $config);
    //you already initializd the library by passing $config in the previous line
    //$this->upload->initialize($config);

    $is_uploaded = $this->upload->do_upload('avatar');

    if(!$is_uploaded)
    {
        return $this->upload->display_errors();
    }

    return TRUE;
}


模型

通过查找$id回答插入或更新问题。如果未设置,则我们有一个新用户insert。如果设置了$id,则该用户存在,请执行update

//function to update user_profile    
function updateProfile($id, $avatar = NULL, $website = NULL, $password = NULL)
{
    if(isset($avatar))
    {
        $this->db->set('avatar', $avatar);
    }

    if(isset($website))
    {
        $this->db->set('website', $website);
    }

    if(isset($password))
    {
        $this->db->set('password', $password);
    }

    //$id will  be set if logged in. 
    if(isset($id))
    {
        return $this->db
                        ->where('id', $id)
                        ->update('users');
    }

    //Not logged in - add new user with insert
    //make an insert and if it returns true the return the new id of inserted record, else return false
    return $this->db->insert('users') ? $this->db->insert_id() : FALSE;
    //but what you probably really want to do is create a new user via ion_auth. Right?
}


响应头像或默认图片问题

如果我错了,请纠正我,但是$user->avataravatar表中具有users字段的值-对吗?如果这是正确的,那么在我看来,最简单的事情总是将某些内容存储在avatar字段中。

例如,第一次创建用户时,您存储他们提供的头像,如果不提供,则存储default.jpg。与配置文件更新类似-如果他们提供图像,则将其存储,否则将字段保留为默认值-default.jpg。使用这种方法,您知道表格将始终提供一些要显示的内容。因此,不需要其他逻辑。

以下是几个实际显示图像供您考虑的图像。但是首先,对您的问题中的代码发表评论。您显示此行代码。

<img src="<?php echo base_url().'assets/images/avatars/'.$user->avatar; ?>" class="avatar img-circle" alt="Profile Image" width="300px">


如果$user->avatar包含字符串“ assets / images / avatars / LeeDavis.jpg”,则您提供了两次路径,结果HTML将遵循这些行。

<img src="http://example.com/assets/images/avatars/assets/images/avatars/LeeDavis.jpg" ...and the rest... />


如您所见,/assets/images/avatarssrc字符串中两次。

好。继续实际显示图像。

假设您将$user对象传递给视图

 <img src="<?php echo base_url($user->avatar); ?>" class="avatar img-circle" alt="Profile Image" width="300px">


或者,如果使用HTML Helper,则可以在显示配置文件的控制器中执行此操作

//assuming that $data is being used to send pass variables to the view
$data['avatar_properties'] = array(
        'src'   => $user->avatar,
        'alt'   => "Profile Image",
        'class' => "avatar img-circle",
        'width' => '300',
);


然后在查看文件

<?php echo img($avatar_properties); />

关于php - Codeigniter 3.1.0文件上传有效,但图像“full_path”信息从未插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40224092/

相关文章:

php - 使用表单的搜索/过滤器分页

php - 无法将语句插入数据库

php - 随机选择动态复选框

php - 仅当数据存在于另一个 PHP 中时如何在表中插入数据

php - 无法合并表以获得所需的结果

mysql - 数据建模 : hierarchy of geographic locations

php - PHP 中 $variable->something 的故事是什么?

mysql - 三表Natural Join怎么做?

jquery - 在 CodeIgniter 应用程序中,您将 jquery javascript 代码放在哪里?

codeigniter - 为什么 Codeigniter 有一个只有构造函数和 get 的 Model 类?