How can I get the filename of the file uploaded in codeigniter. We get the values of the input fields as $this->input->post('name'), but how can i get the name of the file uploaded from the form??
public function create(){
//getting all the POST data in $data array
$data = array('title' => $this->input->post('title') ,
'content' => $this->input->post('content'),
'filename' => ?? HOW ??
);
}
1) make sure that you form is multipart. With helper its form_open_multipart()
2) use upload library for receiving the file
3) then with $this->upload->data() you get array with file info
Here is full how to and official documentation
public function create(){
//getting all the POST data in $data array.
$data = array('title' => $this->input->post('title') ,
'content' => $this->input->post('content'),
'filename' => $_FILES["file"]["name"]
);
}
Related
So, I am trying to store an image that is uploaded through a blog post to a specific folder with its original file name.
The image is saved to the correct file path already but it's saving it as a random string name. My code is below:
public function fields(Request $request)
{
return [
ID::make('id')->sortable(),
Text::make('URL ID', 'id')->hideFromIndex(),
Text::make('Title', 'title'),
select::make('Market Type', 'market_id')->options([
'church' => 'Church',
'school' => 'School',
'business' => 'Business',
'municipal' => 'Municipal'
]),
Trix::make('Body', 'text'),
Image::make('Image', 'main_image')
->disk('blog')
->storeOriginalName('main_image')
->maxWidth(200)
->prunable(),
];
}
->storeOriginalName() is not about name of the saved file, but name of file that browser gets when clicking 'download' in the image field in detail page
Changing file names most simply can be done with ->store() method, something like this:
Image::make('Image', 'main_image')
->store(function (Request $request, $model) {
$filename = $request->main_image->getClientOriginalName();
$request->main_image->storeAs('/', $filename, 'blog');
return [
'main_image' => '/' . $filename,
'main_image_name' => $request->main_image->getClientOriginalName()
];
})
->maxWidth(200)
->storeOriginalName('main_image_name')
->prunable(),
I need to store the image as blob type in database using codeigniter. I don't want to upload the image in a folder. I just wanted to store the image in db as blob.
I have this in my model
public function insert_user()
{
$get_image = $this->input->post(file_get_contents($_FILES['imgProfile']['tmp_name'])); //imgProfile is the name of the image tag
$insert_values = array(
'first_name' => $this->input->post('FirstName'),
'last_name' => $this->input->post('LastName'),
'profile_image' => $this->$get_image
);
$insert_qry = $this->db->insert('user', $insert_values);
}
My controller contains
public function new_user()
{
$this->user_model->insert_user(); //user_model is the model name
}
Error:
Fatal error: Cannot access empty property in C:\xampp\htdocs\CI\system\core\Model.php on line 52
Thanks.
Within your code you have typo related to variable. It seems you might be calling your variable as function.
Even though if you want to access the value from a function then it should be written as $this->get_image() and for variables $this->get_image not as $this->$get_image
public function insert_user()
{
$get_image = $this->input->post(file_get_contents($_FILES['imgProfile']['tmp_name'])); //imgProfile is the name of the image tag
$insert_values = array(
'first_name' => $this->input->post('FirstName'),
'last_name' => $this->input->post('LastName'),
'profile_image' => $get_image //its a variable
);
$insert_qry = $this->db->insert('user', $insert_values);
}
I'm developing a PHP application where I have a form in which the user should upload a text file and an other page works with this data. I'm also creating controller tests with CakePHP and PHPUnit. My question is, how can I make the test automatically upload a file for the tests of this action?
Thanks in advance.
update 1:
The question in more details: Basically I have a 'submit' action which has the form in its view which submits the parameters (and the uploaded file) to the 'curl' action. Here this curl action processes the uploaded text file and this is actually what I'd like to test. But to test this, I should have an uploaded file with its content, so a more specific question: how could I mock this uploaded file to 'submit' it to my curl controller?
Code snippet for the View:
...
echo '<fieldset><table>';
echo $this->Form->create('Job', array('type' => 'post','action' => 'curl', 'enctype' => 'multipart/form-data'));
echo $this->Form->input('user.name', array('type' => 'hidden', 'value' => $this->User->getCode1(),'name' => 'user.name'));
echo $this->Form->input('class', array('type' => 'hidden', 'value' => $this->Hadoop->getClass(), 'name' => 'class'));
...
update 2:
The test I've already written:
public function testCurl() {
$data = array(
'user_name' => ...,
'release' => ...,
'analysis_period_start' => ...,
'uploaded_file' => ???
);
$Jobs = $this->generate('Jobs', array('components' => array('Session')));
$Jobs->Session->expects($this->any())->method('setFlash');
$this->testAction('/jobs/curl', array('data' => $data, 'method' => 'post'));
}
So basically I'm trying to test my curl action with a POST method with the data provided in the $data variable. But I don't know how to mock/imitate an uploaded file into that array.
update 3:
The relevant cod snippet from my controller's given action:
public function curl() {
/* This action accepts only POST request */
if (!$this->isPOSTRequest())
return $this->redirect(array('controller' => 'jobs', 'action' => 'submit'));
/* Create a new entry in the database and get its ID */
$id = $this->createNewEntryInTheDatabase();
/* Inserts the new patterns into the DB and looks up the already existing
** patterns in the DB. Returns an array with the IDs of the submitted patterns */
$patternIds = $this->lookupPatternIDsAndInsertNewPatterns($_FILES['patterns']);
$curl = $this->initCURL();
...
$this->closeCURL($curl);
return $this->redirect(array('controller' => 'jobs', 'action' => 'submit'));
}
...
private function lookupPatternIDsAndInsertNewPatterns($patternsFile) {
$patternIDs = null;
/* One element for each row */
$patternsArray = $this->convertUploadedCSVFileIntoArray(
$patternsFile, $this->CSV->getDelimiter(),
$this->CSV->getEnclosure(), $this->CSV->getEscape());
...
return $patternIDs;
}
/* Returns the patterns from the CSV file in an array */
private function convertUploadedCSVFileIntoArray(
$patternsFile, $delimiter, $enclosure, $escape) {
$patternsArray = file($patternsFile['tmp_name']);
$patterns = null;
foreach ($patternsArray as $pattern)
$patterns[] = str_getcsv(
$pattern,
$delimiter,
$enclosure,
$escape);
return $patterns;
}
I am using http://milesj.me/code/cakephp/uploader#configuration to upload images. I got it to work fine (in terms of uploading images) but I can't get it to save title/description in my db.
so I have Image.php model that has the following code
<?php
class Image extends AppModel {
var $name = 'Image';
public $actsAs = array('Uploader.Attachment', 'Uploader.FileValidation');
public $validate = array(
'title' => array( 'rule' => 'notEmpty')
);
}
In my view I have bunch of fields such as
echo $this->Form->input('title');
My ImagesController.php add function looks like this
function add($number_of_images = 1){
if (!empty($this->data)) {
var_export($this->data);
exit();
$count = 1;
foreach($this->data['Images'] as $entry){
$file_name = "file" . $count;
if ($data_s = $this->Uploader->upload($file_name)) {
$this->Image->saveAll($data_s);
}
$count++;
}
$this->Session->setFlash("Your image(s) has been saved");
$this->redirect(array('action'=>'index'));
}else{
// make sure 10 is max amount of images a user can upload
if($number_of_images <= 10 ){
$this->set('number_of_images', $number_of_images);
}else{
// set to default 1
$this->set('number_of_images', '1');
}
}
}
When I click save, the image gets uploaded but title/description doesnt get uploaded or validated. This is how my var_export($this->data) looks like
array ( 'selectImages' => '1', 'Images' => array ( 'title' => 'adsafdas', 'description' => 'asdfasd', 'tags' => '', 'file1' => array ( 'name' => '308462_926071922398_11704522_41424436_637322498_n.jpg', 'type' => 'image/jpeg', 'tmp_name' => '/tmp/php7tycbu', 'error' => 0, 'size' => 81638, ), ), )
How can I fix this?
According with the link, $this->Uploader->upload() returns only data of file uploaded. So, you need merge this array with the other fields of your form $this->data before saveAll.
However, if you need validate form data before upload the file, use $this->Image->validates($this->request->data).
below code return "File '' is not readable or does not exist" always:
$filters = array(
'*' => 'stringTrim'
);
$validators = array(
'image'=> array(
'allowEmpty' => TRUE,
new Zend_Validate_File_ImageSize(array('minheight'=>0,'minwidth'=>0,'maxheight'=>1024,'maxwidth'=>1024)),
)
);
$input = new Zend_Filter_Input($filters, $validators);
$input->setData(array_merge($data, $_FILES));
if (!$input->isValid()) {
$this->_errors = $input->getMessages();
}
The input name of your file input has to be image. Also, be sure your form has enctype="multipart/form-data". The format of $_FILES is explained here.
Aside from that I don't detect any code in Zend_Validate_File_ImageSize that can operate on $_FILES. I think you've got to pass the actual path to the file, e.g. 'image' => $_FILES['image']['tmp_name'] (in your $input->setData() call).