PHP saves broken image files downloaded from a URL - php

No matter which function I'm using:
copy("http:" . $imglink, "images/" . substr($imglink, 34));
//or
file_put_contents("images/" . substr($imglink, 34), file_get_contents("http:" . $imglink));
//or
file_put_contents("images/" . $productData['imagefile'], fopen($productData['imagelink'], 'r'));
the files are saved broken and almost 4 times bigger. No errors in the log,
already checked that I can manually download healthy images from the remote server through the browser. Any ideas?

Found the problem - the image filename contains space char which should be
rawurlencode($imglink)-ed before it is passed as argument

Related

Saving file to folder using file_put_contents() doesn't work

I have been working on a little PHP script that dynamically creates & saves images in a folder tmp (which already exists!) from a base64 string. This is my save.php file.
// get base-64 string from form
$filteredData = substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);
// decode string
$unencodedData = base64_decode($filteredData);
// create unique filename
$a = uniqid();
// name, location and file extension
$compfile = '/tmp/' . $a . '.png';
// save image
file_put_contents($compfile, $unencodedData);
// print image
echo '<img src="' . $compfile . '" />';
Strangely enough: It will neither create nor render the image on the page, because of the /tmp/ in my $compfile variable. When I remove it, everything works like a charm and the image is being created in the same folder.
Unfortunately, I really want the image to be created in the /tmp/ folder. Before $compfile was a randomly generated filename, and instead was called /tmp/img.png I was able to save to create an image by the name img.png and save it to the tmp.
What am I missing here?
(Thank you for your time.)
Since I guess this was the solution I'll post it as answer.
I think you want "tmp/" . $a . ".png" instead of "/tmp/" . $a . ".png". It's good practice to just always use absolute paths, so: __DIR__ . "/tmp/" . $a . ".png". This takes away any confusion.

PDFLib TET PHP: Can`t extract images

I was able to install TET (php_tet.dll) on Windows 8.1 + Xampp and I have no problems with PDF to Text, but I had no luck with image extraction.
I'm using the example "image resources.php" ( and "image_extractor.php" ) which is supposed to "print" some info about the images (x, y, width, height, alpha and e.t.c) in PDF file. Also must save/extract all available (or any) images into files (tiff, jpg).
The examples can be found here: http://goo.gl/ZeDlc0
The part with image information is working, but there is no files extracted.
I haven't got any trouble with text extraction to TXT file in the same folder.
So I'm able to write there ?
Is something wrong with my SEARCHPATH or else ?
My TRY:
The original example throws ERROR:
Error 1016 in open_document(): Couldn't open PDF file 'FontReporter.pdf' for reading (file not found)
So I changed the SEARCHPATH:
/* global option list */
$globaloptlist = "searchpath={{../data} {../../data} }";
with the location of my pdf file:
/* global option list */
$globaloptlist = "searchpath={{D:\Workshop\www\TET\data} }";
Now I have some output data via print/echo:
page 7: 208x277pt, alpha=0, beta=0 id=0, 595x750 pixel, 1x8 bit Indexed
page 7: 208x277pt, alpha=0, beta=0 id=1, 595x750 pixel, 1x8 bit Indexed
The $tet->write_image_file method returns 10 which says "I can extract TIFF file".
But no images are extracted in my pdf`s folder or anywhere around...
Somehow the images are exported in D:\workshop\xampp\apache
In the option FILENAME I need to set the ABSOLUTE path and the filename...
$path = str_replace('\\', '/', __DIR__);
$imageoptlist = $baseimageoptlist . " filename {".$path."/out/" .
$outfilebase . "_p" . $pageno . "_I" . $ti->imageid . "}";
if ($tet->write_image_file($doc, $ti->imageid, $imageoptlist) == 0){
print("Error " . $tet->get_errnum() . " in " .
$tet->get_apiname() . "(): " . $tet->get_errmsg());
}
this is exactly what I found in the TET manual, (chapter 3.9 "PHP" section):
File name handling in PHP
Unqualified file names (without any path component) and relative file names are
handled differently in Unix and Windows versions of PHP:
- PHP on Unix systems will find files without any path component in the directory
where the script is located.
- PHP on Windows will find files without any path component only in the directory
where the PHP DLL is located.
So I guess, it's expected that you have to adjust the sample slightly for your needs.

Using fopen() to write file into subdirectory

I already looked at this StackOverflow question and it didn't help (similarly titled).
I'm passing an image in from my Android application. If I type
$file = fopen('test.jpg', 'wb');
It works correctly and the image uploads; however, I want to allow for multiple uploads from android phones, so I want to randomize the name of the .jpg file so that I can save each new upload as a different name. I was trying this below:
$destination = time() + rand(1, 1000) . ".jpg";
$url_destination = "/project_images/" . $destination;
$file = fopen($url_destination, 'wb');
fwrite($file, $binary);
fclose($file);
It doesn't write the file to the server, however. I tried different variations of the URL there - with 'project_images/', '/project_images/', even trying the full URL (which the aforementioned StackOverflow post corrected me on), and I still can't get it to write.
The permissions of the project_images folder are set to allow files to be written to it. Any ideas?
Your problem is "/project_images" which is a wrong absolute path.
For it to work change it to "project_images/" or dirname(__FILE__).'/project_images/'.
For those who use XAMPP on Windows: use DIRECTORY_SEPARATOR instead /
dirname(__FILE__).DIRECTORY_SEPARATOR.'project_images'.DIRECTORY_SEPARATOR

PHP: imagemagick creates empty image with convert

I have a script that is supposed to take an image and convert it to a .jpg. This is the code that makes it happen:
$uploadDir = $_SERVER['DOCUMENT_ROOT'] . "/blogimages/";
$tempFile = ereg_replace("'", "_", basename($_FILES['newsImg']['name']));
$uploadFile = $uploadDir . $tempFile;
move_uploaded_file($_FILES['newsImg']['tmp_name'], $uploadFile);
$newPic = $uploadDir . $blogID . ".jpg";
if(file_exists($newPic)){
unlink($newPic);
}
$convertString = "$IM -strip $uploadFile $newPic";
echo "<!-- $convertString -->";
exec($convertString);
as can be seen I put the final string in an HTML comment so I can see what is being executed. What happens is that the converted image is created, but it is a 0 byte image. So no data is actually written to the file. Just to make sure convert is actually working like it normally should I copy and pasted the convert string from the html comment to a command line and it works just fine. It only seems to be having problems within the PHP exec. Any thoughts on why this might be?
I'm thinking perhaps the upload file handle isn't yet closed when you try to execute the command? That way Imagemagick would see an incomplete file.
Looking at the code I don't see how it could happen, especially since the file is moved around, but it would explain the behavior.
Start by doing some error checking on the $_FILES['newsImg']['name'] and follow it up by making sure the move_uploaded_file(...) succeeded.

Remove spaces in file names apache

1.Hi, I have a internal use only file upload script that uploads the files to a directory. When I upload something from my computer with a spcace in the name i.e example 1.zip it uploads with a space in the name thus killing the link in a email. Is it possible to make apache remove the space when its uploaded or make it a underscore?
The second problem I am having is how would I parse this to make the link an email link with the url of the file as the body of the email amd the email addy anything?
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $_FILES['file']['name'])) {
// uploaded file was moved and renamed succesfuly. Display a message.
echo "Link: " . "http://example.org/" . $_FILES["file"]["name"];
You just need to urlencode() your file name and everything is fine:
echo "Link: http://example.org/" . urlencode($_FILES["file"]["name"]);
But if you want to remove the spaces for another reason, you can use str_replace():
$replaced_name = str_replace(' ', '_', $_FILES["file"]["name"]);
rename($uploaddir . '/' . $_FILES['file']['name'], $uploaddir . '/' . $replaced_name);
# You should urlencode() it nonetheless:
echo "Link: http://example.org/" . urlencode($replaced_name);
Try:
$filename = $_FILES['file']['name'];
$filename = preg_replace("/[^a-zA-Z0-9]/", "", $filename);
//then
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $filename)) {
// uploaded file was moved and renamed succesfuly. Display a message.
echo "Link: " . "http://example.org/" . $filename;
As a side note : with the code you are using, what is happening if two files with the same name are uploaded ? If you don't do a check (like "is there a file that already has that name in $uploaddir ?") the second file will replace the first one.
That might not be something you want... is it ?
If not, to solve that (potential) problem, one solution is to always rename uploaded files, with names you control. (A simple counter would probably to the trick)
Another thing is : $_FILES["file"]["name"] is sent by the client, and, as such, can probably be forged to contains whatever someone would want. If it contains something like "../../index.php" (or something like this - you get the idea), this could allow someone to put any file they want on your server.
To prevent this from happening, you shoud be sure the file name/path used as destination of move_uploaded_file does not contain anything "dangerous". A solution could be to use basename. (see, for instance, example #2 on POST method uploads)
You might also want to check the mimetype of the uploaded file, so you don't get executables, for instance -- and you should make sure files uploaded are not executable by the webserver.

Categories