Laravel how to get a image path? - php

Hi i'm new using Laravel and i have a form with a upload file button, but this is optional on my form, if i don't want to upload an image, my app stores one by default (no-image.jpg) and this image is in my storage_path, how i can get this path and assign it to my new record?
I tried this but it doesn't work:
if($request->infopath == null){
$request->infopath = public_path() . "/infopath"."/". 'no-image.jpg';
PreguntaAbierta::create($request->all());
Session::flash('store-success','Datos agregados correctamente!');
return redirect()->route('abierta.index');
}
'SOLUTION'
I finally found a solution , although an unorthodox but it does what I want, but I doubt remains =/
On my view:
#if($pregunta->infopath == null)
<td><img src="infopath/no-image.jpg" alt="" style="width:100px"/></td>
#endif
LOL

You can use ->with
return redirect()->route('abierta.index')->with('infopath',$request->infopath);
and get this as $infopath in abierta.index
Also there is multiple option you can check here : https://laravel.com/docs/5.1/responses

You can do like this:
$input = $request->all();
$input['infopath'] = $your_image_public_path;
PreguntaAbierta::create($input);

Related

I want to upload multiple images at a time using Laravel 5.4 and php. Please guide me step wise.

I am building an android app for adding product details to the database. The need of the hour is that I have to send more than 1 image for the description of the product. I want assistance in writing a Post API using Laravel 5.4 framework which could accept the multiple images.
For Multiple Images
Use HTML like as follow on blade
<input type="file" multiple="multiple" name="eventimages[]" >
Inside Your controller use as follows
if($request->hasFile('eventimages'))
{
foreach($request->file('eventimages') as $image) {
$destinationPath = storage_path('content_images/');
$filename = $image->getClientOriginalName();
$image->move($destinationPath, $filename);
$image = new ImageModel;
$image->create_by = '1';
$image->image_name = $filename;
$result = $image->save();
}
}

php - rand() update image with the name of the previous one

I have a table CRUD that display my database.
When I upload an image in my image folder I generate a random name of numbers with that function rand()
Here is what I have coded :
My upload function
function importer_image()
{
if(isset($_FILES["image"]))
{
$extension = explode('.', $_FILES['image']['name']);
$new_name = rand() . '.' . $extension[1];
$destination = './upload/' . $new_name;
move_uploaded_file($_FILES['image']['tmp_name'], $destination);
return $new_name;
}
}
My upload php
if($_POST["operation"] == "Ajouter")
{
$image = '';
if($_FILES["image"]["name"] != '')
{
$image = importer_image();
}
The problem is then when I code the update function, the substitued image stays in my folder and the new one has a new name generated. In order to avoid this, I would like to create a condition that says if $image !='' 1/ erase the old file 2/ upload the new file and keep the same name than the deleted image.
So I'm trying to create an update php process that would 1/ delete unlink() 2/ upload the new image with the name of the previous image.
In order to delete the old image and maintain new name of image as previous, you have to take a hidden input in your form which contain your uploaded image name.
For e.g :
<input type="hidden" name="old-image" value="here is your previous image">
Now when your upload function will hit then you can get previous image name by request and can delete or maintain new image as previous.
if($_FILES['image']['name'] != '') {
$old_image = $_POST['old-image']; // get old image
$new_name = $old_image; // make new image name as previous
unlink('/upload/'.$old_image); // remove old image from folder
$destination = './upload/' . $new_name;
move_uploaded_file($_FILES['image']['tmp_name'], $destination);
return $new_name;
} else {
//if there is no image uploaded in the form then it will maintain old image
return $new_name= $_POST['old-image'];
}
Hope it will help you.
Your code to get extension works only if you have just one dot in the uploaded filename, it won't work for example on image_a.1.jpg. Use instead:
$extension = strrchr($_FILES['image']['name'],'.');
Also, using rand() for naming will eventually give you a headache when it generates the same number the second time and the uploaded image will overwrite the old one or not get saved, possibly producing error showing the user your full server save path. I'd use some hashing, like:
$new_name = md5($_FILES['image']['name'] . time());
If you need to save the file name as int, use crc32() instead of md5(). You could convert md5() result to int, but that would produce a very long int (128bit) that might not fit in your database or even PHP code.

READ empty file image in Codeigniter

which i need to update the profil user with or without user's photo profile, here my code in view
<input type="file" name="file_foto" class="form-control">
how i can read the file is empty or not, to chose when update data is with image or without image.
and how to make unlink image to delete previouse image in Codeigniter. thanks
here is my Controller
if (empty($_FILES['file_foto']['name'])) {
$data_profil = array(
'name'=>$name
);
}else{
$foto_up = $this->do_upload_image('file_foto');
$data_profil = array(
'name'=>$name,
'foto'=>$foto_up['file_name']
);
}
if($_FILES['file_foto']['name'])){
code to upload image
}
oh sory all, my problem now solve, just use this code
if (empty($_FILES['file_foto']['name']))

PHP: Properly storing image names in MySQL DB

I am storing images name inside on MySQL database. Everytime I perform an upload, I have it return a link back with the image name attached which then I extract the image name and saved to the database. I have corrections to some critical flaws but I am still facing issues of having blank spaces/ duplicate names inserted into my database even though I have established checkpoints.
How can I avoid duplication/blank spaces of file names?
Is there a better approach in storing names in DB?
Location of image inside webserver:
http://www.example.com/imageupload/uploads/medium/50038dc14afb7.jpg
Link in the browser:
http://www.example.org/imageupload/index.php?i=50038dc14afb7.jpg
PHP
<?
$images = retrieve_images();
insert_images_into_database($images);
function retrieve_images()
{
$images = explode(',', $_POST['i']);
return $images;
}
function insert_images_into_database($images)
{
if(!$images) //There were no images to return
return false;
$db = dbConn::getConnection();
foreach($images as $image)
{
$sql = "INSERT INTO `urlImage` (`image_name`) VALUES ( ? )";
$prepared = $db->prepare($sql);
$prepared->execute(array($image));
}
}
?>
First, the blank name issue can perharps be fixed by checking $_POST['i']:
if (!isset($_POST['i'])) {
echo "No image to upload!";
die();
}
Have you tried redirecting after uploading the image?
// When image is uploaded
header("Location: http://example.org/imageupload/index.php");
die();
you can change the image name at the time of upload,
rand() is the function, which return random value, so you can avoid the duplicate image name,
the date time option will return always new date time, so you can diffidently get unique image name
Ex.$imageName.rand().$extention;
OR
Ex. $date = new DateTime(now);
$date = $date->format('Y_m_d_H_i_s');
$imageName.$date.$extention;
a couple of things:
To make sure you have unique file names, use tempnam() (
http://php.net/manual/en/function.tempnam.php )
To avoid page reload issue, post the upload form to a different page, which redirects to a
different page (or the previous form page) after it finishes doing the upload.
This is unrelated to your question but your SQL prepared statement should be outside of the loop.

symfony image inside a button?

I'm trying to include an image inside a button using symfony1.4 with this code:
<?php
echo button_to(image_tag('icon.png')."button_name",'url-goes-here');
?>
But the result i get, instead of what i want is a button with "img src=path/to/the/icon.png button_name" as the value of the button. I've google'd it long enought and found nothing, so i'll try asking here.
In other words:
i'd like to find the way to generate html similar to:<button><img src=..>Text</button> but with a symfony url associated in the onclick option
How can i do it to put an image inside a button with symfony? Am i using the helpers wrong?
Thank you for your time!
You are using Symfonys button_to function incorrectly. From the documentation:
string button_to($name, $internal_uri, $options) Creates an
button tag of the given name pointing to a routed URL
As far as I can tell, the button_to function does not allow for image buttons. Instead, you will probably create the button tag yourself and use symfonys routing to output the url.
I finally created my own helper to display this kind of buttons. I know is not very efficient and flexible but works in my case. Here is the code
function image_button_to($img,$name,$uri,$options){
$sfURL = url_for($uri);
$sfIMG = image_tag($img);
if(isset($options['confirm'])){
$confirm_text = $options['confirm'];
$jsFunction = 'if(confirm(\''.$confirm_text.'\')){ return window.location=\''.$sfURL.'\';}else{return false;}';
}else{
$jsFunction = 'window.location="'.$sfURL.'";';
}
$onclick = 'onclick="'.$jsFunction.'"';
if(isset($options['title'])){
$title = 'title=\''.$options['title'].'\' ';
}else{
$title = '';
}
if(isset($options['style'])){
$style = 'style=\''.$options['style'].'\' ';
}else{
$style = '';
}
return '<button type="button" '.$onclick.$title.$style.' >'.$sfIMG." ".$name.'</button>';
}
With this function as helper, in the templates i just have to:
<?php echo image_button_to('image.png',"button_name",'module/actionUri');?>
hope this be useful for someone ;)

Categories