Good day! I am trying to retrieve from image path with the name stored from database but I am struggling to display that image from folder and I'll explain you that later... here is my code.
in my controller
public function save()
{
$url = $this->do_upload();
$title = $_POST["title"];
$this->main_m->save($title, $url);
}
public function do_upload()
{
$type = explode('.', $_FILES["pic"] ["name"]);
$type = $type[count($type)-1];
$url = "./images/".uniqid(rand()).'.'.$type;
if(in_array($type, array("jpg","jpeg","gif","png")))
if(is_uploaded_file($_FILES["pic"]["tmp_name"]))
if (move_uploaded_file($_FILES["pic"]["tmp_name"], $url))
return $url;
}
in my view im trying to retrieve like this.
<?php foreach ($this->b->getalldata() as $row) {
echo '<li>'.
'<a class="ns-img" href="'.base_url("images/".$row->image).'".></a>'.
'<div class="caption">'.$row->title.'</div>'.
'</li>';
} ?>
in my model
public function save($title, $url)
{
$this->db->set('title', $title);
$this->db->set('image', $url);
$this->db->insert('slider');
}
the image stored to path folder and also the new name of the image stored to database but displaying the image like that is not working for me. my image path folder is "images" and the image name stored to database is "./images/new_name.jpg" not the same name as image that stored to the folder path. the image name that stored to folder path has no ./images/ only new_name.jpg...
how to display that image? someone tried that? help!
You need to explode image name from "./images/new_name.jpg".
$image_arr = explode("/", "./images/new_name.jpg");
echo $image_name = end($image_arr);
we used codeigniter upload library
$this->load->library('image_lib');
$config = array(
'upload_path' => APPPATH."upload/folder",
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "2048000"
);
$this->load->library('upload', $config);
$this->upload->do_upload('pic');
You need img HTML tag:
<img src="<?php echo base_url('images/' . $row->image);?>">
Try this
On view
<?php foreach ($this->b->getalldata() as $row) {
echo '<li>'.
'<a class="ns-img" href="#">'.base_url().'images/'.$row->image.'</a>'.
'<div class="caption">'.$row->title.'</div>'.
'</li>';
} ?>
You have error here .base_url("images/".$row->image).'n try to use site_url('images').'/'.$row->image
i hope you will get the proper path of your file.
Related
/**
* A function to update single image. Params are filename, name, directory, the image file, old images
*/
static function singleUploadUpdate($filename, $directory, $file, $data){
$dir = "backend/images/".$directory;
$large_dir = $dir."/large";
if (!empty($file)){
if (!File::exists($dir)){
File::makeDirectory($dir, 0755, true);
}
if (!File::exists($large_dir)){
File::makeDirectory($large_dir, 0755, true);
}
$images = json_decode($data);
foreach ($images as $key => $value){
File::delete("public/".$value->big_image);
File::delete("public/".$value->small_image);
}
$uploaded_file_name = $filename.rand(1,100000).".".$file->getClientOriginalExtension();
$path = public_path($dir."/".$uploaded_file_name);
$path2 = public_path($large_dir."/".$uploaded_file_name);
Image::make($file->getRealPath())->save($path2);
Image::make($file->getRealPath())->resize(250,250)->save($path);
$files = [
"small_image" => $dir."/".$uploaded_file_name,
"big_image" => $dir."/large/".$uploaded_file_name
];
return json_encode($files);
}else{
return $data;
}
}
this is my helper function to update user image, I got error on these lines :
foreach ($images as $key => $value){
File::delete("public/".$value->big_image);
File::delete("public/".$value->small_image);
}
and my image upload codes to create a user firt time is here:
/**
* A function to upload single image. Params are filename, name, directory and a file
*/
static function singleUpload($filename, $directory, $file){
$dir = "backend/images/".$directory;
$large_dir = $dir."/large";
if (!empty($file)){
if (!File::exists($dir)){
File::makeDirectory($dir, 0755, true);
}
if (!File::exists($large_dir)){
File::makeDirectory($large_dir, 0755, true);
}
$uploaded_file_name = $filename.rand(1,100000).".".$file->getClientOriginalExtension();
$path = public_path($dir."/".$uploaded_file_name);
$path2 = public_path($large_dir."/".$uploaded_file_name);
Image::make($file->getRealPath())->save($path2);
Image::make($file->getRealPath())->resize(250,250)->save($path);
$files = [
"small_image" => $dir."/".$uploaded_file_name,
"big_image" => $dir."/large/".$uploaded_file_name
];
return json_encode($files);
}else{
return [];
}
}
and I call this this functions like this
imageUpload::singleUploadUpdate(mHelper::permalink($request->job_title.rand(1,1000)), "users", $request->file("avatar"),$all_images);
so what I did wrong ?
In blade template engine or somewhere else everything works fine, but while uploading image makes problem. Thank you for your help.
im trying to upload multiple images with laravel 5.4, actually the process to upload images is done, the question is how to store them in database?
for example when gonna create a slide show of something that has several images that is uploaded, how to group them so the slide show knows those images are in one group?
can you guys help me?
Make sure you go to config/filesystems and turn 'FILESYSTEM_DRIVER' to 'public'
Model to store image paths:
class UserDocuments extends Model
{
//
protected $table = 'user_documents';
public function store($user_id, $document_link, $file_name)
{
$this->user_id = $user_id;
$this->document_link = $document_link;
$this->file_name = $file_name;
$this->save();
}
}
Code in controller to store files ('document' is file input field name)
if ($request->hasFile('document')) {
$link = $request->file('document')->store('documents');
}
$userDocuments->store(request('user_id'), url($link), $link);
To show if the images are in a group, you would have to create a database column called 'group_id' and sort them accordingly.
We have to store images into one records/row by separting commas.
class DocumentController extends Controller
{
public function store(Request $request)
{
$pid = $request->input('pid');
$input = $request->file('files');
$picture = array();
if($request->hasFile('files')) :
foreach ($images as $item):
$extension = $item->getClientOriginalName(); //image extension
$name = time() . '.' .$extension; //image name
$item->move('uploads/documents/', $name); //move to destination
$arr[] = $name; //store image into array
endforeach;
$picture = implode(",", $arr); //Image separated by comma
else:
$picture = '';
endif;
DB::table('document')->insert(array('pid' => $pid,'image' => $picture));
Session::flash('message', 'Multiple Images are uploaded successfully');
return redirect('/multiple-image');
}
}
I'm trying to upload an image to my local folder
webroot/img/
and save the image name to database. Everything seems working fine but the image is not saving to the path
here's my view
<?php echo $this->Form->create(null,['url' => ['controller' => 'users', action' => 'update_image'],
array('enctype'=>'multipart/form-data')]); ?>
<?php echo $this->Form->input('User.id') ?>
<?php echo $this->Form->file('Profile.picture',['type'=>'file']) ?>
<?php echo $this->Form->end('submit') ?>
My controller
public function update_image(){
$id = $this->Auth->user('id');
$this->Profile->id = $id;
$this->set('profile', $this->User->findById($id));
if ($this->request->is(array('post','put'))) {
$frmData = $this->request->data;
//Path to store upload image
$target = "/teamjob_back/img/../img/".basename($frmData['Profile']['picture']);
//Get the data from form
$image = $frmData['Profile']['picture'];
//save data to database
$this->Profile->save($this->request->data);
//Image store to the img folder
if (move_uploaded_file($image['tmp_name']['name'], $target)) {
echo "Image successfull";
}
}
}
And the code
$image['tmp_name']['name']
gives me an Illegal string offset error.
EDITED
This code works on the controller
if ($this->request->is('post')) {
$frmData = $this->request->data;
$tmp = $frmData['picture']['tmp_name'];
$hash = rand();
$date = date("Ymd");
$image = $date.$hash."-".$frmData['picture']['name'];
$target = WWW_ROOT.'img'.DS.'uploads'.DS;
$target = $target.basename($image);
if (move_uploaded_file($tmp, $target)) {
echo "Successfully moved";
}
else
{
echo "Error";
}
}
First you need to remove "type => file" becuase you already use Form helper "file" function , if we are use "Form->input" then we use 'type=>file'
e.g. $this->Form->input('email', array('type' => 'email'));
$this->Form->file('Profile.picture')
check your target path have write permission, pr($image) then you get proper array format of $image['temp_name] or $image[0]['temp_name] etc.
and put your temp_name in move_uploaded_file function
e.g. move_uploaded_file(your temp_name)
Form Helper
First add
['type' => 'file']
as an option to your file instead of trying to send enctype.
Second $image is a $this->request->data['Profile']['picture'] so you can't do ['tmp_name'] and ['name'] together ... debug($this->request->data['Profile']['picture'] and you'll see that you could have
$image['tmp_name']
or
$image['name']
but not both together.
Probably more but those are good starts.
make sure to include enctype when you create the form uploading file
<?= $this->Form->create(NULL, ['enctype' => 'multipart/form-data']) ?>
I have this code which uploads an image from admin and it works well.
add_action('admin_init', 'register_and_build_fields');
function register_and_build_fields() {
register_setting('theme_options', 'theme_options', 'validate_setting', 'delete_file');
}
function validate_setting($theme_options) {
$keys = array_keys($_FILES); $i = 0; foreach ( $_FILES as $image ) {
// if a files was upload
if ($image['size']) {
// if it is an image
if ( preg_match('/(jpg|jpeg|png|gif)$/', $image['type']) ) { $override = array('test_form' => false);
$options = get_option('theme_options'); echo "<img src='{$options['logo']}' />";
// save the file, and store an array, containing its location in $file
$file = wp_handle_upload( $image, $override ); $theme_options[$keys[$i]] = $file['url']; } else {
// Not an image.
$options = get_option('theme_options'); $theme_options[$keys[$i]] = $options[$logo];
// Die and let the user know that they made a mistake.
wp_die('No image was uploaded or invalid format.<br>Supported formats: jpg, jpeg, png, gif.<br> Go <button onclick="history.back()">Back</button> and try again.'); } } // Else, the user didn't upload a file.
// Retain the image that's already on file.
else { $options = get_option('theme_options'); $theme_options[$keys[$i]] = $options[$keys[$i]]; } $i++; }
return $theme_options;
}
and now I want the function to delete the current image.
function delete_file($theme_options) {
if (array_key_exists('delete_file', $_FILES)) {
$image = $_FILES['delete_file'];
if (file_exists($image)) {
unlink($image);
echo 'File '.$image.' has been deleted';
} else {
echo 'Could not delete '.$image.', file does not exist';
}
}
}
I added the button in admin but is doing.. nothing.
I'm building a TemplateOptions in WordPress and now I'm trying to make the logo function to be uploaded and deleted from admin. Like I said, uploading the logo works and now I want to make the field "delete" to work.
I found out that you don't need to insert the record in the DB as you only have a single image and whose name and path are also constant . So you simply need to unlink the image from the directory and it will be deleted, nothing else.
say your logo.png is in your themes's img folder then you should unlink it like this. default is your theme name
$path = ABSPATH.'wp-content/themes/default/img/logo.png';
if(file_exists($path))
{
unlink( $path );
}
Note: Remember that you have to pass the absolute path to the unlink() and not the url having http , because it will give you an error , you can't use http with unlink.
I've been having trouble properly outputting the directory for images in a slider using Custom Fields. The code I'm using is following:
<div class="container">
<?php
//path or directory where the images are stored
$directory = "echo get_post_meta($post->ID, 'directory', true)";
//read all files with a .jpg extension
$images = glob($directory . "*.jpg");
//output the required HTML code to display the images in the gallery
foreach($images as $image)
{
echo '<div class="content"><div><img src="'.$image.'" width="120" height="80" alt="this is a test" class="thumb" /></div></div>'."\n";
}
?>
</div>
The value I want to dynamically output is the $directory = "", where it would normally be something like $directory = "images/product1/". I have my custom field 'directory' set as images/product1/. Any ideas? Thanks for the help!
It looks like the issue is with this line:
$directory = "echo get_post_meta($post->ID, 'directory', true)";
will result in trying to glob like this:
glob("echo get_post_meta($post->ID, 'directory', true)*.jpg");
which is obviously invalid.
Instead you should actually be calling the get_post_meta() function
$directory = get_post_meta($post->ID, 'directory', true);