Save image from URL without form (Symfony 3) - image

I want to save an image (from URL) and relocate it to another folder without creating a form, into a controller. How can I realize it?
Download image inside Controller -> relocate it to another folder -> save image name into my database (in an existing table).

Your question is broad and you don't specify if you are using Doctrine DBAL and ORM and what exactly your problem is, so I will assume that you do use them and you are aware how to inject entity manager inside a controller action.
First you have to download the image and save the image:
$content = file_get_contents("http://example.com/image.jpg");
//Store in the filesystem.
$fp = fopen("/location/to/save/image.jpg", "w");
fwrite($fp, $content);
fclose($fp);
Then save the path into the database:
$imageEntity->setPath('image.jpg');
$entityManager->flush($imageEntity);

Related

Protect Images from being public laravel 5

i have seen certain techniques to protect images like to show them only to authenticated users. one example is
how-to-protect-image-from-public-view-in-laravel
It tells us only about 1 image. what if we want to retrieve multiple private images and show them to authenticated users?. What is the most appropriate way?. we cannot generate a link to storage directory right?
Save the images in your storage folder which isn't publicly accessible. Then create a route to generate the image based on the parameter, which could be the image name or path. Wrap this route with the auth middleware. Display the image content with appropriate headers in the controller method for the route based on its parameters.
Edit : Check this out to give you an idea.
Sample route
Route::get('securedimage/{name}', 'SecuredImageController#show');
Sample controller method
public function show($name)
{
// check if the image with name exists in the folder that you store them
// If the image doesn't exist then display dummy image or return nothing
$imagePath = storage_path('/upload/' . $name);
return Image::make($imagePath)->response();
}
Then you can access images like so
<img src="http://example.com/securedimage/ball.jpg">
<img src="http://example.com/securedimage/topsecret.jpg">

Showing a default Image in a CakePHP application

I am working in a CakePHP application, where I am using HTML helper's image() function to show images. What I want, if it gets the image in the given path, then it will show the image, otherwise, it'll show a default image. I have that "default" image, but I don't understand where/how to define it.
Thanks
Extend the HTML helper and add the logic to the image method and override the called image with your default image if the originally requested image does not exist.
index.ctp file code
<?php
$MyImage = $post['Post']['image0']; // image0 is my db field
if (file_exists("img/uploads/posts/".$MyImage))
$MyImage1 ="/img/uploads/posts/".$MyImage;
else
$MyImage1 = "/img/uploads/posts/no-image.jpg";
echo $this->Html->image($MyImage1);
?>
Note : My post's images are stored in app/webroot/img/posts folder(default image is also in this folder.)

CodeIgniter retrieve image from secret folder

I have create private folder in application folder: application/private/username, I'm uploading images here with ajax, that works, but how can I retrieve that image with ajax, and display it in img tag. First problem is that http://example.com/application/private/useraname/img.jpg is protected, I can't access it through out url in browser, how to display an image. Just advice, I wanna write code on my own.
This is part of function(that is part of controller) that grabs image:
$filepath = 'path to image';
header("Content-type: image/jpeg");
if (file_exists($filepath)) {
$img_handle = imagecreatefromjpeg($filepath) or die("");
echo $img_handle;
ImageJpeg($img_handle);
}
But how to get this image with ajax?
You might want to create a PHP file that would get the filename eg thumb.php?src=img.jpg and inside that file, you load the image from that path and display it. This way the path of the images are not exposed to the user.

Codeigniter instance and external library object: authentification

I will try to be as clear as possible to explain my problem. If not, tell me !
Mywebapp is based on Codeigniter. In it, I did a controller in order to show images uploaded by the users. By this way, the images can only be seen by members or authorized people and are not public like in facebook for example (image addresses are just hashed but are public).
I also use the mpdf library to generate a pdf from the content of a web page. To use it, I have in the third party directory the mpdf library. To be able to use it with my formatting, I put in the library directory (in application directory) my mpdf library (just to be able to use it from different controller). I have a pdf controller which is called from the view where I want to generate the pdf.
So the process is : I call a function of the pdf controller from my view. In this function, I call a function of my mpdf library which create a mpdf object (the third party class) and generate the pdf.
The generation of the pdf works great. The only I had is for the images. I explain. In my html document, the image are embedded like that :
<img src="http:localhost/www/myapp/library/image/hashed_name_of_the_image" alt="" />
The image function of the library controller retrieve the image and shows it. But in this function, I can protect or not the access to run it. For example, to force to be a logged user to see an image (if($this->session->userdata(‘logged’) == true)).
If there is no restriction, the generated pdf contains the images. Cool :).
But if I put a restriction, it doesn't. I understand that the mpdf object is the one which is asking to image function to show the image. So the verification failed.
I tried to use a config parameter on the CI instance object before I call the pdf function. For example, set to true a "pdf_conversion" and the conversion finished, set it back to false.
But it doesn't work. When I check the value in the image function, it's still false... It's like the config value is not change for all object but only for th pdf object which has changed it.
Is there a way to do what I want to do ??? With config parameter or anything else !!! I think I misunderstood something but don't know what !
thanks by advance for answers
Bastien
You problem is that then the library "calls" the image function, it is not logged in. So your controller code denies access.
There are two things you can do:
Move the code that generates/gets the image form the controller into a new library. then call that library from the controller and from the PDF library. This is the preferred way.
In the "image" action, find a way to check if the request is coming from the PDF library. Best guess is to look for something in the HTTP headers the PDF library sends. Anyway this is not very secure since HTTP headers can be "faked".
OFF TOPIC: Is there a reason you server the image from a controller action instead of by directly referencing the image file?
CLARIFICATION ON SOLUTION 1
So you'll have a library image.php that looks like this
class Image {
...
function get_image($hash){
[code for getting the image here]
}
...
}
In the controller:
function image($hash) {
$this->load->library('image');
if (if($this->session->userdata(‘logged’) == true)) {
$image = $this->image->get_image($hash);
[send it to the browser]
}
}
In the PDF library
function export($hash) {
$ci =& get_instace();
$ci->load->library('image');
[do pdf stuff]
$image = $ci->image->get_image($hash);
$this->add_image($image);
[do more pdf stuff]
}
This is the idea, the actual details of the implementation are up to you.

JQuery Ajax call for PDF file download

My question is similar to Download and open pdf file using Ajax
But not exactly the same , the reason I want an JQuery ajax is that my file is being generated dynamically from the data which would be fetched from the same page.
So basically I have a Json Object which needs to be sent to the server which would dynamically generate a file and send it back to the browser.
I would not like to use query strings on an anchor with my Json object stringyfied ,
as I think it would be a potential threat as query strings have character restrictions ( am I right here ?).
Please let me know If my workflow is right or I can achieve the same thing thing using a different flow.
You should not use AJAX to download files. This doesn't work. This being said you are left with 2 options:
action link and query string parameters or if the download must be trigerred at some specific javascript event you could also set the window.location.href to the action that is supposed to generate the PDF file and pass query string parameters to it.
or if you are afraid that you have lots of data to pass to the controller action that will generate the PDF to download you use a <form> with method="POST" and inside you use hidden fields to store as much parameters and data as you like:
#using (Html.BeginForm("download", "home"))
{
... hidden fields containing values that need to be sent to the server
<input type="submit" value="Download PDF" />
}
Instead of making one more ajax call in your page you can use anchor tag and php force download to perform pdf download
HTML
Download pdf here
PHP
<?php
$fullPath = $_GET['fileSource'];
if($fullPath) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
header("Content-type: application/pdf"); // add here more headers for diff. extensions
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
if($fsize) {//checking if file size exist
header("Content-length: $fsize");
}
readfile($fullPath);
exit;
}
?>
I am checking for file size because if you load pdf from CDN cloudfront, you won`t get the size of document which forces the document to download in 0kb, To avoid this i am checking with this condition
if($fsize) {//checking if file size exist
header("Content-length: $fsize");
}
I too was struggling with this problem, above code worked for me I hope it helps
I have a very sure answer. You can't download PDF file while using the ajax request to server. So instead of that you should use html actionlink. for example
#Html.ActionLink("Convert Data into PDF", "PDFView", null, new { #class= "btn btn-info" });
Above code will generate a link button and you can access Action Method of controller. Also you can use any technique to return PDF file from controller for example you can return PDF file using FileResult class.

Resources