Remote uploading MULTIPLE images - php

Okay, I have a question guys. I want to remote upload (copy an image from a site to my server) MULTIPLE images by putting links into a TEXTAREA and hitting submit. I just don't know how to make this possible with multiple images.
I am able to make it with an single image using the copy(); function, but not for multiple entries in a TEXTAREA.
I also want to limit the remote uploading feature up to 30 remote links and one image should not exceed 10MB - But I don't know how to start. I heard cURL is able to make this and I also heard that file_get_contents(); with file_put_contents(); can make a similar thing, but I still cannot figure out how to do it myself.
Help anyone? :)

You can use the same procedure as you do now with a single image, but do it in a loop.
$lines = explode("\n", $_POST['textarea']);
if(count($lines) > 30) {
die('Too many files');
}
foreach($lines as $line) {
$srcfile = trim($line);
//copy $srcfile here
//check size of the file with filesize()
}

You need to parse the URLs out of the textarea. You could with this PHP side with a regular expression.
You could then examine the parsed URLs and array_slice() the first 30, or error if more than 30.
You'd then need to copy the files from the remote server. You could inspect the Content-Length header to ensure the file is under 10mb. You could get just the headers using HEAD instead of GET.

I am not familiar with PHP but I suggest the following:
Solving the multiple files upload issue:
splitting the content in the text area by the carriage return
then iterate them to get image
preserve the size of each file in a variable, but how to get the size?
you can do exec (system) call to know the file size (this requires a full image download but its the most convenient way ), or you can make use of Content-Length header value, if the content length is more than 10 MG then skip it and move to the next item.
How to download the image?
use the file put content but make sure to put the encoding as binary encoding to preserve the content type.

Related

Read multiple image files using php readfile

I am trying to read multiple image files from a folder (.htaccess protected) and display in a HTML page using php readfile().
The problem is I can see only the first image is read and the next is not shown in the browser. The code is as below
<?php
$image1 = 'files/com_download\256\50\www\res\icon\android\icon-36-ldpi.png';
$image2 = 'files/com_download\256\50\www\res\icon\android\icon-48-mdpi.png';
$imginfo = getimagesize($image1);
header("Content-type: ".$imginfo['mime']);
readfile($image1);
$imginfo = getimagesize($image2);
header("Content-type: ".$imginfo['mime']);
readfile($image2);
?>
I could see the first image 'icon-36-ldpi.png' successfully read and displayed in the browser and the second image is not read and not displayed in the browser.
Am I missing something? Any advice please.
Sorry if I am doing stupid but the requirement is to read multiple image files and render in the browser like a grid view. I cannot use img tag because of security reasons.
You can't dump both images out at once. Why not make two images in your html so the browser makes two calls to your script. Then use a GET param to pass the filename you want to display.
---Edit---
Important Security Note
There is an attack vector which you open up when doing soething like this. Someone could easily view your source html and change the parameter to get your image script to output any file they want. They could even use "../../" to go up directories and search for well known files that exist. e.g. "../../../wp_config.php". Now the attacker has your wordpress database credentials. The correct way to prevent against this is to always validate the input parameter properly. For example, only output if the file name ends with ".jpg"

base64 Pic Upload and Crop Situation PHP

I am trying to take a pic upload from a mobile device to a server. We are building with PhoneGap (Javascript), so we are having turn it into a string in order to send it to the server. I am having problems once I receive it, to turn it back into a readable image file.
Simply put, I need to take a string and a file name sent to me, decode it, convert it into a .png, then crop it into a circular image.
This is what I have going on currently
if (isset($_POST['file']))
{
//Result variable
$result = false;
$pic = base64_decode($_POST['file']);
$filename = $_POST['filename'];
if (strlen($pic) > 9 )
{
$fh = fopen("/var/www/pics/events/".$filename, 'w') or die("can't open file");
fwrite($fh, $pic);
fclose($fh);
}
}
I think I can get the rest of the code to work if I can figure out what I am doing wrong here that makes it not save properly as a image file? The file uploads correctly, but it stores with out an extension, and when I point to it in my browser, it comes up like it is supposed to be an image file, but never displays the image. That little broken picture icon with the colored shapes is what I get when I direct to it's location.
Do I need to be aware of what image type is being sent during this process at all? How is it knowing if it is a .gif, .jpg/jpeg, .png, etc...?
Thanks in advance for any help!
Nathan
For Security reasons you should sanitize the file name to prevent directory traversal.
On a brighter note, make sure the file is saved with the proper extension; if you are already saving with the correct extension you could have an encoding issue from the app.
If neither of the previous possibilities are the case make sure that your String Size does not exceed the maximum POST size limit in your php.ini; if that is the case increase the size limit.

Image creation using php

Am trying to create a video clip using .jpg images and ffmpeg, am creating .jpg images as below:
$str=$_REQUEST['data_array'];//gets the base64 encoded image data;
$count =$_REQUEST['count'];//gets number of images i've to create;
$edited_str=substr($str,23,strlen($str)-1);//
$edited_str=base64_decode($edited_str);
$f=fopen("Images/temp".$count.".jpg","w");//am creating temp.jpg file
fwrite($f,$edited_str);//placing my decoded data into file
fclose($f);
are the images am creating above different from normal .jpg images?
This line:
$edited_str=substr($str,23,strlen($str)-1);
makes it different. If this is the full base64 sting of the file, then this cuts it up and corrupts it. Maybe you are adding some stuff on the front.
If you are just removing stuff from the front that was added, then it should be the same as the original file that was encoded with base64.
If you want to get the information this way from another page, I suggest using $_POST as opposed to $_REQUEST for a number of reasons.
EDIT: I wouldn't say video manipulation in php is impossible. I think there is even a toolkit... here's one:
http://phpvideotoolkit.sourceforge.net/
which states:
It can perform video format conversion, extract video frames into separate image files, and assemble a video stream from a set of separate video images.
Haven't tested it, but plan to try it out one day.
EDIT2: On the php site, there were some issues that you could try, but to help more, there needs to be more information. Check with a file directly to make sure it's being sent and decrypted properly.
I haven't got to test any of these yet.
One piece of advice was for large files use:
$decodedstring=base64_decode(chunk_split($encodedstring));
Another was if you use javascript canvas.toDataURL() then you need to convert spaces back to pluses:
$encodedData = str_replace(' ','+',$encodedData);
$decocedData = base64_decode($encodedData);
http://php.net/manual/en/function.base64-decode.php

Why is php rename() corrupting my file?

I am using plupload to do an upload of multiple files to my server. Using this, there is a parameter 'url : 'upload.php'. upload.php catches the files as they are received, and might recombine them if they get chunked. Once the full file is received, it sends a response back to the original page, displaying a green checkbox icon.
I have added some code to this page, after all the main code to manipulate the photos I have uploaded. My plan is to create three copies of my full size image, lg, med, and small. I got this part working, but then decided to first rename the original file to match my naming scheme.
I now get a corrupted renamed file, and thus my three smaller images also get corrupted.
//get the original file info
$filepath = $_SERVER['DOCUMENT_ROOT'].'/uploads/';
$filepathinfo = pathinfo($filepath.$fileName);//fileName is used previously in the file
//rename original file to a unique name
$finding_id = 'xyz';
$file_name_new = uniqid($client_id . '-' . $finding_id . '-', true); //doesn't include extension
//rename($filepath.$fileName, $filepath.$file_name_new.'.'.$ext);
//copy($filepath.$fileName, $filepath.$file_name_new.'.'.$ext);
As is, I get my one file, or how ever many I uploaded, byte size matches original exactly, and name stays the same (except for removal of certain characters).
If I uncomment only the rename function, I actually get two files. The byte sizes total the original photo. The larger file displays with a section of gray at the bottom. The smaller file doesn't display at all.
If I uncomment only the copy function, I get an exact renamed copy of my original file, my original file, and another file, the same size and corruption as the larger file doing a rename.
Any ideas? Seems like it should be pretty straightforward.
if the file was currently uploaded by HTTP POST use move_uploaded_file
if you fopen() somewhere in this request the same file make sure to call fclose()
I forgot I had the chunking feature turned on. Must have turned it on to test something. For whatever reason, when the script was running the last chunk of the file hadn't been fully appended yet. Thanks for all the input anyway!
Are you writing to the file yourself? If so, the problem might be that you're missing a call to fflush or fclose. (The last chunk of the file not getting written and the file no longer being there when PHP gets round to writing it. This shouldn't happen if you're using Linux or some other Unix, but I could envisage it on Windows.)

How to display an Image from a mysql blob

I am trying to display an image from a MySQL blob field. I have tried a few different things and none of them seem to work.
I have tried:
header("Content-type: $type"); img src = $blobData;
header("Content-type: $type"); echo($blobData);
<?php
header("Content-type: $type");
echo $blobData;
?>
This code looks perfectly OK. However, I heard a similar complain from another person and I was able to troubleshoot it by assuring that:
The php script does not output any extra character before or after sending the binary image data.
The php script is saved as a pure ASCII text file, not as a Unicode/UTF-8 encoded file. The Unicode/UTF-8 encoded PHP files might include a signature as the first bytes. These bytes will be invisible in your text editor but server will send these few extra bytes to the browser before the JPEG/GIF/PNG data. The browser will therefore find the wrong signature in the beginning of data. To workaround, create a blank text file in notepad, paste in the php code and save the file in ANSI encoding.
Another option you might consider (assuming you are on Apache):
Create an .htaccess file with a mod_rewrite for all image extensions (png, jpg, gif).
Have it redirect to a php script that looks up the image requested in the DB. If it is there, it echos out the header and BLOG. If it isn't there, it returns a standard 404.
This way you can have:
<img src="adorablepuppy.jpg" />
Which then gets redirected ala:
RewriteEngine on
RewriteRule \.(gif|jpg|png)$ imagelookup.php
This script does a query for the image, which (obviously) assumes that the requested image has a unique key that matches the filename in the URL:
$url = $_SERVER['REQUEST_URI'];
$url_parts = explode("/", $url);
$image_name = array_pop($url_parts);
Now you have just the image filename. Do the query (which I shall leave up to you, along with any validation methods and checks for real files at the address, etc.).
If it comes up with results:
header('Content-type: image/jpeg');
header('Content-Disposition: inline; filename="adorablepuppy.jpg"');
print($image_blog);
otherwise:
header("HTTP/1.0 404 Not Found");
FYI: I have no idea if this would be bad in terms of performance. But it would allow you to do what I think you want, which is output the image as though it were a flat image file on the server using a simple image element. I'm inclined to agree that BLOBs are not the best way to go, but this does avoid any cross-browser issues.
I believe that the issue that you are encountering is an issue with encoding. This resource claims that you can use the print function.
Just get the image from the database. And print it using the correct headers.
$image = mysql_fetch_array(...)
header("Content-type: image/jpeg"); // change it to the right extension
print $image['data'];
For performance reasons... this is not advisable. There are several reasons to put images in databases but the most common are:
a) keeping them indexed (duh!)
You can do this by storing the images flat on the server and just indexing the image filename.
b) keeping the image hidden/protected
Flickr and alike still store the images flat on the server and use a different approach. They generate a URL thats hard to find.
This link points to a protected image on my account. You can still access it once you know the correct URL. Try it!
farm2.static - a farm optimized for delivering static content
1399 - perhaps the server
862145282 - my username
bf83f25865_b - the image
In order to find all my secret images any user can hard hit Flickr with the above address and change the last part. But it would take ages and the user would probably be blocked for hammering the server with thousands of 404s.
That said there is little reason to store images on BLOBs.
Edit:Just a link pointing to someone that explained much better than I did why BLOB is not the way to go when storing images.

Categories