Get file contents after pageload - php

I have an external resource for my images let's say https://api.domain.com/api/downloads/{file_id}. The file gets downloaded after I visit that page. In this case I want to know the mimetype of the file. file_get_contents() doesn't work because the file is downloaded after I visit the page.
This means that I get HTML as output when I dump the result of file_get_contents(). I don't have any hold on how images are served to my application. So I guess I have to find a solution for this problem.
Is there a way to get the mimetype of a file after the page is loaded and it downloaded the file? If something I just wrote is not clear enough please let me know then I try to explain it further. Thanks in advance.
Some more detailed information:
I am currently creating an EML export from data from an external API from Genesys. This is pure PHP and thus I can’t make use of any client-side code like Javascript. The inline images in the body don’t show on in the EML export email body. I think this is because Genesys saves those images somewhere on their side. The image is not directly available from the URL they gave to me, because when I visit that page the page downloads a file but it is not directly served on that page.
To show the images inside the email body I want to encode them to base64 and change the src of the image to the base64 encoded image. To do so I need to know the filetype which I can’t get as described above.

Did you try with the onload property on the <img /> tag ?
<img src="w3html.gif" onload="loadImage()" width="100" height="132">
<script>
function loadImage() {
alert("Image is loaded");
}
</script>
https://www.w3schools.com/tags/ev_onload.asp
You will need to use javascript as the image is on a remote server and loaded on client side

Related

How to download file Using PHP that has delayed force download?

I am at a situation, where I need to download files from the URL, it is easy with the direct file URLs like https://somedomain.com/some-path/somefile.exe
file_put_contents( $save_file_loc, file_get_contents($url_to_download);
But what to do when you have delayed force download from the URL which actually prints HTML and how to differentiate those URL?
Example URL: https://filehippo.com/download_mozilla-firefox-64/post_download/
EDIT: On above url the file download starts using JS, as I tested with blocking JS and download did not start.
Thanks in advance for your help.
Read the html of the URL using file_get_contents
Find the URL of the file within the HTML. You'll have to visit the page and view source to locate the URL. In your example of https://filehippo.com/download_mozilla-firefox-64/post_download/ it's found in between data-qa-download-url="https://dl5.filehippo.com/367/fb9/ef3863463463b174ae36c8bf09a90145/Firefox_Installer.exe?Expires=1594425587&Signature=18ab87cedcf3464363469231db54575665668c4f6&url=https://filehippo.com/download_mozilla-firefox-64/&Filename=Firefox_Installer.exe"
As you may have noticed, the page may have pre-approved the request so it's not guaranteed to work if the host has checks using cookies or other methods.
Create a regex based on the above to extract the URL using preg_match
Then file_get_contents the URL of the file to download it.

How to paste image in chrome, then upload it to a server with PHP

I actually want to upload an image to a server.
To achieve this, i want the user just paste the image into chrome (the image is a print screen in fact), and then i post the stream to a php page, convert the stream as an image, and then upload it.
How can i achieve this web application ?
Today i have develop some differents parts :
I used this script, and i create the Upload.php page which gets the post variable and try to Create and image.
The problem i have, is that when i post the data, i only get a blob. I would like to get a base64 stream.
Can you help me ?
Thanks in advance.
I'm not sure why you are specifically looking for a "base 64 stream". If you are sending the Blob to your server via ajax, as far as your server is concerned, it's a file. Treat it no different than any other upload server-side. A Blob is a File without a name property. That's perhaps a bit overly-simplistic, but my point is that, again, this is really nothing more than a file as far as your server knows.
Assuming you are sending a multipart-encoded request, I'd like to point out that most user agents will set the filename property of the item's Content-Disposition header in the request to "blob" when the item you are uploading is a Blob instead of a file. It is possible to change this value in some browsers via the 3rd argument in FormData's append method, but I wouldn't rely on this just yet.
Also note that, if you are interested in a library that handles all of this already, I maintain, Fine Uploader which natively supports uploading images via paste in Chrome.
To answer this old question: Posting an image from clipboard with chrome is pretty much the same as posting a dropped file - except that the image/blob doesn't have the properties "name" and "lastModified".
var entry = items[i].webkitGetAsEntry();
if (!entry) entry = items[i].getAsFile();
if (entry instanceof Blob) /** CHROME pastet Bilder als Blob **/
{
entry.isFile = true;
entry.lastModifiedDate = new Date();
entry.name = ""+new Date().getTime()+"."+entry.type.split('/')[1];
}
if (entry.isFile)
{
//handle dropped file
}

Preview pdf file created with TCPDF in embed tag after Ajax call

So my application generates pdf files using TCPDF, and that works fine. That is done inside php file, called with ajax. I'm using embed tag to preview them like:
$.ajax({
url: 'create_pdf_file.php',
success: function(){
/* https://stackoverflow.com/questions/17083018/jquery-loads-cached-file-inside-ajax-success-function */
$('#pdf_placeholder embed').attr('src','output/my_file.pdf?v=' + Math.random()');
}
});
Because many users could generate my_file.pdf at the same time, there could be a case when one user will preview a file generated for another user. So my question at this point is how to force TCPDF to output directly into that tag, not using temp file
Output('my_file','I')
not working here after ajax.
There is an advice here to echo pdf directly back, but i don't know how to do that or is it possible at all. Anyway will try with success(data) to receive that like json.
Other workaround is to give session-bond file name for each user, but is using session_id() and appending to the file name is safe? Most probably I will end with generating UID for each session.
Any general advices are welcome.
You should try passing what TCPDF will produce in a way widely used in embeding images: Data Uri
Embedding Base64 Images
This however might choke browser - i haven't test this.
I would rather save pdf file on server, print filename to browser or other ID of produced file so it could be read with "success" of the ajax request. Then calmly pass proper filename to Embed element. If you wish to do it more safely you can encode it using already used session-exclusive data like session cookie or data that is assosiated with that cookie on a server. You can bond pdf file access to IP that sent request to produce it and timestamp of request that caused production.

how to send png image from server to display in browser via ajax

I have been having a hard time with what must be an incredibly normal task. I upload and save images to my web server and save the path to the file in MySQL data base (this is all working). The thing that doesn't work is fetching an image file from the server and displaying it on the page via ajax.
Originally I was trying to just retrieve the path from the database, and update an tag's src attribute with the path to the image. This was working, but this way all the images are in a folder on the server where people all have access to them. This is not good. I can only have the pictures that belong to certain users accessible by these users.
In order to restrict access to these photos I added an Apache directive on that folder, which successfully restricted access. The problem then became that I could not display the images in the browser by setting the src attribute to that path. See my post: https://serverfault.com/questions/425974/apache-deny-access-to-images-folder-but-still-able-to-display-via-img-on-site
Finally I have learned that I have to use PHP to read the image data directly from the server and send this data to the browser. I have used the file_get_contents() function, which works to convert the image file (PNG) on the server into a string. I return this string to the browser in an ajax call. The thing I can't get is: how to convert this string back into an image using JavaScript?
See this code:
$.ajax({
url: get_image.php,
success: function(image_string){
//how to load this image string from file_get_contents to the browser??
}
});
You could display a default "no access" image to users who are forbidden to access the image:
<?php
$file = $_GET['file']; // don't forget to sanitize this!
header('Content-type: image/png');
if (user_is_allowed_to_access($file)) {
readfile($file);
}
else {
readfile('some/default/file.png');
}
And, on the client side:
<img src="script.php?file=path/to/file.png" />
Alternatively, if you really really want or need to send the data via Ajax, you can Base64 encode it:
<?php
echo base64_encode(file_get_contents($file));
And place the response in an img tag using the Data URI scheme
var img = '<img src="data:image/png;base64,'+ server_reponse +'"/>';
Given that the Base64 encoded data is significantly larger than the original, you could send the raw data and encode it in the browser using a library.
Does that make sense to you?
Instead of getting get_image.php through AJAX, why not just use:
<img src="get_image.php" />
It's practically the same thing. You can just use AJAX to update the <img> dynamically.
You can't do it via ajax.
You could do something like this:
<img src="script.php?image=image_name" />
Then use JavaScript to change the query string.
You can actually embed image data inside the img tag in the browser, therefore ajax code could look like this:
$.ajax({
url: get_image.php,
success: function(image_string){
$(document.body).append("<img src='data:image/gif;base64," + base64_encode(image_string) + "' />);
}
});
Note that you will need to write this base64_encode function. Have a look at this question - the function is given there.

How do I load an image in PHP

I want code that loads an image to a PHP server and then send it to browser.
For example I want sample.php to send an image to browser once it is requested.
in other words, I want to create a PHP file that acts like a proxy for an image.
why are you doing this?
why don't deliver the image directly?
if you are trying to display a random image you may as well just redirect to the image using
header("Location: address-of-image");
for delivering the file to your clients from your server and not from its original location you can just do. however your php.ini settings need to allow external file opens
readfile("http://www.example.com/image.jpg")
correct headers are not required if you are going to display the image in an img tag,
altough i would recommend it. you should check the filetype of the image or in most cases just set an octet-stream header so the browser doesnt assume an incorrect type like text or something and tries to display binary data.
to do so just do
header("Content-type: application/octet-stream")
one more thing to consider may be setting correct headers for caching...
You need to use
$image = fopen("image.png");
Modify the headers(not sure exacly if it's correct)
headers("Content-type: image/png");
And then send the image
echo fread($image, file_size("image.png"));

Categories