submitting multiple files thru a form with CodeIgniter - php

I have the following:
<form id="set" method="post" action="<?php echo $base_url; ?>schedule" enctype="multipart/form-data">
<?php
for($i=0;$i<10;$i++) {
?>
<input type="file" name="file[]" class="selective_file">
<input type="checkbox" name="name[]" value="<?php echo $name[$i]; ?>" style="display:none;"/>
<?php
}
?>
<input type="submit" value="Post />
</form>
The client has to submit 10 photos and once they click the button and the form is submitted, the schedule controller gets the files as follows
public function index() {
$files = $this->input->post('files');
$name = $this->input->post('name');
print_r($files);
print_r($name);
}
I know that for uploading files in CI, the following has always worked for me
if(!$this->upload->do_upload('file')) {
$error = array('error' => $this->upload->display_errors());
print_r($error);
} else {
$pic = $this->upload->data();
}
How do I identify the files with CI so that it can be uploaded successfully while looping thru the array of files with the correct corresponding name from the checkbox field?

Related

how can send array in html forms to php

I want to send uploaded files address from html to php with array and then moved the uploaded files to images from tmp and checked their size
<form method="post" enctype="multipart/form-data" name="form1" id="form1" action="upload.php">
<p>
<input type="file" name="Img[]" />
</p>
<p>
<input type="file" name="Img[]" />
</p>
<p>
<input type="file" name="Img[]" />
</p>
<p>
<input type="submit" name="submit" id="submit" value="Submit">
</p>
</form>
<?php
$name=rand('0123456789',5).'jpg';
$files=array($_POST['Img[]']);
echo '<pre>';
print_r($files);
if($_FILES['$files[0]']['type'] == 'image/pjpeg'){
move_uploaded_file($_FILES[$files[]]['tmp_name'],'image/'.$name);
echo "success";
}
?>
I want to upload files with form
Input file elements never store in the $_POST array. You have to loop through the $_FILES array to get the file elements
if(isset($_POST['submit']))
{
for ($i=0; $i < count($_FILES['Img']['tmp_name']) ; $i++) {
$name=rand('0123456789',5);
if($_FILES['Img']['type'][$i] == 'image/jpeg')
{
move_uploaded_file($_FILES['Img']['tmp_name'][$i],'image/'.$name . '.jpg');
}
echo "success";
}
}
In this solution you can increase the number of input files with the same name as Img
Try this
<?php
if(isset($_POST['submit']))
{
foreach($_FILES['Img'] as $Img) {
$name=rand('0123456789',5);
if($Img['type'] == 'image/jpeg')
{
move_uploaded_file($Img['tmp_name'],'image/'.$name . '.jpg');
}
echo "success";
}
}
?>

PHP Form - File Upload Field for Signup

I have created a PHP signup form for visitors to fill and submit that asks for their basic information.
I am trying to accomplish the following two tasks;
Add Image/File Upload Field
Redirect them to a confirmation page
I have been unable to make it work. Below is what I have.
My Code
HTML Form
<form name="form1" method="post" action="signup.php">
Username: <input type="text" name="user">
<br>Email: <input type="text" name="mail">
<br>Experience: <select name="exp"> <option value="beginner">Beginner</option>
<option value="intermediate">Intermediate</option> <option value="advanced">Advanced</option>
</select><br> <input type="submit" name="Submit" value="Sign Up">
</form>
Signup.php
<?php
$username = $_POST['user'];
$email = $_POST['mail'];
$experience = $_POST['exp'];
//the data
$data = "$username | $email | $experience\n";
//open the file and choose the mode
$fh = fopen("users.txt", "a");
fwrite($fh, $data);
//close the file
fclose($fh);
print "User Submitted";
?>
It seems like you lack an input field in your HTML to begin with.
here's an example of a form for uploading files.
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
Once you've done that you're not quite there yet because your file is stored in a temporary folder, you will need to move the file to your uploads folder like so:
$target_file = "uploads/" . basename ($_FILES["fileToUpload"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)
I hope this helps!
Ta add an upload you need to add enctype="multipart/form-data" to your form tag,then add the upload field. For the Email field change the type to HTML5 type="email", this will do a little validaation check that it is in the correct format. At the bottom of the php file add a location header if all went well. You could put it all in one file with an if statement at the top.You should also sanitize your inputs
this is a upload file script which will loop through all the data of a file and insert
if(isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['filename']['name']. "uploaded successfully." . "</h1>";
}
$csv_file=$_FILES['filename']['tmp_name'];
$type=$_FILES['filename']['type'];
$handle = fopen($csv_file, "r");
$i=0;
while (($data = fgetcsv($handle)) !== FALSE) {
if($i>0) {
$import="insert into `table_name`(col1,col2,col3,col4,col5,col6,col7)values('".addslashes($data[0])."','".addslashes($data[1])."','".addslashes($data[2])."','".addslashes($data[3])."','".addslashes($data[4])."','$data[5]','$data[6]')";
mysql_query($import) or die(mysql_error());
}
$i=1;
}
echo "Success";
echo "<br>";
echo $_FILES['filename']['type'];
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" name="" id="">
Choose File:<br>
<input name="filename" type="file" />
<input type="submit" name="submit" value="submit" />
</form>

Rename an image during the uploading in php

Am trying to rename an image during upload i know i am met to put the function rand() and end() but i just do not know where to put it here is my code below
php / html section
if (isset($_POST['uploadimage'])) {
list($typed) = $_FILES['images']['type'];
if(!ereg("image",$typed)){
echo "<div class='msg1'>File is not an image or field is empty</div>";
}else{
$pixsname = $_FILES['images']['name'];
while(list($key,$value) = each($_FILES['images']['name'])){
if(!empty($value)) {
$pixsname = $value;
$add = "./img/venues/$pixsname";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
}
$image = new Image();
$image->load("$add");
$image->resize(652,300);
$image->save("$add");
}
echo "<div class='msg1'>Image profile has been updated</div>";
}
}
form method="post" enctype="multipart/form-data" id="loginform" >
<input type="hidden" name="MAX_FILE_SIZE" value="200000000">
<input type="file" name="images[]" id="fileField" class="field_ss"/>
<?php echo $pix; ?>
<input type="submit" name="uploadimage" value="Upload Image"/>
</form>
Replace
$pixsname = $value;
with
$pixsname = 'The_New_Name_Of_Your_Picture';

Multiple file upload herror

I found a nice tutorial on YouTube by Anthoniraj Amalanathan. On the video tutorial, it works fine for hem but when I try to replicate it, I get an error. Here is the code:
<form action="<?php $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" method="post">
<input type="file" name="upload[]">
<input type="file" name="upload[]">
<input type="submit" name="send" value="Send Now">
</form>
<?php
if(isset($_FILES['upload'])=== true)
{
$files = $_FILES['upload'];
for($x=0;$x<count($files['name']);$x++)
{
$name=$files['name'][$x];
$tmp_name = $file['tmp_name'][$x];
move_uploaded_file($files,'test/'.$name);
echo 'Upload OK';
}
}
?>
The message states that the error is on line 12 ($tmp_name = $file['tmp_name'][$x];) but I don't seem to figure out why.
Can some one help here?
Try this, I tested it and it works for me.
<form action="<?php $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" method="post">
<input type="file" name="upload[]">
<input type="file" name="upload[]">
<input type="submit" name="send" value="Send Now">
</form>
<?php
if(isset($_FILES['upload'])=== true) {
$files = $_FILES['upload'];
for($x=0;$x<count($files['name']);$x++) {
$name = $files['name'][$x];
$tmp_name = $file['tmp_name'][$x];
move_uploaded_file($files['tmp_name'][$x],'test/'.$name);
echo 'Upload OK';
}
}
?>
The error I got came from using an array as the temp. file location. By changing it to $files['tmp_name'][$x], it worked.
Old: move_uploaded_file($files,'test/'.$name);
New: move_uploaded_file($files['tmp_name'][$x],'test/'.$name);
Its just a typo. $file is never declared, it should be $files.
Here:
$tmp_name = $file['tmp_name'][$x];
// ^ missing s
Also here:
move_uploaded_file($files,'test/'.$name);
// ^^^^^^ shouldn't this be $tmp_name?
Try like this :
<?php
if(is_uploaded_file($_FILES['upload']['tmp_name'])){
foreach($_FILES['upload']['name'] as $x=>$name) {
$name = basename($_FILES['upload']['name'][$x});
$folder = 'test/';
$full_path = $folder.$name ;
if(move_uploaded_file($_FILES['upload']['tmp_name'][$x], $full_path)) {
echo 'Upload OK';
} else {
echo 'Upload Failed';
}
}
}else{
echo 'Upload Not Received';
}
?>

How to save image in folder using CodeIgniter?

I am new to CodeIgniter. I want to know how to save an image in a folder. But I wrote the code like image name was stored in a table. But I want to store the image in a folder and retrieve image from the folder. Here I am using the code to store image name in table:
In Controller:
public function product()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('productname','Product Code','trim|required');
$this->form_validation->set_rules('productcode','Product Code','trim|required');
$this->form_validation->set_rules('productprice','Product Price','trim|required');
$this->form_validation->set_rules('quantity','Quantity','trim|required');
$this->form_validation->set_rules('uploadimage','Upload Image','trim_rquired');
if($this->form_validation->run()==FALSE)
{
$this->index();
}else
{
$data['query']=$this->main_model->product_db();
$this->load->view('query_view',$data);
}
}
In Model:
public function product_db()
{
$data=array(
'productname'=>$this->input->post('productname'),
'productcode'=>$this->input->post('productcode'),
'productprice'=>$this->input->post('productprice'),
'quantity'=>$this->input->post('quantity'),
'image'=>$this->input->post('uploadimage')
);
$query=$this->db->get("product");
if($query->num_rows())
{
$this->db->insert('product',$data);
$query=$this->db->get("product");
$this->session->set_userdata($data);
return $query->result();
}
return false;
}
In View:(form page)
<?php echo validation_errors('<p class="error">'); ?>
<?php echo form_open("main/product"); ?>
<p>
<label for="product_name">Product Name:</label>
<input type="text" id="productname" name="productname" value="<?php echo set_value('product_name'); ?>" />
</p>
<p>
<label for="ProductCode">Product Code</label>
<input type="text" id="productcode" name="productcode" value="<?php echo set_value('productcode'); ?>" />
</p>
<p>
<label for="productprice">Product Price:</label>
<input type="text" id="productprice" name="productprice" value="<?php echo set_value('productprice'); ?>" />
</p>
<p>
<label for="Quantity">Quantity:</label>
<select name="quantity" id="quantity" value="<?php echo set_value('quantity'); ?>" /><option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</p>
<p>
<label for="Uploadimage">Upload Image:</label>
<input type="file" name="uploadimage" id="uploadimage" value="<?php echo set_value('quantity'); ?>" />
</p>
<p>
<input type="submit" class="greenButton" value="submit" />
</p>
<?php echo form_close();
?>
In View(query_view Page):
<?php
echo "<table border='2'>
<tr>
<th>productid</th><th>productname</th><th>productcode</th><th>productprice</th>
<th>quantity</th><th>image</th>
</tr>";
foreach($query as $r)
{
echo "<tr>";
echo "<td>".$r->productid."</td>"."<td>".$r->productname."</td>".
<td>".$r>productcode."</td>"."<td>".$r->productprice."</td>"."<td>"
.$r->quantity."</td>"." <td>".$r->image."</td>";
echo "</tr>";
}
echo "</table>";
echo "<br>";
?>
This is just a sample code of uploading an image:
<?php
$configUpload['upload_path'] = './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'] = true; #encrypt name of the uploaded file
$this->load->library('upload', $configUpload); #init the upload class
if(!$this->upload->do_upload('uploadimage')){
$uploadedDetails = $this->upload->display_errors();
}else{
$uploadedDetails = $this->upload->data();
}
print_r($uploadedDetails);die;
?>
you are seeking this kind of code
$config['upload_path'] = './files'; //core folder (if you like upload to application folder use APPPATH)
$config['allowed_types'] = 'gif|jpg|png'; //allowed MIME types
$config['encrypt_name'] = TRUE; //creates uniuque filename this is mainly for security reason
$this->load->library('upload', $config);
if (!$this->upload->do_upload('picture_upload')) { //picture_upload is upload field name set in HTML eg. name="upload_field"
$error = array('error' => $this->upload->display_errors());
}else{
//print_r($this->upload->data()); // this is array of uploaded file consist of filename, filepath etc. print it out
$this->upload->data()['file_name']; // this is how you get for example "file name" of file
}
Please follow this guide http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html it has everything in it. If you need help with logic its pretty simple
form -> upload field -> button -> form sent -> check rules if file is OK -> upload file -> save data (filename, filepath...) in table.

Categories