$judul = $_POST['judul'];
$idKategori = $_POST['kategori'];
$idPropinsi = $_POST['propinsi'];
$img = $_FILES['img']['name'];
$img_tmp = $_FILES['img']['tmp_name'];
$idUser = $_POST['user'];
$isi = $_POST['isi'];
$date = $_POST['date'];
if(empty($img)) {
$query = mysql_query("INSERT INTO `artikel`(`idArtikel`, `idKategori`, `idPropinsi`, `judul`, `idUser`, `isi`, `date`) VALUES ('','$idKategori','$idPropinsi','$judul','$idUser','$isi','$date')");
}else{
if(move_uploaded_file($img_tmp,"../../../img/".$img)) {
$query = mysql_query("INSERT INTO `artikel`(`idArtikel`, `idKategori`, `idPropinsi`, `judul`, `img`, `idUser`, `isi`, `date`) VALUES ('','$idKategori','$idPropinsi','$judul','$img','$idUser','$isi','$date')");
}else{
echo "Failed to upload image";
}
}
if($query) {
header("location:../../index.php?page=artikel");
}else{
echo "failed to update this post";
}
But the result is
move_uploaded_file(http://localhost/mvc/kuliner/assets/img/Green Nature Wallpapers 04.jpg): failed to open stream: HTTP wrapper does not support writeable connections
No!
Basically rewriting this code to work with Codeigniter is a lot more work than writing it from scratch using examples found in the CI documentation. Link provided in comment above (http://www.codeigniter.com/userguide2/libraries/file_uploading.html).
There are several reasons as both file upload, redirection, database handling, user output etcetera are done differently in CI using CI's methods and the MVC structure of programming.
This is how I do my uploads in CI (Using Dropzone).
Create Dropzone Controller
class Dropzone extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('url','html','form'));
}
public function upload() {
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$temp = $_FILES["file"]["name"];
$path_parts = pathinfo($temp);
$t = preg_replace('/\s+/', '', microtime());
$fileName = $path_parts['filename']. $t . '.' . $path_parts['extension'];
$targetPath = UPLOADPATH;
$targetFile = $targetPath . $fileName ;
echo $fileName;
move_uploaded_file($tempFile, $targetFile);
// if you want to save in db,where here
// with out model just for example
// $this->load->database(); // load database
// $this->db->insert('file_table',array('file_name' => $fileName));
}
}
}
// Usage : <form action="<?php echo site_url('/dropzone/upload');" class="dropzone" >
/* End of file dropzone.js */
/* Location: ./application/controllers/dropzone.php */
Secondly Add the following HTML, (mainly to a form so as to submit file name
<div id="upload" class="form-group">
<label>Drop file Here</label>
<input type="hidden" id="file" name="file"/>
<div
class="dropzone"
id="uploadFile"><!--uploadFile is the dropzone name-->
</div>
</div>
Then a little Js to do the magic
Dropzone.options.uploadFile = {
paramName: "file", // The name that will be used to transfer the file
url:"<?php echo site_url('/dropzone/upload');?>",
maxFiles:1,
acceptedFiles:'image/*,application/pdf,.docx,.doc,.xls,.xlsx,.csv',
dictMaxFilesExceeded:"You can only upload one file per Response",
init: function() {
this.on("sending", function(file) {
// $('button#submit').attr('disabled','');// Requires Jquery
});
this.on("complete", function(file) {
//$('button#submit').removeAttr('disabled'); // Requires JQuery
});
this.on("success", function(file,xhr) {
//$('input[type="hidden"]#file').val(xhr); // Requires Jquery
});
}
};
Remember to include dropzone.js and jquery.js if needed.
You can upload files using the PHP function. But at first, you should make the directory or folder by yourself.
Here is my code, I did not add the validation part. I have created the uploads folder in the root directory.
$file = $_FILES['verfication_image'];
$file_name_with_extenstion = $file['name'];
$file_name = pathinfo($file_name_with_extenstion, PATHINFO_FILENAME);
$extension = pathinfo($file_name_with_extenstion, PATHINFO_EXTENSION);
$file_tmp_location =$_FILES['verfication_image']['tmp_name'];
$upload_name = $file_name.time().".$extension";
if(move_uploaded_file($file_tmp_location,"uploads/".$upload_name)){
echo "The file has been uploaded.";
}else{
echo "There was an error.";
}
I would suggest using the Codeigniter version of uploading the file as it is simple to add validation. I have added my Codeigniter code with validation,
$file = $_FILES['verfication_image'];
$file_name_with_extenstion = $file['name'];
$file_name = pathinfo($file_name_with_extenstion, PATHINFO_FILENAME);
$extension = pathinfo($file_name_with_extenstion, PATHINFO_EXTENSION);
$upload_name = $file_name.time().".$extension";
$config['upload_path'] = 'uploads/';
$config['file_name'] = $upload_name;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);//Load the libary with the configuration
if(!$this->upload->do_upload('verfication_image')){
echo($this->upload->display_errors());//validation error will be printed
}else{
echo "The file has been uploaded.";
}
For more details, please follow the official guideline File Uploading class
Related
I've been trying to upload an image to my database (Note: I'm using Codeigniter 3) but every time I try to upload the image to the database it doesn't store it's filename and the image itself and only stores 1 bit in BLOB var type.
$photo = file_get_contents($_FILES['image']['tmp_name];
this->db->select('*')
[...]
if(empty($response){
$data['entry_phone_no'] = $this->input->post('phone_no');
$data['entry_email'] = $this->input->post('email');
$data['entry_firstname'] = $this->input->post('first_name');
$data['entry_lastname'] = $this->input->post('last_name');
$data['entry_photo'] = $photo;
$data['entry_photo_name'] = $photo;
In my model.php I have the setup above and it saves the other data (the phone num, email etc). I know I am missing some code at the "$photo" part but can anyone please point it out?
You can upload the image on folder called "Uploads" and save that filename into database as below:
Views.php:
<input class="my-set_3" type="file" name="chatbot_profile" id="chatbot_profile" required>
Controller.php:
if (!empty($_FILES['chatbot_profile']['name']))
{
$config['upload_path'] = './uploads';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1000000;
$config['file_name'] = time();
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('chatbot_profile'))
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
$file_name = $data['upload_data']['file_name'] ;
// Store this filename into database
// Your database code will be placed here
// OR call model mathod from here
}
}
Note: uploads folder will created by us and outside the application
folder.
I am uploading multiple dynamic images with codeigniter with the following code.
foreach ($_FILES as $key => $value) {
$imagePrefix = time();
if (!$this->upload->do_upload($key))
{
echo $errors = $this->upload->display_errors();
return '';
}
else
{
$imagename = $imagePrefix.$value['name'];
$insertImage = $this->db->query("Insert into `tbl_event_imges` (`iEventID`,`vImage`) values ('".$insertId."','".$imagename."')");
}
}
When I upload an image to the specific folder this works fine; the issue is if a user uploads an image having same name, then it will automatically rename the image and upload to the folder, but what I want is to rename it by adding $imagePrefix that I have added in else part of the code and then want to upload the image with this name. But this is not working with me..
Any suggestion please?
you need to provide configuration preferences to your upload function like so:
$imagePrefix = time();
$imagename = $imagePrefix.$value['name'];
$this->load->library('upload');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['file_name'] = $imagename; // set the name here
$this->upload->initialize($config);
if (!$this->upload->do_upload($key)){
...
}else{
...
}
Source: http://www.codeigniter.com/user_guide/libraries/file_uploading.html?highlight=file%20upload#setting-preferences
Just alternative, you can use CI's rename function to rename after file uploaded.
$image = $this->upload->data();
$file_path = $image ['file_path'];
$file = $image ['full_path'];
$file_ext = $image['file_ext'];
$final_file_name = time() . $image['file_name'] . $file_ext;
only add below code and it run successfully and also set encrypt_name to false
$path = $_FILES['userfile']['name'];
$newName = "Add any name".".".pathinfo($path, PATHINFO_EXTENSION);
$config['file_name'] = $newName;
$config['encrypt_name'] = false;
I used the Codeigniter's Upload Class to upload images to a folder in the project. In the database I only store the the url generated after upload the image, so when I want to delete a row in the db I also need to delete the image. How can I do it in codeigniter?
I will be grateful for your answers.
You can delete all the files in a given path, for example in the uploads folder, using this deleteFiles() function which could be in one of your models:
$path = $_SERVER['DOCUMENT_ROOT'].'/uploads/';
function deleteFiles($path){
$files = glob($path.'*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file))
unlink($file); // delete file
//echo $file.'file deleted';
}
}
delete_row_from_db(); unlink('/path/to/file');
/path/to/file must be real path.
For eg :
if your folder is like this htp://example.com/uploads
$path = realpath(APPPATH . '../uploads');
APPPATH = path to the application folder.
Its working...
if(isset($_FILES['image']) && $_FILES['image']['name'] != '')
{
$config['upload_path'] = './upload/image';
$config['allowed_types'] = 'jpeg|jpg|png';
$config['file_name'] = base64_encode("" . mt_rand());
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('image'))
{
$error = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('msg', 'We had an error trying. Unable upload image');
}
else
{
$image_data = $this->upload->data();
#unlink("./upload/image/".$_POST['prev_image']);
$testData['image'] = $image_data['file_name'];
}
}
$m_img_real= $_SERVER['DOCUMENT_ROOT'].'/images/shop/real_images/'.$data['settings']->shop_now;
$m_img_thumbs = $_SERVER['DOCUMENT_ROOT'].'/images/shop/thumbs/'.$data['settings']->shop_now;
if (file_exists($m_img_real) && file_exists($m_img_thumbs))
{
unlink($m_img_real);
unlink($m_img_thumbs);
}
View:
<input type="file" name="new_file" data-required="1" class="" />
<input type="hidden" name="old_file" value="echo your old file name"/>
<input type="submit" name="submit"/>
Controller:
function edit_image() {
if(isset($_FILES['new_file']['name']) && $_FILES['new_file']['name'] != '') {
move_uploaded_file($_FILES['new_file']['tmp_name'],'./public_html/banner/'.$_FILES['new_file']['name']);
$upload = $_FILES['new_file']['name'];
$name = $post['old_file'];
#unlink("./public_html/banner/".$name);
}
else {
$upload = $post['old_file'];
}
}
Try using delete_files('path') function offered by CI framework itself:
https://ellislab.com/codeigniter/user-guide/helpers/file_helper.html
$image_data = $this->upload->data();
unlink($image_data['full_path']);
This line $this->upload->data() will return many information about uploaded file. You can print information and work accordingly.
I am trying to upload multiple images. I am using Codeigniter and I know there is a built in file upload class but I am just experimenting with my custom made image upload library. I have provided the code below.
The problem I am facing with the following code is it is just uploading only one (the one that is selected at last in the form) image.
Could you please kindly tell me where I am doing wrong?
My Controller:
function img_upload(){
$this->load->library('image_upload');
$image1= $this->image_upload->upload_image('imagefile1');
$image2= $this->image_upload->upload_image('imagefile2');
$image3= $this->image_upload->upload_image('imagefile3');
echo $image1 ."<br>"; echo $image2;
}
application/libraries/image_upload.php (Custom made library)
function upload_image($image_info){
$image=$_FILES[$image_info]['name'];
$filename = stripslashes($image);
$extension = $this->getExtension($filename);
$extension = strtolower($extension);
$image_name=time().'.'.$extension;
$newname="support/images/products/".$image_name;
$uploaded = move_uploaded_file($_FILES[$image_info]['tmp_name'], $newname);
if($uploaded) {return $image_name; } else {return FALSE;}
}
My Form
<form id="myForm" enctype="multipart/form-data"
action="<?php echo base_url();?>add/img_upload" method="post" name="myForm">
<input type="file" name="imagefile1" size="20" /><br>
<input type="file" name="imagefile2" size="20" /><br>
<input type="file" name="imagefile3" size="20" /><br>
<br /><br />
<input type="submit" value="upload" />
</form>
you can create some kind of rollback functionality and use CI native lib . it's little extra work for the server but it's less/clean/easyTOdebug code and it works .
function do_upload()
{
1 - configuration
$config['upload_path'] = './uploads/';
// other configurations
$this->load->library('upload', $config);
$error = array('stat'=>0 , 'reason'=>'' ;
2- uploading
if ( ! $this->upload->do_upload('file_1'))
{
$error['stat'] = 1 ;
$error['reason'] = $this->upload->display_errors() ;
}
else
{ $uploaded_array[] = $uploaded_file_name ; }
// you may need to clean and re initialize library before new upload
if ( ! $this->upload->do_upload('file_2'))
{
$error['stat'] = 1 ;
$error['reason'] = $this->upload->display_errors() ;
}
else
{ $uploaded_array[] = $uploaded_file_name ; }
3 - checking for errors and rollback at the end
if($error['stat'] == 1 )
{
$upload_path = './upload/';
if(!empty($uploaded_array))
{
foreach( $uploaded_array as $uploaded )
{
$file = $upload_path.$uploaded;
if(is_file($file))
unlink($file);
}
}
echo 'there was a problem : '.$error['reason'];
}
else
{
echo 'success';
}
}
I have found the solution to my problem, and thought it could help someone if I share.
The problem was in the image_upload.php file (custom made library), specifically in this line:
$image_name=time().'.'.$extension; //
time() was perhaps overwriting the files. So I replaced my previous code with the following:
function upload_image($image_info){
$image=$_FILES[$image_info]['name'];
$filename = stripslashes($image);
$extension = $this->getExtension($filename);
$extension = strtolower($extension);
$image_name=$this->get_random_number().'.'.$extension;
$newname="support/images/products/".$image_name;
$uploaded = move_uploaded_file($_FILES[$image_info]['tmp_name'], $newname);
if($uploaded) {return $image_name; } else {return FALSE;}
}
function get_random_number(){
$today = date('YmdHi');
$startDate = date('YmdHi', strtotime('-10 days'));
$range = $today - $startDate;
$rand1 = rand(0, $range);
$rand2 = rand(0, 600000);
return $value=($rand1+$rand2);
}
I have a script working to upload images without refreshing the page using jquery.form.js
Below is the PHP file that it kicks off the processes the file and when finished PHP creates an tag to show the image.
I now need a method to let JQUERY know the PHP file processing has completed. Is there a good way to connect these two?
I thought I could write something hidden to the page and have JQUERY look for this but I'm not sure if this is a B-Grade solution.
Any ideas? I can explain better if needed. thx
<?php
$type = $_POST['mimetype'];
$xhr = $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
foreach($_FILES as $file) {
$filename = $file['name'];
$filesize = $file['size'];
$filetmp = $file['tmp_name'];
}
// Script Variables
$errors=0;
$notAllowedFileType=0;
$exceededMaxFileSize=0;
$maxsize='10485760'; // 10MB Maximum Upload
$folder = 'images/';
$configWidth = 500;
$newFileName = 'success_story'.time().'.jpg';
// Process if No Errors
if(!$errors) {
// Variables
$uploadedFile = $filetmp;
$filename = basename( $filename);
$extension = strtolower(getExtension($filename));
// Convert the Specific Type of File into an Image
if($extension=='jpg' || $extension=='jpeg' ) {
$uploadedfile = $fullfilepath;
$src = imagecreatefromjpeg($uploadedFile);
}elseif($extension=='png') {
$uploadedfile = $fullfilepath;
$src = imagecreatefrompng($uploadedFile);
}else{
$uploadedfile = $fullfilepath;
$src = imagecreatefromgif($uploadedFile);
}
// Configure Width & Height
list($origWidth, $origHeight) = getimagesize($uploadedFile);
$configHeight = ($origHeight/$origWidth)* $configWidth;
// Create Empty File
$tmp = imagecreatetruecolor($configWidth, $configHeight);
imagecopyresampled($tmp, $src, 0,0,0,0,$configWidth,$configHeight,$origWidth,$origHeight);
imagejpeg($tmp, $_SERVER['DOCUMENT_ROOT'].$folder.$newFileName,90);
echo "<img src=".$folder.$newFileName." id=\"cropMeNowImage\">";
}
// Get Extension from Uploaded File
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) {return "";}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script>
(function() {
$(document).on('change','img#cropMeNowImage', function() {
alert('Ready to Crop');
});
})();
</script>
You need to use a callback function. Something like:
$(document).on('change','img#cropMeNowImage', function() {
$.post(url, {
vars_to_server : vars
}, function(process_done){
if (process_done)
alert("ready");
})
});
php must echo something recognizable by jquery in the var process_done
Instead:
echo "<img src=".$folder.$newFileName." id=\"cropMeNowImage\">";
you can echo 1 for success
This is the idea. It's totally possible. Specially for the common task of upload files via AJAX...
I recommend you: 5 Ways to Make Ajax Calls with jQuery
Take a look to http://github.com/valums/file-uploader I always use it to upload files.