I am using the code below to handle image upload. Every thing is going fine. I have allowed the option to upload two images, one will be the logo and another the screenshot.
Now when I am providing the option to edit the uploads, say choose new files to upload and replace the old ones, I am having this problem.
In my images[] array, I will get the image names one by one with the help of loop. However when the user wants to change the second image(screenshot) and selects nothing in the logo field, only screenshot should be changed.
But in the images[] array, the first element will be the first from the uploads. If i select both the images it is all right, I will get logo.jpg in images[0] and screenshot.jpg in images[1]. But when I select only the second image, i will get screenshot.jpg in images[0]. However, the first element of the array should be blank and the second element of the array should have the data of the second image upload option so the the changes to take into effect. How can i acheive that?
$config['upload_path'] = '../uploads/';
$config['allowed_types'] = '*';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$this->load->library('upload', $config);
$image = array();
foreach ($_FILES as $key => $value) {
if (!empty($value['tmp_name'])) {
if ( ! $this->upload->do_upload($key)) {
$error = array('error' => $this->upload->display_errors());
//failed display the errors
} else {
//success
$data = $this->upload->data();
$image[]= $data['file_name'];
}
}
}
Remember, You must to initialize the upload library with each upload.
$this->load->library('upload');
$this->upload->initialize($config);
User guide: http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html
Edit:
You can check the $_FILES array and check if there are the name of the screenshot input and the logo input, if they aren´t, you can create the array you need
I´ve found this:
A simpler way to have create that data structure is to name your HTML file inputs different names. >If you want to upload multiple files, use:
<input type=file name=file1>
<input type=file name=file2>
<input type=file name=file3>
Each field name will be a key in the $_FILES array.
http://www.php.net/manual/es/features.file-upload.multiple.php#53933
Related
I have a drop down box with multiple options, and based on what value is selected I want it to dynamically update the folder path of the move_uploaded_file() function.
When I echo out the same thing that is in the if($file_name) block it shows the correct path each time I pick from the drop down, but when I actually submit the image upload the variable is basically empty and uploads the image to ../www/html//$file_name
Any help on to why the variable is basically empty on submit would be greatly appreciated. I can share all of the code if needed, but all of the rest of it is working fine, even the echo statement is pulling in the variable $selected just fine, but just not in the if($file_name) block.
$selected = $_POST['countries'];
if(isset($_POST['upload_img'])){
$file_name = $_FILES['image']['name'];
$file_type = $_FILES['image']['type'];
$file_size = $_FILES['image']['size'];
$file_tmp_name = $_FILES['image']['tmp_name'];
if($file_name) {
move_uploaded_file($file_tmp_name, "../www/html/$selected/$file_name");
}
}
echo "../www/html/$selected/$file_name";
I've wrote a script where the user can select to upload more than one image to a form. I'm preventing the user from submitting the form until all of the file fields that have been added actually contain files for upload.
EG:
The user has three file fields to fill in, therefore three files must be ready for submission to the database.
I'm using the same id on each of the file upload fields. When I use print_r($_FILES); it returns me an array. If I browse for a file in the first file field, and leave another two blank, it will state that the array object for [1] and [2] are blank, however [0] will obviously have a name, type, size etc as it exists.
How would I go about making sure that all of the file fields are actually filled in using PHP?
Thanks in advance, Rich
Here are my efforts so far:
$imgName1 = $_FILES['upload1']['name'];
$imgTmp1 = $_FILES['upload1']['tmp_name'];
$imgType1 = $_FILES['upload1']['type'];
$imgSize1 = $_FILES['upload1']['size'];
print_r($_FILES);
if(!$imgTmp1){
echo "<span class='error'>You need to include at least one image with this article.</span>";
exit();
} else {
$fileCount=($_FILES['upload1']['name']); // My attempt to count that the file fields are all filled in
$cnt = $_POST['cnt']; // This is the number of file fields that currently exist
echo "<br/>";
echo count($fileCount);
if($cnt != $fileCount){
echo "<span class='error'>You have not uploaded all of your files.</span>";
exit();
}
// etc etc
You have incorrect upload checking. The presence something in $_FILES doesn't mean that file uploaded. A failed upload will STILL create $_FILES entries.
You need to check for BOTH the presence of the $_FILES entry, and its error parameter:
if (isset($_FILES['upload1'])) {
if ($_FILES['upload']['error'] === UPLOAD_ERR_OK) {
... file was successfully uploaded
} else {
... upload failed
}
} else {
... no file upload was even attempted
}
I am making an edit form where the user can edit item details and change the item image. The item details get updated in the database fine but the item image does now change. Below is my code...
if($_POST['item_img']){
$old_img = "img/items/$item_id.jpg";
$default_img = "img/items/default.jpg";
if (file_exists($old_img)) {
unlink($old_img);
$filename = $item_id.'.jpg';
move_uploaded_file ($_FILES["item_img"]["tmp_name"],"img/items/".$filename)
}elseif(file_exists($default_img)) {
unlink($default_img);
$filename = $item_id.'.jpg';
move_uploaded_file ($_FILES["item_img"]["tmp_name"], "img/items/".$filename);
}
}
I think it is my if($_POST['item_img']) statement that is causing this issue. What could I change the loop to.
The first nested if statement checks if there is an image attached, and the second if statement checks if a default image is attached. In both cases it deletes the old image and sets a new image with the "item_id" as its name.
Below is the code for my for upload field:
<form class="stock" method="post" enctype="multipart/form-data" action="">'
<input type="file" name="item_img">
</form>
Change it
$_POST['item_img']
To
$_FILES["item_img"]["tmp_name"]
I am trying to create a cross platform application and I would like to save images from different devices in the database using Codeigiter. I am able to select the images form the device but I am confused and stocked on how to save images and retrieving them from the database.
Controller
function addstatesoothing() {
// write user data into the user database
$config['upload_path'] = './';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000000';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$config['encrypt_name'] = FALSE;
$this->load->library('upload', $config);
$image_path = $this->upload->data('soothing-img');
$data = array(
'soothing-img' => $image_path[full_path],
'soothing-title' => $this->input->post('soothing-title'),
);
$this->favourite_db->addstatesoothing($data);
$this->load->view('soothing');
}
Model
function addstatesoothing($data) {
$this->load->database();
$this->db->insert('soothing', $data);
return $data;
}
View
<form method="post" action="addstatesoothing">
<!-- <button data-theme="d" onclick="capturePhoto();">Capture Photo</button> -->
<a data-theme="d" onclick="getPhoto(pictureSource.PHOTOLIBRARY);">Click to Add Pictures</a>
<img style="width:100%;" id="largeImage" src="" name="soothing-img"/> <br>
<input type="text" name="soothing-title" id="Climbed a Mountain" value="" placeholder="Climbed a Mountain"/>
<button data-theme="a">Save Memory</button>
</form>
To save image in database:
1 - Your image field on database should be BLOB type.
2 - Get file content from your image:
$image = file_get_contents($_FILES['image']['tmp_name']);
3 - Save it in your BLOB type field on database
mysql_query("insert into images (image) values ('$image') ");
I don't know if you use another approach to save data in database, your code is a bit different , but that's the way, right? In the end it'll be a row inserted in database, If you have any doubt, comment here, but at this point is all easy, ham? now let's go to retriving images
First of all, storing images content in database is a real mistake, but that isn't the question right? So I'm not an expert in this approach, but is how I would:
Create an another page like image.php, receiving some id or image name by parameter
image.php:
<?php
$id = $_GET['id'];
$query = "SELECT image FROM images WHERE `id`=$id";
$result = mysql_query($query);
header("Content-type: image/jpeg"); //if is another format like .png change here
while($row = mysql_fetch_assoc($result))
{
echo $row['image'];
}
?>
Nice, you have a nice *.php file that response an image just like any *.jpg file, so now call it in your HTML
SomePage.html:
<img src="image.php?id=12345" />
Ok, all done,
but why I told that saving image content is bad?: SO fellas are awesome, we have amazing material to explain why saving images in database is BAD! You could check it, here's:
Storing Images in DB - Yea or Nay?
Store images in database or on file system
The first thing in this question is your form is not able to upload image because your not using multipart form data
you can try like this
<form enctype="multipart/form-data"></form>
I have recently started working on zend framework. I want to upload a profile picture and rename & re-size it. Am using the code below. with this am able to upload but am not able to rename and am not getting a way to re-size the uploaded file.
if($this->getRequest()->isPost())
{
if(!$objProfilePictureForm->isValid($_POST))
{
//return $this->render('add');
}
if(!$objProfilePictureForm->profile_pic->receive())
{
$this->view->message = '<div class="popup-warning">Errors Receiving File.</div>';
}
if($objProfilePictureForm->profile_pic->isUploaded())
{
$values = $objProfilePictureForm->getValues();
$source = $objProfilePictureForm->profile_pic->getFileName();
//to re-name the image, all you need to do is save it with a new name, instead of the name they uploaded it with. Normally, I use the primary key of the database row where I'm storing the name of the image. For example, if it's an image of Person 1, I call it 1.jpg. The important thing is that you make sure the image name will be unique in whatever directory you save it to.
$new_image_name = 'new';
//save image to database and filesystem here
$image_saved = move_uploaded_file($source, '../uploads/thumb'.$new_image_name);
if($image_saved)
{
$this->view->image = '<img src="../uploads/'.$new_image_name.'" />';
$objProfilePictureForm->reset();//only do this if it saved ok and you want to re-display the fresh empty form
}
}
}
To Rename a file while uploading, you will have to add the "Rename-Filter" to your file-form-element. The class is called Zend_Filter_File_Rename.
// Create the form
$form = new Zend_Form();
// Create an configure the file-element
$file = new Zend_Form_Element_File('file');
$file->setDestination('my/prefered/path/to/the/file') // This is the path where you want to store the uploaded files.
$file->addFilter('Rename', array('target' => 'my_new_filename.jpg')); // This is for the filename
$form->addElement($file);
// Submit-Button
$form->addElement(new Zend_Form_Element_Submit('save');
// Process postdata
if($this->_request->isPost())
{
// Get the file and store it within the specified destination with the specified name.
$file->receive();
}
To make the filename dynamically you may name it with a timestamp or something. You may also apply the Rename-filter within your post-data-processing before the call of $file->receive(). This could be useful if you insert a row into a table and want to name the file with the id of the just inserted row.
Since you want to store a profile picture you could get the id of the user from your db and name the pic with that id.