matching file extension in the document via javascript - php

This is continued from my original question (http://stackoverflow.com/questions/10133976/getelementsbytagname-specific-links-only) which I got resolved but now facing different issue.
I'm implementing Anarchy player on my site and problem is that script stores files outside the domain root so links to them are in format like ( http: // mysite.com/mod/file/download.php?file_guid=fileID) which is fine for the player, it still plays the file but I need to separate files by type.
Look at the javascript code below, "if(o.href.match(/.mov$|.mp4$|.m4v$|.m4b$|.3gp$/i)" part, if I understand it correctly it says if file extension is .mov, .mp4, etc. than include that player. But since link is not in standard format with file name and extension it does not recognize it.
How to change that "if(o.href.match" to something that would distinguish what type of file it is?
I can pull file full name with extension in text format via PHP code and maybe wrap it in or div and that use if...div.match(...?
Link to video file is already inside div block id "video"
<div id="video">
</div>
Here is javascript:
var all = document.getElementById ( "video" ).getElementsByTagName ( "a" );
for (var i = 0, o; o = all[i]; i++) {
if(o.href.match(/\.mov$|\.mp4$|\.m4v$|\.m4b$|\.3gp$/i) && o.className!="amplink") {
Thank you so much for any suggestions.

It's not always possible to decide upon the filetype of a file just by looking at the filename. A better approach is to look at the Content-Type header (in case of an HTTP resource) or the MIME-type (which is essentially the same thing).
It's still possible to send a bad Content-Type so perhaps there is a way to identify the filetype by looking at the first few bytes? I know PNG starts with a very obvious indicator.

Related

Get file contents after pageload

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

Saving images from sources without a specific mime type

As an example, say I'm trying to download App Icons from the Google Play store for a service. Here is an example URL:
https://lh6.ggpht.com/1eVPA6Iukw-F4i5xq1ZWicaKBzmprLGw98YhdG20E-wlsHHg3PcKJqbY_fWLdJeGRw=w512-rw
There is no mime type associated with the data provided, and when the file is saved any image viewers (or at least the ones I've tried) will say the file is corrupt. They will show up in Chrome and a couple of other things, but when inspecting the data, it's clear there's simply no mime type. This is an issue, because I am further using these data streams in other scripts which require that they be recognized as a specific type. (namely PNG)
I've tried things such as:
imagepng(imagecreatefromstring($icondata), $finaldir.'/icon.png');
Where $icondata is simply a curl response for the image. This will return an error saying that the data is of an unknown format for the imagecreatefromstring function. Of course, I've also tried:
file_put_contents($finaldir.'/icon.png', $icondata);
To no avail. It creates the file, but as I said, the image is not recognized as an image in most applications and in various analyzing functions. Is there a way to specifically set the mime type of a given string of data? Or some other workaround I'm not quite seeing?
Edit: Also, to note, there is nothing wrong with the $icondata variable. I have tried manually saving the image to a file through my web browser, and the same problem arises.
I have developed a small CMS for myself and was facing the same issue. After trying a lot, I have found a solution. It is working for me and I hope you will find it useful for your project too.
Regarding the corruption of file, for Chrome user-agent, Google servers send icons as .webp format and you need a PHP library for handling images of this type. And for other user-agents (like Firefox), images are sent as PNG.
Now comparing the two URLs for a same icon in Firefox or Chrome, you will notice that image paths generated for Chrome contain -rw at the end while the same URL in Firefox doesn't contain that -rw.
Not digging very deeper, simply remove the -rw from the end of the URL and copy the image. You will get a PNG image. A hint is here for you:
<?php
$image_path = "https://lh5.ggpht.com/8PODwBXKk4L201m4IO1wifRDfbn4Q1JxNxOzj-5TXPJ85_S-vOqntLi7TsVyeFQM0w4=w300-rw"; // Firefox app on Google Play
$png_path = substr($image_path, 0, -3);
copy($png_path, 'file.png');
?>
This will save the image as PNG. Please note that I have used substr() function to remove -rw from the end. To make it precise, you may use any other way to fix that part of the path.
P.S. You may also try sending a custom user-agent (i.e. Firefox) with your CURL request to receive the PNG path so you will not need to fix it by yourself :)
You can use HttpResponse::getContentType to determine type of content you're getting from URL
This not a png, but WebP
You can use it in PHP with
imagecreatefromwebp( string $filename );
More information:
- https://developers.google.com/speed/webp/
- http://php.net/manual/function.imagecreatefromwebp.php

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
}

html5 get file path

Using html5 javascript, how do you get the file path when user select the file?
I needed the file path to use in this example case:
user upload a file, pause it(I know so far I think only mozilla can do this), and then close the browser and plan to resume the file the next day. I need to know the file path for this file..
Even if you did have a path (some browsers used to give it to you), there is no way to set the path of a input of type file.
Therefore, it is not possible to do what you want with plain JS and the DOM.
I said it wasn't possible, but now that you asked I do think there is a way, with new File API. The following steps outline what needs to be done, but have in no way been tested, and I don't expect it to work, it's just to show you the way, also global variables are bad, it's just the simplest way to show you. Here's a good page with examples on using the File API http://www.html5rocks.com/en/tutorials/file/dndfiles/
First You need an input of type file, then you can use once a user selects a file, you are given access to the File object. http://dev.w3.org/2006/webapi/FileAPI/#dfn-filereader
<input type="file" id="files" name="files[]" multiple />
<script>
var fileBlobs = [];
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. You may now read their contents
var reader = new FileReader();
for (var i = 0, f; f = files[i]; i++) {
fileBlobs.push(reader.readAsBinaryString(f));
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
Second Now you have the content as a binary string. You can use the File API to store the file locally in a way that you can access later using the FileWriter and FileSaver interfaces http://dev.w3.org/2009/dap/file-system/file-writer.html
var bb = new BlobBuilder();
bb.appendfileBlobs.(fileBlobs[0]);
window.saveAs(bb.getBlob(), "test_file");
Third You need to make an Ajax request passing that blob to the server, tracking how much of the upload is complete. http://www.w3.org/TR/XMLHttpRequest/#the-upload-attribute. It doesn't look like tracking progress can be done on the client. Your may have to poll the server for actual progress. A possible solution to know where to start an interrupted upload is to have upload ids and when you restart an upload, you ask the server how much of the file has been uploaded.
Sorry I can't provide a full answer, but this is not an easy problem. The steps I gave you should take you in the right direction.
Much like you can't submit an HTTP request in pieces over several days, you can't do it with file uploads as well. The protocol just won't allow it. Hence the entire effort is futile.
As far as I know, that isn't possible as Javascript only has access to files that were shared with it through either a file input or drag-and-drop.

PHP Link to image outside root folder [a href, not img src]

Here's my situation: Images are stored outside root folder. I can access them with an external php file (as it should be) then file_get_contents then echo then img src it then it will show perfectly.
I have thickbox installed and what I want to happen is when a user clicks on the image, it will show in the thickbox enlarged
<a href="img.jpg" class="thickbox"><img src="my_image_processing.php?img=img.jpg" />
I'm trying to create a gallery upon clicking. What happens is the thickbox shows up but the image doesn't. Instead of the image, the gibberish/garbage codes show up with black diamonds with a questionmark. I suppose this is the raw code of the image.
How can I output that as image and not raw code in
<a href> 's
ADDED: I just played around with it a bit more. When I remove the thickbox class, the a href actually works. It displays the image normally on the next page. Unforunately when I attach the thickbox classes, it shows the thickbox, but it shows the raw code
Try:
header ("Content-type: image/jpeg");
If you see the raw image data as text, probably your browser does not recognize the output as an image. You can signal the right mime type with the header line above.
It is also possible that an error occures and error messages make the image file unreadable (because instead of the headers the stream starts with an error message). In that case you should see the error message before the characters.
In your example you are using the jpg file directly, it should be something like:
<a href="my_image_processing.php?img=img.jpg" class="thickbox"><img src="my_image_processing.php?img=img.jpg" />
That is, the php page that read the hidden folder and return the image.
Thickbox recognizes the type of the resource linked by the file extension to determine, whether it is an image to be displayed, or not. It also ignores the query string when determining extension. Thus, you have the following options:
use some custom URL rewriting and make your script work eg. using URL like my_image_processing/img.jpg instead of my_image_processing.php?img=img.jpg (search for more info on "mod_rewrite"),
rewrite the code of ThickBox (or search for option parameters allowing you to change that recognition mechanism without changing the code - I did not find any), or
implement other library allowing you to implement what you need (and allows you to use the external script in a way you intended),
One thing is making Thickbox think it loads image, not a page into the frame, and the second one is - as vbence pointed - adding proper mime type to the image you return with your script: you should add appropriate header with "Content-Type" information.
EDIT:
The code responsible for displaying images begins as follows [sic!]:
var baseURL;
if(url.indexOf("?")!==-1){ //ff there is a query string involved
baseURL = url.substr(0, url.indexOf("?"));
}else{
baseURL = url;
}
var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
var urlType = baseURL.toLowerCase().match(urlString);
if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
You may wish to add another type ('php'), if you choose to modify the script yourself, but you should be aware of the consequences.
EDIT2:
If you go with the 'change plugin' option, there is some alternative (ColorBox), that makes you able to decide without the need to dig into the code, whether the *.php link should be treated as image. Just look for the photo option within the documentation (when set photo=true should behave as you would expect).
You've probably neglected the http headers for displaying an image.
header("Content-type: image/jpeg");
header("Content-Disposition: attachment;");

Categories