How to upload an image to database in php - php

I need to upload an image to database and save it inside a folder so I can display the image by giving the path to that folder. I have already coded this but there is a problem it in saving inside a folder. It saves the path to the database and correctly storing details but it dosen't save inside the folder which I have created inside my project.Folder name is also same but I cannot fix this problem. Please help me find to correct this. I've been struggling with this for a long time.
public function save()
{
$url = $this->do_upload();
//$title = $_POST["title"];
//$this->main_m->save($title, $url);
}
private function do_upload()
{
$type = explode('.', $_FILES["pic"]["name"]);
$type = strtolower($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;
return "";
}

Try change the relative path by a absolute path.
public function save()
{
$url = $this->do_upload();
//$title = $_POST["title"];
//$this->main_m->save($title, $url);
}
private function do_upload()
{
$type = explode('.', $_FILES["pic"]["name"]);
$type = strtolower($type[count($type)-1]);
$url = "/data/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;
return "";
}

Related

Manually add files in $_FILES

I need to add manually files into $_FILES, then I use this method :
public function addToFiles($key, $filename): void {
$tempName = tempnam('/tmp', 'php_files');
$originalName = basename(parse_url($filename, PHP_URL_PATH));
$rawData = file_get_contents($filename);
file_put_contents($tempName, $rawData);
$_FILES[$key]['name'][] = $originalName;
$_FILES[$key]['type'][] = mime_content_type($tempName);
$_FILES[$key]['tmp_name'][] = $tempName;
$_FILES[$key]['error'][] = 0;
$_FILES[$key]['size'][] = strlen($rawData);
}
I see temporary file in temporary directory but move_uploaded_file () return false.
What wrong with this code ?
Thank you

how to do code refactoring to reduce similar code in laravel?

Hello I am a newbie, I just started creating a project for quiz application.I have repeated code in my store and update
function,how can i reduce the duplication and write a cleaner code, any help will be appreciated
Thanks Nabeel
This is my store method
public function store(Quiz $quiz, QuestionRequest $request)
{
if($request->hasfile('image'))
{
$file=$request->file('image');
//Get File name with the extension
$fileWithExt = $file->getClientOriginalName();
//Get Just File Name
$filename = pathinfo($fileWithExt,PATHINFO_FILENAME);
//Get Just Extension
$extension = $file->getClientOriginalExtension();
//Filename to store
$nameoffile = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->move(public_path('images'),$nameoffile);
//$path = $file->storeAs('app/img/',$nameoffile);
$path = $nameoffile;
}
else
{
$path=null;
}
}
This is my update method
public function update(Quiz $quiz,QuestionRequest $request,Question $question)
{
if(is_null($question->imgpath))
{
if($request->hasfile('image'))
{
$file=$request->file('image');
//Get File name with the extension
$fileWithExt = $file->getClientOriginalName();
//Get Just File Name
$filename = pathinfo($fileWithExt,PATHINFO_FILENAME);
//Get Just Extension
$extension = $file->getClientOriginalExtension();
//Filename to store
$nameoffile = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->move(public_path('images'),$nameoffile);
$path = $nameoffile;
}
else
{
$path=null;
}
}
elseif(!empty($question->imgpath) && $request->hasfile('image'))
{
$file=$request->file('image');
$fileWithExt = $file->getClientOriginalName();
$filename = pathinfo($fileWithExt,PATHINFO_FILENAME);
$extension = $file->getClientOriginalExtension();
$nameoffile = $filename.'_'.time().'.'.$extension;
$path = $file->move(public_path('images'),$nameoffile);
$path = $nameoffile;
}
else
{
$path=$question->imgpath;
}
You can create a new trait or function in your model class and can use that in your controller . Like this
In your Quiz.php just create a new function called fileUpload()
php artisan fileUpload($data)
{
$file=$data;
//Get File name with the extension
$fileWithExt = $file->getClientOriginalName();
//Get Just File Name
$filename = pathinfo($fileWithExt,PATHINFO_FILENAME);
//Get Just Extension
$extension = $file->getClientOriginalExtension();
//Filename to store
$nameoffile = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->move(public_path('images'),$nameoffile);
$path = $nameoffile;
return $path;
}
And in your controller in store() and update() you can just do this
if(is_null($question->imgpath))
{
if($request->hasfile('image'))
{
$path = $quiz->fileUpload($request->file('image'));
}
else
{
$path=null;
}
}

Codeigniter image uploading not working in first attempt?

I'm trying to create a image upload function for my e-commerce website. This is the function I used to upload files,
Image upload function
private function upload_product_image($name, $file) {
$this->load->library('upload');
$dir = $name;
if (!is_dir('store/' . $dir)) {
mkdir('store/' . $dir, 777, true);
}
$config['upload_path'] = './store/' . $dir . '/';
$config['allowed_types'] = 'jpg|png';
$config['encrypt_name'] = TRUE;
$this->upload->initialize($config);
if (!$this->upload->do_upload($file)) {
return null;
} else {
if (is_file($config['upload_path'])) {
chmod($config['upload_path'], 777);
}
$ud = $this->upload->data();
$source = $ud['full_path'];
$destination = $ud['full_path'];
$image = imagecreatefromjpeg($source);
imagejpeg($image, $destination, 75);
return $config['upload_path'] . $ud['file_name'];
}
}
Save product
public function save_product(){
*** other code ****
$dir = date('Ymdhis');
$dir = url_title($dir, 'dash', true);
$this->upload_product_image($dir, 'add-product-image1'),
*** other code ****
}
There are couple of issues when running this function,
Image is not uploaded in first attempt ( Add new product )
But It created the product folder
If I update the product images It is working fine.
If you could show me, what is the wrong with this code It'll be really helpful.
Thank you so much

PHP Passing $_FILES and $_POST as parameters to function

I searched online for a code that does PHP image upload using ajax. I found the code attached below. The issue is that I changed few things (minor tweaks) to make it work on my server. Originally it was just a php page (not a class or function) that handles the data posted from form. I made it into class then function. I am following OOP now. I thought the best way to do things in the conversion from procedural to OOP was to pass $_FILES and $_POST to a method and inside deal with them. I think this didn't work. Look at the example and please advise on how to go forward.
function uploadImageChosen($_FILES, $_POST){
$path = "../uploads/images/";
$valid_formats = array("jpg", "png", "gif", "bmp");
$connectionInstance = new ConnectionClass();
$connectionInstance->connectToDatabase();
$imgName;
$imgURL;
$imgSize;
$imgDir = $_POST['directory'];
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$imgSize = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$imgName = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$imgName))
{
$imgURL = $path.$imgName;
$connectionInstance->query("INSERT INTO imagesupload(id, title, url, size, directory) VALUES (null, '$imgName','$imgURL', '$imgSize', '$imgDir')");
//echo "<img src='uploads/".$imgName."' class='preview'>";
}
else{
echo "failed";
}
}else{
echo "Image file size max 1 MB";
}
}else{
echo "Invalid file format..";
}
}else{
echo "Please select image..!";
}
}//end of if
}//end of function
As to the page where the class function is being called, here it is:
<?php
require_once("../classes/UploadImages.php");
$uploadInstance = new UploadImages();
$uploadInstance->uploadImageChosen($_FILES, $_POST);
//header("LOCATION:portfolio.php");
?>
Thank you very much :)
$_POST and $_FILES are superglobal arrays, they are always available, and redefining them in a function or method is a bad idea.
You can do something like this:
$uploadInstance->uploadImageChosen();
..
function uploadImageChosen(){
$path = "../uploads/images/";
$valid_formats = array("jpg", "png", "gif", "bmp");
...
$name = $_FILES['photoimg']['name'];
...
Or if you need copies in the local scope do it like this:
$uploadInstance->uploadImageChosen($_FILES, $_POST);
..
function uploadImageChosen($files, $post){
$path = "../uploads/images/";
$valid_formats = array("jpg", "png", "gif", "bmp");
...
$name = $files['photoimg']['name'];
...
Try removing $_SERVER['REQUEST_METHOD'] == "POST" from the IF-statement, and see what it does.
The script above has a problem which was not detected in error log. The problem was first presented when I instantiated the connection class. I should have created another variable that would receive the open connection for querying to work That was solved and data now present in the DB. The second problem was the JPG format was not in array of acceptable types, so I added that along with jpg (variations). This made the file actually transfer to upload folder. Thank you all for support and sorry for the inconvenience :)

Image upload takes previous temp file to upload in PHP

Here I have the problem with uploading image in PHP.
The problem is that when first time I upload the image file it works fine.
But when I am trying to upload the file second time without page refresh it takes first image name and upload it.
What is the problem and how can it be resolved?
$name = $_FILES['ImageFile']['name'];
$size = $_FILES['ImageFile']['size'];
$tmp = $_FILES['ImageFile']['tmp_name'];
$path = "public/www/uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp");
$response = '';
if(strlen($name)) {
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats)) {
if($size<(1024*1024)) {
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
if(move_uploaded_file($tmp, $path.$actual_image_name)) {
$response = "<img src='public/www/uploads/".$actual_image_name."?parm=".time()."' class='preview'>";
} else {
$response = "failed";
}
} else {
$response = "Image file size max 1 MB";
}
} else {
$response = "Invalid file format..";
}
} else {
$response = "Please select image..!";
}
Here, $response is a variable that used to get status.
Sounds like you are using some sort of AJAX to call this function.
You might need to find a way to reset the $_FILES array at the end of this function... maybe something like this would help:
$_FILES = array();
Otherwise, because there is no (apparent) page refresh happening after the file upload (as you mentioned,) I'm thinking that the $_FILES variable has no chance of being naturally reset (as would happen if you weren't using AJAX here.)

Categories