Script cannot read file from directory - php

I have a script which extracts Exif data from a photo stored in a given directory and then displays the image with the exif information on a web page.
Here's the part of the script which retrieves the exif data, this example being a hard coded image:
$Image = 'original/raleighbike.JPG';
echo "$Image";
$exif = exif_read_data($Image, 0, true);
This works and the exif data is displayed.
(The 'echo' is just there to verify that the correct image is being setup for retrieval in the next part - which is where I have a problem.)
I now use the same script to fetch the exif from an image uploaded in a previous script and stored in the same directory.
The upload script sets a variable ($Image9) containing the image name and location and the exif extraction script now looks like this:
$Image = $Image9;
echo "$Image";
$exif = exif_read_data($Image, 0, true);
The problem I have is that the 'echo' prints the correct image name and location, but the exif data is empty and the error log reads:
[02-Apr-2013 18:45:29 America/Chicago] PHP Warning: exif_read_data() [<a href='function.exif-read-data'>function.exif-read-data</a>]: Unable to open file in /home2/webi8726/public_html/domain.com/sqlsidebar/displayexif.php on line 23
Line 23 is the last line in the quoted section above.
I cannot understand why the hard coded image is opened with no problem, but the image identified by the variable can't be opened - even though the variable contains the correct info and is pointing to the same file which is hard coded.
Can anyone suggest why the problem is occurring.
OK- played about some more today and this is what I find.
1 - In the script that uploads and stores the jpg I changed the variable it sets to $photo.
$photo should contain the name of the jpg and the directory it is stored in. I also set a different variable called $thumb which contains the name and location of a thumbnail of the jpg which is created and stored by the upload script.
2 - I changed the exif extraction script to use the $photo variable to create a variable called $Image which is used at various points in the script after exif extraction - for example to fetch and display the image as well store the image details in a sql database.
3 - I set some 'echo' commands to verify the contents of the variables, as well as too confirm the file exists.
This is the script code now:
$Image = $photo;
echo "$photo";
echo $Image;
echo file_exists($Image) ? 'ok' : ' image file not found';
echo file_exists($photo) ? 'ok' : ' photo file not found';
echo $thumb;
echo file_exists($thumb) ? 'ok' : ' thumb file not found';
$exif = exif_read_data($photo, 0, true);
The resulting echo string displays the following
original/raleighbike.jpg - content of variable $photo (correct)
original/raleighbike.jpg - content of variable $Image (correct)
image file not found - when checking for the file in $Image (incorrect, file does exist)
photo file not found - when checking for the file in $photo (incorrect, file does exist)
thumb file not found - when checking for the file in $thumb (incorrect, file does exist)
thumbnail/thumb_raleighbike.jpg
So it would appear that if a file is hardcoded the script is able to physically locate it, but if a file/s are specified as variables, the script cannot find them.
Has anyone any ideas as to why this might happen - I surely can't be the only one to ever experience this issue ;-(

Related

PHP echo uploaded image content

I'm trying to echo an image content from an uploaded file with this code:
<?php
$imgContent = addslashes(file_get_contents($_FILES['image']['tmp_name']));
header("Content-type: image/png");
echo $imgContent;
?>
But it just shows an small empty square. I must upload and fetch a BLOB field from mysql to show on the browser, but it's not saving correctly.
As commented by Lars Stegelitz and RiggsFolly, I corrupted the file by adding addslashes on the file content. By removing it I could see the image being returned back.
I wroted that simple script just to test if I getting the image content correctly. In the real code I'm checking the file type.

PHP image don't upload to server

I am having a problem in getting a image uploading to the server (first I convert it to .png and resize it):
In functions.php
function imageUploadedResize($source, $target,$nWidth, $nHeight)
{
$sourceImg = Imagecreatefromstring(file_get_contents($source));
if ($sourceImg === false)
{
return false;
}
$width = imagesx($sourceImg);
$height = imagesy($sourceImg);
$targetImg = imagecreatetruecolor($nWidth, $nHeight);
imagecopyresized($targetImg, $sourceImg, 0, 0, 0, 0, $nWidth,$nHeight,$width, $height);
imagedestroy($sourceImg);
imagepng($targetImg, $target);
imagedestroy($targetImg);
}
In uploadtoServer.php
if(isset($_POST["fileToUpload"]))
{
$target_dir = "img/data/";
$fn = $_FILES['fileToUpload']['tmp_name'];
$newFileName = mysqli_insert_id($link).".png";
header('Content-type: image/png');
imageUploadedResize($fn, $target_dir.$newFileName, 45,60);
}
If I change $fn to a static image like "https://pbs.twimg.com/profile_images/54789364/JPG-logo-highres.jpg" it works so I guess I am having a problem in $fn. Any thoughts what can it be?
Part 1:
Form input
As Johnathan mentioned, you're checking isset($_POST["fileToUpload"]) when a file upload form will supply the value in the $_FILES array. So you need to change your reference from $_POST to $_FILES otherwise it will always return false.
Edit: As your comment states you are getting 100% false, you should use a more specific qualifier such as if($_FILES['fileToUpload']['error'] == 0) .
Your HTML form submitting the data needs to be enctype="multipart/form-data" otherwise your server will not collect anything file shaped from your form. HTML forms also need to be set in the POST method.
Part 2
File storage:
Your references to file system storage for the image, such as $target_dir = "img/data/"; are relative, so that means that the value of $target_dir needs to be the child of the file that is calling that script block.
It would probably help you a lot to use Absolute file system references, typically (but not exclusively) using $_SERVER['DOCUMENT_ROOT']."/img/data";
This example will store data in the www.your-web-site.com/img/data location.
Part 3
Displaying the image.
You have a header setting content type to image/png but you do not actually output the image, instead saving it to the file reference mentioned above. If you want to output the image to the browser, you need to skip saving it so:
imagepng($targetImg, NULL);
This will then output the image in $targetImg straight out to the browser. At the moment you appear to be saving it but not displaying it, despite setting the image header which means that any output to browser is expected to be an image content.
Some systems have a restriction on freshly uploaded data and prevent that data being handled too freely, to get around this it is advisable to use move_upladed_file to save the file to a "proper" destination and then access it to output to the browser.
Further Notes:
You should be checking $_FILES['fileToUpload']['error'] before acting on the file, as this will tell you if a file is present. using isset is a bad (very ambiguous) idea on this as the array can still be set, even if the file has not been uploaded.
You should use PHP error logging. You should not use error supression #.

how to retrieve blob file to image in php?

I am using plupload to upload file in my php based website, with large file uploading the file becomes a file named 'blob' without any suffix. I know this is a binary file that contains the raw data, question is how to retrieve the data and save it back as an image file, say .png/.jpg or etc? I tried:
$imageString = file_get_contents($blogPath);
$image = imagecreatefromstring($imageString);
But it gives me some 'Data is not in recognized format...' error, any thoughts? Thanks in advance.
Your call to imagecreatefromstring() should work just fine if your file_get_contents() is working. Use var_dump($imageString) to verify. Did you mean to name your variable $blobPath instead of $blogPath?
You don't need to load this image though. Just rename the file.
rename($blobPath, 'new/path/here.jpg');
http://php.net/manual/en/function.rename.php
I am storing the uploaded image files for late use, like attaching them to posts or products(my site is e-commerce CMS). I figured that my image file didn't get fully uploaded to the server, the image before upload is 6mb, but the blob file is just 192kb, so my best guess is that what get uploaded is just a chunk instead of the whole package, and yet that brought up another question: how should I take all the pieces and assemble them as one complete image file? As mentioned earlier, I am using plupload for js plugin and php as backend, the backend php code to handle uploading goes like this:
move_uploaded_file($_FILES["file"]["tmp_name"], $uploadFolder . $_FILES["file"]["name"]);
Instead of doing that you should do this to display image to the browser
<img src="data:image/jpeg;base64,'.base64_encode( $row['blob_image'] ).'"/>
I'm not sure what imagecreatefromsting does or how it encodes the image.
I looked at the documentation for that function; you're missing:
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data); <--- this operation

uniquely name images that are output to browser with php script

I use wordpress cms. I allow selective people to upload image. I have a script that resizes it and outputs resized image back to the browser where they can right click and save it. Here is the relevant part of the code. If needed I will put up the whole code. The script works and puts the resized image in the browser nicely.
header('Content-type: image/jpeg');
ob_start();
imagejpeg($resized, null, 100);
echo '<img src="data:image/jpeg;base64,' . base64_encode(ob_get_clean()) . '">';
imagedestroy($resized);
ISSUE : The form has just one upload field. I only allow images to be resized and saved one-by-one. Since all these resized images generated by the script has a same name index, an issue arises, which is when the visitor goes to save his image in windows the first time, say in a folder, it is saved as index.jpeg but when he goes to save images after that he is prompted to replace index.jpeg image. Because "these people " are not tech savvy so they usually replace the image end up wasting my time solving the case. So I would like these resized images to have unique name generated either by uniqid() or time().
WHAT I TRIED / AM TRYING : I am confused to what phpfunction I should be using here together with time() so that I could create a new filename each time a resized images is generated. In order to first set a variable, i tried to use basename() function like this, but it wont work.
$new_filename = basename($resized); echo '<br>' .$new_filename. '<br>';
Obviously it throws a warning:basename() expects parameter 1 to be string. I tried that and realized that in this case the variable $resized is a resource not a string. I am still crawling through threads for imagejpeg() at php.net in search of a solution, have not found any resource yet.
Bottomline question : how do I set or get a variable for resized file so
that I can manipulate it alongwith time() to create new names each
time.
FINAL UPDATE : #CBroe, pointed out that this is not possible so I am off to looking for an alternative.

Resize image directly from Rackspace Cloud Files 'object' without downloading?

I have moved my images to Rackspace Cloud Files and am using their PHP API. I am trying to do the following:
Get an image from my "originals" container
Resize it, sharpen it, etc.
Save the resized image to the "thumbs" container
My problem is with #2. I was hoping to resize without having to copy the original to my server first (since the images are large and I'd like to resize dynamically), but can't figure out how. This is what I have so far (not much):
$container = $conn->get_container("originals");
$obj = $container->get_object("example.jpg");
$img = $obj->read();
Part of the problem is I don't fully understand what is being returned by the read() function. I know $img contains the object's "data" (which I was able to print out as gibberish), but it is neither a file nor a url nor an image resource, so I don't know how to deal with it. Is it possible to convert $img into an image resource somehow? I tried imagecreatefromjpeg($img) but that didn't work.
Thanks!
First, you cannot resize an image without loading it into memory. Unless the remote server offers some "resize my image for me, here are the parameters" API, you have to load the image in your script to manipulate it. So you'll have to copy the file from the CloudFiles container to your server, manipulate it, then send it back into storage.
The data you receive from $obj->read() is the image data. That is the file. It doesn't have a file name and it's not saved on the hard disk, but it is the entire file. To load this into gd to manipulate it, you can use imagecreatefromstring. That's analogous to using, for example, imagecreatefrompng, only that imagecreatefrompng wants to read a file from the file system by itself, while imagecreatefromstring just accepts the data that you have already loaded into memory.
You can try to dump the content of the $img variable into a writable file as per the below:
<?php
$filename = 'modifiedImage.jpg';
/*
* 'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate
* the file to zero length. If the file does not exist, attempt to create it.
*/
$handle = fopen($filename, 'w+');
// Write $img to the opened\created file.
if (fwrite($handle, $img) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote to file ($filename)";
fclose($handle);
?>
More details:
http://www.php.net/manual/en/function.fopen.php
http://www.php.net/manual/en/function.fwrite.php
Edit:
You might also want to double check the type of data returned by the read() function, because if the data is not a jpg image, if it's for example a png, the extension of the file needs to be changed accordingly.

Categories