Im new at CodeIgniter and I want to read some data from mysql database using CodeIgniter. Data I have stored is an image.
I have this folder structure in my aplication:
1.ci
application
controllers
views
models
upload_images (Here I have the images stored as jpg files)
When I create this code the image shows up and it is Ok:
echo ' <img src=" http://localhost/ci/'.$row->book_img.' " />'
While when I try to output images from the database in another way like below it outputs the link instead of the image. I want to use html helper and I have loaded it.
echo ' img(' http://localhost/ci/'.$row->book_img.')';
the image doesn't appear. Do I do something wrong in the second way? Thanks!
The uploads folder should be out side of application folder because the htaccess in the application folder blocks access I also would auto load the url helper
config > autoload.php
$autoload['helper'] = array('url');
Folder Structure For Upload Images
application
system
upload_images <-- folder permission 0777
index.php
then make sure you are getting the image correct on controller var_dump($row->book_img)
Option : 1
$data['img'] = $row->book_img;
$this->load->view('your_view', $data);
View
<img src="<?php echo base_url('upload_images/' . $img);?>" />
Option: 2
$this->load->helper('html');
$data['img'] = img('upload_images/' . $row->book_img); ;
$this->load->view('your_view', $data);
View
<?php echo $img;?>
And set your base url
$config['base_url'] = 'http://localhost/yourproject/';
It all depends on what what $row->book_img is returning. If it is only returning the image name, you must first make sure that is has the extension at the end whether it be name.jpg or name.png, etc.
if it is correct you simply use:
$img_src = base_url () . '/PATH_TO_IMAGE_FOLDER/' . $row->book_img;
echo "<img src='$img_src'/>";
If it is returning the full path then:
$img_src = base_url () . $row->book_img;
echo "<img src='$img_src'/>";
Try calling it like:
echo img('http://localhost/ci/'.$row->book_img);
Source
You have syntax errors in your second code snippet and you probably don't have error reporting enabled (which is a bad idea during development). Check here for help with setting that up.
Related
I have tried to setup an upload script in Laravel and have followed the instructions in the docs.
I created a Symlink using the Laravel script and it looks like the following
storage -> /Users/username/Sites/switch/storage/app/public
The problem arrives when I go to upload the image and then get result of the image url in return. As you can see to match the symlink I set the folder to be public below.
$path = $request->file('manufacturer_image_name')->store('public');
echo asset($path);
and this returns
http://127.0.0.1:8000/public/XxIX7L75cLZ7cf2xzejc3E6STrcjfeeu3AQcSKz1.png
the problem is this doesn't work and throws a 404 but if I manually change the url from "public" to "storage" it will find the image.
http://127.0.0.1:8000/storage/XxIX7L75cLZ7cf2xzejc3E6STrcjfeeu3AQcSKz1.png
Shouldn't
echo asset($path);
be returning a url containing storage instead of public?
assett($path) is for generating a URL for assets that are just in the public folder, things like the Mix generated CSS and JS files. If you user Laravel Storage to save the file, you also have to use Laravel storage to generate the file URL.
Storage::url('file.jpg');
Well, there are a lot of ways to do that, pick anyone which fits you best.
// using storage_path helper
storage_path('public/' . $filename);
// you could make a double-check with File::exist() method
$path = storage_path('public/' . $filename);
if (!File::exists($path)) {
abort(404);
}
// using asset helper
asset('storage/your_folder/image.png');
// using url helper
url('storage/your_folder/image.png');
// using Storage facade
Storage::url($photoLink)
Here is the simplest and exact thing for your issue
if(!empty($request->file('manufacturer_image_name'))){
$path = storage_path('public/image/');
$image_path = Storage::disk('public')->put('manufacturer_image_name', $request->file('manufacturer_image_name'));
//Assuming you have a model called Manufacturer and created $manufacturer = new Manufacturer()
$manufacturer->manufacturer_image_name = isset($image_path) ? "storage/".$image_path : "";
}
Thanks for the help, I discovered this answer the fits nearly perfectly what I am after. Laravel: Storage not putting file inside public folder
This was what I ended up with.
if($request->file('manufacturer_image_name')){
$path = Storage::disk('public')->put('logo', $request->file('manufacturer_image_name'));
echo $path;
}
$path now returns "logo/filename.ext" instead of "public/ or storage/" so I can store this directly in the db.
I have the following shortcode which gets the images of that post (that will be in a folder named as the post's id ) and displays them echoing as many tag images as needed.
session_start();
$postID = $_SESSION['post_ID'];
$upload_dir = wp_upload_dir();
$path = $upload_dir['basedir'].'/'.'gallery/'.$postID;
if(file_exists($path)) {
$pathFile = $path.'/*';
$images = glob($pathFile);
if(!empty($images)) {
foreach($images as $image){
$alt = end(explode('/', $image));
echo '<img src="'.$image.'" alt="'.$alt.'" />';
}
} else echo 'No hay imágenes.';
} else echo 'No hay imágenes.';
?>
The problem is that the images aren't displayed, i get the followin error in the brower's console GET https://path-to-theme/wp-content/uploads/gallery/1658/wwg.jpg 404, per every image and i get this icon:
image
I have no idea why my images aren't displayed the images, the path is correct, the images are there, complitely no idea what I'm missing. It's not a permissions problem as i tried giving 755 permissions to the directories starting from /uploads/.. and so on including the images.
I'm going to assume that the URL you reference in your question is actually https://yourdomain/wp-content/uploads/gallery/1658/wwg.jpg and not https://path-to-theme/wp-content/uploads/gallery/1658/wwg.jpg. Right?
If that's the case, then it should be able to pull open that file. The first thing I'd check is whether you actually have the file located where you think it is: /wp-content/uploads/gallery/1658/
If the file is actually in that folder, and you can access it from your browser at https://yourdomain/wp-content/uploads/gallery/1658/wwg.jpg then my next suggestion would be to check the permission of each of the folders leading up to the file and make sure they are set to 755, and then make sure your file is set to 644.
Here are instructions on changing file permissions.
Let me know if that helps?
I fixed the problem. The issue wa sthat i wasn't uploading the images as wp wants me to, therefore the images, even they were in the folder, couldn't be displayed. So I had to change the way i uploaded them, by using wp functions and specifying the mime_type etc so wp could store their metadata in it's db in order to be able to acknowledge them and display them in a future.
In my project I have a folder secure in root. The project package looks like:
application
secure
system
...........
Inside secure folder I am uploading some images on form submit using
$config1['upload_path'] = './secure/';
$ext = end(explode(".", $_FILES['thumb_image']['name']));
$config1['file_name'] = time().$_FILES['thumb_image']['name'];
$config1['allowed_types'] = 'jpg|png|jpeg|gif|bmp|jpe|tiff|tif';
$this->load->library('upload', $config1);
$this->upload->initialize($config1);
$this->upload->do_upload('thumb_image');
and it is working properly. Now while on editing the details, using another form, if I am uploading a new image instead of the current image file, I want to unlink the current one and then upload new file.
For this I am using the code:
unlink(base_url("secure/".$data['row']->videothumbnail));
I also tried with
unlink('/secure/'.$data['row']->videothumbnail);
where $data['row']->videothumbnail) is the current image file from database. New file is successfully uploaded. But old file is not getting unlinked. I have set the permission of secure folder to 777. But the images are uploaded with read only permission. Is it because of this, it is not getting unlinked?
Can anyone help me to solve this?
Thanks in advance.
Try this:
Set the permission dynamically using:
#chmod('./secure/'.$data['row']->videothumbnail, 0777);
then try unlink:
#unlink('./secure/'.$data['row']->videothumbnail);
Try echoing the path that you are providing to unlink function.
It should be something like this:
base_url()."secure/".$data['row']->videothumbnail;
I also had this issue even after setting the right permission on the folder. But the following code worked for me.
unlink(realpath(APPPATH . '../uploads').'/'.$ImageName);
Try to use $_SERVER['DOCUMENT_ROOT'] instead of base_url
$this->load->helper("file")
unlink(base_url('folder/file.ext'));
location:
\app\controller
\system\libraries
**folder\file.ext**
$unlinkUrl = "secure/".$data['row']->videothumbnail;
if(file_exists($unlinkUrl)){
unlink($unlinkUrl);
}
else{
echo $unlinkUrl." is not available";
}
I think you are just making a stupid mistake.
Firstly, the first param of unlink should be a relative path or absolute path, but base_url function will return you a path contains domain name, HOW CAN YOU DELETE A FILE ON REMOTE SERVER ?
Secondly, '/secure/'.$data['row']->videothumbnail here is not a relative path but a absolute path
YOU MUST change it into /the/absolute/path/to/secure/ or ./the/relative/path/to/secure/ (DO NOT MISS THE DOT)
use this to unlink
$oldthumb = "secure/".$data['row']->videothumbnail;
#unlink($oldthumb);
First Load the $this->load->helper("file") and then unlink it
unlink("secure/".$data['row']->videothumbnail);
if ($rowAffected > 0) {
if ($isMediaUpload)
if (file_exists('./uploads/' . $this->input->post('img_url')))
unlink('./uploads/' . $this->input->post('img_url'));
redirect('/admin/configration', 'location');
}
Though i came in late but someone might need this .
unlink(FCPATH."secure/".$data['row']->videothumbnail)
**FCPATH** - path to front controller, usually index.php
**APPPATH** - path to application folder
**BASEPATH** - path to system folder.
I try to unlink an image in CodeIgniter, but the unlink function shows:
notice Undefined index: userfile
Here is my code
<?php
function get_from_post(){
$data['logo_name'] = $this->input->post('logo_name',TRUE);
$data['logo_thumb'] = $_FILES['userfile']['name'];
return $data;
}
function deleteconf($data){
$data= $this->get_from_post();
$update_id=$this->uri->segment(3);
#unlink(base_url.'image/logo_thumb'.$logo_thumb);
$query= $this->_delete($update_id);
}
?>
the unlink function shows notice Undefined index: userfile
The upload form, using multipart/form-data
Make sure you've use enctype="multipart/form-data" attribute/value for your upload form.
<form action="" method="post" accept-charset="utf-8" enctype="multipart/form-data">
From the MDN:
enctype
multipart/form-data: Use this value if you are using an <input>
element with the type attribute set to "file".
If you're going to use CodeIgniter form helper, you could use form_open_multipart() function:
This function is absolutely identical to the form_open() tag above
except that it adds a multipart attribute, which is necessary if you
would like to use the form to upload files with.
Deleting files, File path vs URL address
PHP unlink() function accepts the Path of the file as the first argument. Not the URL Address.
The base_url() helper function returns the URL address of the site, which you've set in the config.php file.
You'll have to use the path of the file on your server, as follows:
unlink('/path/to/image/image_name.jpg'); // This is an absolute path to the file
You could use an Absolute or Relative path, but note that the relative path is relative to the index.php file. i.e. If the image/ folder is placed beside index.php file, you should use image/image_name.jpg as the file path:
unlink('image/image_name.jpg'); // This is a relative path to the file
If you want to upload a photo for user profile and also
at the time the old user photo should be deleted by
using unlink method in codeignitor
$query = $this->db->where('profile_id',$profile_id)->get('users')->row();
$result = $query->photo;
$result = http://localhost/abc/user_photo/FE12563.jpg
if ($result) {
$dd = substr($result, strlen(base_url()));
unlink($dd);
return $this->db->set('photo',$photo)->where('profile_id',$profile_id)->update('users');
}
First check your file input name. Is it "userfile" or not?
if not then add it and then run it once again.
function get_from_post(){
$filename = $_POST['logo_name'];
$path = $_SERVER['DOCUMENT_ROOT'].'/projectname/uploads/'.$filename ;
if(is_file($path)){
unlink($path);
echo 'File '.$filename.' has been deleted';
} else {
echo 'Could not delete '.$filename.', file does not exist';
}
}
base_url() function returns url of you project but here you have to use directory path of file which you want to delete.
$path = BASEPATH.'/assets/upload/employees/contracts/';
$get_file = $path.$con_id.'.jpg';
if(file_exists($get_file)){
unlink($get_file);
}
instead of unlink(base_url("/assets/upload/employees/contracts/'.$con_id."));
First unlink function work only with path (without url), so please remove base_url() function.
Then in your first function $_FILES array doesn't contain userfile index, that's why getting error.
NOTE:- Before using unlink i would like to use also file_exists() function, first it will check if file is exist on same path then use unlink function (for error handling).
Like that -
<?php
if(file_exists(filePath))
{
unlink(filePath);
}
?>
Please fix both issue.
Thanks
Suppose you have the file name in the database and your file is abc.jpg. Then to unlink that in Code Igniter just do -
$file = "abc.jpg";
$prev_file_path = "./assets/uploads/files/".$file;
if(file_exists($prev_file_path ))
unlink($prev_file_path );
My file upload path is "public_html/assets/uploads/files/". I am writing the above code in my controller which is "public_html/application/controllers/MyController.php". So the path will be same which I used in my CI file upload section. i.e.
...
$config['upload_path'] = './assets/uploads/files';
...
So we used relative path in both the upload and unlink section. So if the upload works perfectly then this will also work perfectly.
You can do like this, you need to get first the path of directory from where you have uploaded your image.
Exemple:
//this is your url
$mainPath='https://google.com/uploads/image/16.jpeg';
$uploadedDirectory=str_replace("https://google.com/","./", $mainPath);
//now you get path like this ./uploads/image/16.jpeg
if(unlink($uploadedDirectory)) {
$this->db->where('prodId',$id);
$this->db->delete('products');
}
$this->load->helper("file");
just add above line before unlink
unlink($path);
Can you please use this code to remove image on folder.
unlink(realpath('uploads/' . $_image));
"uploads" : Image exist in uploads folder.
"$_image" : Image file name
PHP functions:
1 : unlink()
2 : realpath()
The above code successfully working on my site to delete image on folder.
try this code
unlink(base_url().'/image/logo_thumb'.$logo_thumb);
Note: You didn't assign / declare $logo_thumb in your deleteconf().
Please check your code.
In my web application I need to display the images uploaded when creating in the view. The uploaded images are stored in /images/xxx folder . I want in such a way that as soon as the user uploads the image, it should appear in the final view. I know we should create an array reference pointing to the images/xxx folder in config/main.php . But I dont know how to refer to the individual images in the folder and print them in the final view..
My code for params in config/main.php
'params'=>array(
'adminEmail'=>'webmaster#example.com',
'vegImageLoc'=>'images/xxx',
),
);
I dont know how to refer to the individual array elements in the final view and print them in the final view. Any body help me how to proceed.
I dont know why you think you need to change anything in config, maybe I'm missing something, but if you want to show all images in a folder like images/xxx , I recommend to do this :
foreach (glob("images/xxx/*") as $img) {
echo "<img src ='".Yii::app()->request->baseUrl."/".$img."' />";
}
Or if you want to get the images from database, get it and again make a foreach like above.
$image = $model->getImages(); // function to get image list stored in db. return as array
Pass $image to view file.
In your view file. you can do as below:
foreach ($image as $img) {
echo "<img src ='".Yii::app()->request->baseUrl."/".Yii::app()->params["vegImageLoc"]."/".$img."' />";
}