Uploading images with foreign key constraint - codeigniter

I have a foreign key constraint in an images table which is the user_id column in my users table. When I try to upload a new image, I get the DB error
1364: Field 'user_id' doesn't have a default value.
I suspect it’s because the code is looking for a value to add to the images column. I originally thought that if the session is set, loading an image would automatically identify the user who’s uploading the image.
Question: How can I include data that would merge the two tables when a user uploads an image? Here is the code in the controller that uploads the image:
function upload() {
//$filename = md5(uniqid(rand(), false));
$config = array(
'upload_path' => 'uploads',
'allowed_types' => "gif|jpg|png|jpeg",
//'file_name' => $filename,
'max_size' => 200,
'max_width' => 1024,
'max_height' => 768
);
$this->load->library('upload', $config);
if(empty($this->session->userdata['email'])){
redirect(site_url().'/main/login/');
}else
$this->load->library('upload', $config);
if($this->upload->do_upload())
{
$file_data = $this->upload->data();
$data['name'] = $file_data['file_name'];
$data['file'] = $file_data['file_path'];
$data['file_type'] = $file_data['file_type'];
$data['file_size'] = $file_data['file_size'];
$data['date_uploaded'] = date('Y/m/d H:i:s');
The images_model:
function save_image($data){
$this->db->insert('images', $data);
}
The 'images' table:
Appreciate ALL input and suggestions.

I think in your application only users can upload image ...
Then before uploading image you should check if user is signed or not and get user id ...
when you want to add new record to images table you must add user_id to $data array
$data['user_id'] = $this->session->userdata('user_id'); // or anything you added to session
.....

Related

Function wp_generate_attachment_metadata returns always empty array in ajax function

I have searched far and wide, but have not found a solution.
I have a real estate ad insertion form, I need to be able to upload photos of the listings. I can upload the photos to the server via ajax, return the filenames in a textarea and always via ajax, after submitting the form, I can upload the photos to wordpress and attach them to the ad
The only problem is that it does not generate the photo metadata, wp_generate_attachment_metadata always returns an empty array.
I can't find a solution about it. I have another plugin with a similar form, but there I post the form not via ajax, but with the action = "post", and I can safely generate the metadata.
This is the code with which I insert the attachments and link them to the newly created post.
Hope someone can help me
//$filename = domoria-torino-strada-della-fornace-druento-15.jpg
if ($filename != '') {
$wp_upload_dir = wp_upload_dir();
$filename_path = $wp_upload_dir['path'] .'/'. $filename;
$filename_url = $wp_upload_dir['url'] .'/'. $filename;
$guid = $wp_upload_dir['url'] . '/' . basename( $filename_path );
$attachment = array(
'guid'=> $guid,
'post_mime_type' => 'image/jpeg',
'post_title' => $filename,
'post_content' => '',
'post_status' => 'inherit',
'post_parent' => $post_id
);
$attach_id = wp_insert_attachment( $attachment, $filename_path);
if($iter === 0){
set_post_thumbnail( $post_id, $attach_id );
}
$ids [] = $attach_id; //this array needs for an ACF field
//filename_path = home/uxo80ef6/domains/homeprime.sviluppo.host/public_html/wp-content/uploads/2021/12/domoria-torino-strada-della-fornace-druento-15.jpg
//$attach_id = 629
$file_uploaded_path = get_attached_file($attach_id);
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $file_uploaded_path );
wp_update_attachment_metadata( $attach_id, $attach_data );
$iter++;
}
UPDATE: The problem is due to getimagesize called by wp_generate_attachment_metadata that can't find the file by file_path, however the file is on the server.
I rewrote some parts of the code you posted:
change hardcoded post_mime_type with wp_check_filetype() instead.
rename some of the variables to: $file_name, $file_path, $parent_post_id
removed unused $filename_url
added $parent_post_id as the third argument into wp_insert_attachment()
removed get_attached_file() function and used $file_path for wp_generate_attachment_metadata()
<?php
// $file_name = domoria-torino-strada-della-fornace-druento-15.jpg
if (!empty($file_name)) {
// The ID of the post this attachment is for.
// eg. $parent_post_id = 37;
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
$file_path = $wp_upload_dir['path'] . '/' . $file_name;
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype(basename($file_path), null);
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($file_path),
'post_mime_type' => $filetype['type'],
'post_title' => sanitize_title($file_name),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment($attachment, $file_path, $parent_post_id);
// Set the first attachment as Featured image.
if ($iter === 0) {
set_post_thumbnail($parent_post_id, $attach_id);
}
// ACF field array data.
$ids[] = $attach_id;
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
wp_update_attachment_metadata($attach_id, $attach_data);
$iter++;
}

Image is not saved/updated into database using Laravel

I am trying to save my image into database while creating my user and i am using postman for this
My Code:
public function register(Request $request) {
$body = $request->all();
$userProfile = $body['user_profile'];
$userPrev = $body['privileges'];
$userProfile['is_super_admin'] = $userPrev['is_super_admin'];
$facilities = $userPrev['facilities'];
$bodyObj = array_merge($userProfile, $userPrev);
$validator = UserValidations::validateUser($bodyObj);
if ($validator->fails()) {
return response([
'status' => false,
'message' => __('messages.validation_errors'),
'errors' => $validator->errors()->all()
], 200);
}
DB::beginTransaction();
try {
If (Input::hasFile('image')) {
$file = Input::file('image');
$destinationPath = public_path() . '/profile_images/';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
$this->user->where('id', Auth::user()->id)->update(['profile_pic' => $filename]);
}
My user is created and saved into database, but the image is not.
Your help will be highly appreciated!
I am really confused. You want to store image in database (bad Idea). Secondly, You want to store image in database but you are storing the file name only.
Suggetion : If you would like to store images in database you have an option to convert it into base64 and store the string. While retrieving you could decode base64. For example:
$file = Input::file('image');
$img_data = file_get_contents($file);
$base64 = $base64_encode($img_data);
$this->user->where('id', Auth::user()->id)->update(['profile_pic' => $base64 ]);
Another suggetion [Best way] : store path in the database and store the file in the storage or public and use the url to access the image
However if you still want to save it on database
$image = addslashes(file_get_contents(Input::file('image')));
$this->user->where('id', Auth::user()->id)->update(['profile_pic' => $image ]);

How to upload multiple images from two different file uploads fields in single form in laravel?

How can I pass multiple images files from two separate file upload option in my form and then store into database? Here are my schema and controller codes.
Schema::create('images', function (Blueprint $table) {
$table->increments('image_id');
$table->increments('book_id')->unsigned();
$table->string('coverPageImage');
$table->string('previewPageImage');
$table->timestamps();
});
Form Fields: BookID, File Upload for coverPageImage, File Upload for
previewPageImage. Both coverPageImage and previewPageImage pass multiple images.
I was able to upload images into folder and save to database for single file upload.
$product_images = $request->file('coverPageImage');
foreach($product_images as $product_image){
$coverImage_name = $product_image->getClientOriginalName();
$upload = $product_image->move('images', $coverImage_name);
Image::create([
'book_id' => $book_id,
'cover_images' => $coverImage_name
]);
}
$preview_pages = $request->file('previewPageImage')
foreach($preview_pages as $preview_image){
$previewImage_name = $preview_image->getClientOriginalName();
$upload = $preview_image->move('images', $previewImage_name);
Image::create([
'book_id' => $book_id,
'preview_images' => $previewImage_name
]);
}
I want to use following way:
Image::create([
'book_id' => $book_id,
'cover_images' => $coverImage_name,
'preview_images' => $previewImage_name
]);
But I am stuck while using foreach loop for two different fileuploads. Any suggestions or hints.
If you are sure there will always be a 1:1 relationship between the $coverImage_name and the $previewImage_name, then you can just push them into an array, loop the array, and create your images from within.
$images = [];
$product_images = $request->file('coverPageImage');
foreach ($product_images as $idx => $product_image){
$coverImage_name = $product_image->getClientOriginalName();
$upload = $product_image->move('images', $coverImage_name);
$images[$idx]['cover_image'] = $coverImage_name;
}
$preview_pages = $request->file('previewPageImage')
foreach($preview_pages as $idx => $preview_image){
$previewImage_name = $preview_image->getClientOriginalName();
$upload = $preview_image->move('images', $previewImage_name);
$images[$idx]['preview_image'] = $previewImage_name;
}
foreach($images as $idx => $arr) {
Image::create([
'book_id' => $book_id,
'cover_images' => isset($arr['cover_image']) ? $arr['cover_image'] : null,
'preview_image' => isset($arr['preview_image']) ? $arr['preview_image'] : null
]);
}

image uploading with codeigniter

Am trying to upload an image and save the images full path in my images table but i dont know how to get the full path it out of the $this->upload->data() array this is my code below.
//assigns the user's sessioned id to the variable $user_id
$user_id = $this->session->userdata('user_id');
//sets rules for the image that is being uploaded
$config['overwrite'] = FALSE; //does not overwrite any image adds +1 instead
$config['encrypt_name'] = FALSE; //encrypts the images name
$config['remove_spaces'] = TRUE; //removes spaces from the images name
$config['file_name'] = $user_id."_0.jpg";/*gives the image a new name combination of the user's id and a number*/
$config['upload_path'] = './uploads'; // the uploaded images path
$config['allowed_types'] = 'jpg|png';/*types of image extentions allowed to be uploaded*/
$config['max_size'] = '2048';// maximum file size that can be uploaded (2MB)
if ( ! is_dir($config['upload_path']) ) /* this checks to see if the file path is wrong or does not exist.*/
die("THE UPLOAD DIRECTORY DOES NOT EXIST"); // error for invalid file path
$this->load->library('upload',$config); /* this loads codeigniters file upload library*/
//this checks for errors incase the image upload breaks a set rule.
if (! $this->upload->do_upload() ) {
echo "UPLOAD ERROR ! ".$this->upload->display_errors(); //image error
}
else {
// success message to show that the image was successfuly uploaded.
echo "THE IMAGE HAS BEEN UPLOADED : "; var_dump($this->upload->data() );
}
All I needed to do was to store the array $this->upload->data(); in a variable for example
$image_info = $this->upload->data();
and from the $image_info variable I can access the images properties like so.
$image_info['full_path'];
$image_info['file_name'];
You should be seeing in the dump for $this->upload->data() the following array:
Array
(
[file_name] => mypic.jpg
[file_type] => image/jpeg
[file_path] => /path/to/your/upload/
[full_path] => /path/to/your/upload/jpg.jpg
[raw_name] => mypic
[orig_name] => mypic.jpg
[client_name] => mypic.jpg
[file_ext] => .jpg
[file_size] => 22.2
[is_image] => 1
[image_width] => 800
[image_height] => 600
[image_type] => jpeg
[image_size_str] => width="800" height="200"
)
So you can simply use something like:
if ($uploaded_image = $this->upload->do_upload() ){
// success message to show that the image was successfuly uploaded.
echo "THE IMAGE HAS BEEN UPLOADED : ";
$full_path = $uploaded_image['full_path'];
} else {
echo "UPLOAD ERROR ! ".$this->upload->display_errors();//image error
}

error resizeing images in a loop in codeigniter

i have a problem while uploading and resizing images in a loop.
can anyone please provide me the working sample of code of codeigniter for uploading and resizing at the same time in a loop.
I want to upload and resize images uploaded from the form. There will be more than 1 images so i have to upload them in loop.
My code first uploads the image then resizes it. 1ts images is uploaded and resized correctly but during 2nd loop the image is uploaded but not resized. It throws this error:
Your server does not support the GD
function required to process this type
of image.
I have tried the clear function too
$this->image_lib->clear();
can anyone please help
Dont load image_lib multiple times. Add image_lib in autoload libs and change
$this->load->library('image_lib', $config);
to
$this->image_lib->initialize($config);
I had the same problem but this seemed to work:
// Do upload
if (! $this->upload->do_upload($image_name)) {
// return errors
return array('errors' => $this->upload->display_errors());
}
$data = $this->upload->data();
$config_manip = array(
'image_library' => 'gd2',
'source_image' => "./assets/uploads/{$data['file_name']}",
'new_image' => "./assets/uploads/thumbs/{$data['file_name']}",
'create_thumb' => true,
'thumb_marker' => '',
'maintain_ratio' => true,
'width' => 140,
'height' => 140
);
// Create thumbnail
$this->load->library('image_lib');
$this->image_lib->resize();
$this->image_lib->clear();
$this->image_lib->initialize($config_manip);
if ( ! $this->image_lib->resize()){
return array('errors' => $this->image_lib->display_errors());
}
Notice the Create Thumbnail goes:
Load Library,
Resize Image,
CLEAR,
Initialize Config
I was putting the clear after the initialize which was causing the same error you're getting.
Here is a working code from my image gallery controller. This function uploads a batch of images, resizes them and saves them to database.
public function create_photo_batch() {
$this->load->library('image_lib');
$this->load->library('upload');
// Get albums list for dropdown
$this->data['albums'] = $this->gallery_m->get_albums_list();
if(isset($_FILES['images']) && $_FILES['images']['size'] > 0) {
$album_id = $this->input->post('albumid');
$images = array();
$ret = array();
// Upload
$files = $_FILES['images'];
foreach ($files['name'] as $key => $image) {
$_FILES['images[]']['name']= $files['name'][$key];
$_FILES['images[]']['type']= $files['type'][$key];
$_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
$_FILES['images[]']['error']= $files['error'][$key];
$_FILES['images[]']['size']= $files['size'][$key];
$upload_config = array(
'allowed_types' => 'jpg|jpeg|gif|png',
'upload_path' => realpath(APPPATH . "../uploads/gallery"),
'max_size' => 5000,
'remove_spaces' => TRUE,
'file_name' => md5(time())
);
$this->upload->initialize($upload_config);
if ($this->upload->do_upload('images[]')) {
$image_data = $this->upload->data();
$images[] = $image_data['file_name'];
} else {
$this->session->set_flashdata('error', $this->upload->display_errors() );
redirect('admin/gallery/create_photo_batch');
}
}
// Resize
foreach ($images as $image) {
$resize_config = array(
'source_image' => realpath(APPPATH . '../uploads/gallery') .'/'. $image,
'new_image' => realpath(APPPATH . '../uploads/gallery/thumbs'),
'maintain_ratio' => TRUE,
'width' => 500,
'height' => 500
);
$this->image_lib->initialize($resize_config);
if ( ! $this->image_lib->resize() ) {
echo $this->image_lib->display_errors();
die;
}
$this->image_lib->clear();
}
// Save to db
foreach ($images as $image) {
$ret[] = array(
'AlbumID' => (int) $album_id,
'Url' => $image,
'IsActive' => 1
);
}
$this->gallery_m->save_images($ret);
redirect('admin/gallery/album/'.$album_id);
}
//Load view
$this->data['subview'] = 'admin/gallery/photo_upload_batch_view';
$this->load->view('admin/_layout_main', $this->data);
}
Your error message suggest that it's not the loop that is the problem, but rather that the 2nd file is of a different filetype than the 1st. And that the underlying server don't have the needed libraries (http://www.libgd.org/Main_Page) installed to handle that file type.
$config['image_library'] = 'gd2';
$config['source_image'] = './assets/upload_images/A.jpg';
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 1600;
$config['height'] = 900;
$config['new_image'] = './assets/upload_images/'.$randy;
$this->load->library('image_lib', $config);
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
I had same problem but solved these by this code.

Resources