PHP EXIF data not working - php

I am new to PHP, and adapting a script from http://www.techrepublic.com/article/create-a-dynamic-photo-gallery-with-php-in-three-steps/ which generates a table of images in a directory along with some accompanying EXIF data. The only problem is that the code has not display the EXIF data. This happens with even the original source code. My best guess of what is happening is that something in the original source code is old and outdated, and no longer supported by modern PHP. I have made sure that my server has EXIF enabled.
Here's the code:
<table>
<?php
// define directory path
$dir = "path/to/directory";
// iterate through files
// look for JPEGs
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (preg_match("/.jpg/", $file)) {
// read EXIF headers
$exif = exif_read_data($file, 0, true);
// get image
echo "<tr><td rowspan='3'><img src='$dir/$file'></td>";
// get file name
echo "<th>Title</th><td>" . $exif['FILE']['FileName'] . "</td></tr>";
// get timestamp
echo "<tr><th>Year</th><td>" . $exif['IFD0']['DateTime'] . "</td></tr>";
// get image dimensions
echo "<tr><th>Description</th><td>" . $exif['IFD0']['Comments'] . "</td></tr>";
}
}
closedir($dh);
}
}
?>
</table>
EDIT: I also get the following error logs:
20160815T185355: benxd.me/art/gallery.php
PHP Warning: exif_read_data(): Unable to open file in /hermes/walnaweb01a/b893/pow.hdemoras/htdocs/benxd/art/gallery.php on line 21
PHP Warning: exif_read_data(): Unable to open file in /hermes/walnaweb01a/b893/pow.hdemoras/htdocs/benxd/art/gallery.php on line 21
PHP Warning: exif_read_data(): Unable to open file in /hermes/walnaweb01a/b893/pow.hdemoras/htdocs/benxd/art/gallery.php on line 21
PHP Warning: exif_read_data(): Unable to open file in /hermes/walnaweb01a/b893/pow.hdemoras/htdocs/benxd/art/gal
In my code line 21 is $exif = exif_read_data($file, 0, true);

Try explicitly adding the full path and the list of sections:
$exif = exif_read_data($dir . $file, "FILE,COMPUTED,ANY_TAG,IFD0,THUMBNAIL,COMMENT,EXIF", true);
Source: http://php.net/manual/en/function.exif-read-data.php

I spent weeks with this problem, so in the end I decided to create a library to extract the metadata (Exif, XMP, GPS...) from a PNG in PHP, 100% native, I hope it helps. :) PNGMetadata

Related

Read php file located in zip archive

I have been trying to read a PHP file inside a ZIP archive. I have coded the following code, which can read text documents and echo without errors, but when I tested it with a PHP file, nothing appear. So what can I do to read the PHP file without extracting?
<?php
$zip = zip_open("test.zip");
$filename= "test.php";
if (is_resource($zip))
{
while ($zip_entry = zip_read($zip))
{
if (zip_entry_open($zip, $zip_entry) && zip_entry_name($zip_entry) == $filename)
{
echo "Name: " . zip_entry_name($zip_entry) . "<br />";
echo "<p>";
echo "File Contents:<br/>";
$contents = zip_entry_read($zip_entry);
echo "$contents<br />";
zip_entry_close($zip_entry);
}
}
zip_close($zip);
}
Thanks in advance!
There aren't a lot of resources out there for using the default zip_read() php function, but this https://github.com/Ne-Lexa/php-zip library makes using zip files in php a breeze, you should check it out.
You can use stream wrappers to read a file directly from within a zip, in one line, without extracting anything to disk. For example:
$str = file_get_contents('zip://test.zip#test.php');

Second Zip file throwing Invalid or unitialized Zip Object

I am trying to unarchive a zip file that was inside another zip file to get to the xml file that is in the second zip file.
The big challenge with this file is that the files inside the zip file will always be different and therefore unknow. So I created a function to put the list of the archived archives into a text list. Then use this list to unarchive each file and extract the information that is needed from the xml file that is inside the second zip file.
Here is my code so far.
//Set the date
$day = date("mdY");
echo $day."<br>";
//URL to download file from for updating the prescription table
//$url = "ftp://public.nlm.nih.gov/nlmdata/.dailymed/dm_spl_daily_update_".$day.".zip";
$url = "ftp://public.nlm.nih.gov/nlmdata/.dailymed/dm_spl_daily_update_09152016.zip";
//Saving the file on the server.
file_put_contents("Prescription_update.zip", fopen($url, 'r'));
//unzip the downloaded file
$zip = new ZipArchive;
if($zip->open('Prescription_update.zip')){
$path = getcwd() . "/update/";
$path = str_replace("\\","/",$path);
//echo $path;
$zip->extractTo($path);
$zip->close();
print 'ok<br>';
} else {
print 'Failed';
}
// integer starts at 0 before counting
$i = 0;
$dir = '/update/prescription/';
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
$i++;
}
}
// prints out how many were in the directory need this for the loop later
echo "There were $i files<br>";
$dh = opendir($dir);
$files = array();
while (false !== ($filename = readdir($dh))) {
$files[] = $filename." \r\n";
}
//Created a list of files in the update/prescription folder
file_put_contents("list.txt", $files);
/*
* Creating a loop here to ready the names and extract the
* XML file from the zipped files that are in the update/prescription folder
*
*/
$ii = 2;
$fileName = new SplFileObject('list.txt');
$fileName->seek($ii);
echo $fileName."<br>"; //return the first file name from list.txt
$zip = new ZipArchive;
$zipObj = getcwd()."/update/prescription/".$fileName;
$zipObj = str_replace("\\","/", $zipObj);
echo $zipObj."<br>";
if($zip->open($zipObj)){
$path = getcwd() . "/update/prescription/tmp/";
$path = str_replace("\\","/",$path);
mkdir($path);
echo $path;
$zip->extractTo($path);
$zip->close();
print 'ok<br>';
} else {
print 'Failed';
}
Can't figure out why the second ZipArchive::extractTo: is throwing the error. I thought it may have been a path problem. I so I did the second string replacement hoping that would clear it up but it did not. So, throwing up my hands and asking for a second set of eyes on this one.
UPDATE ERROR LOG ENTRY
[18-Sep-2016 02:24:24 America/Chicago] PHP 1. {main}() C:\emr-wamp\www\interface\weno\update_prescription_drug_table.php:0
[18-Sep-2016 02:24:24 America/Chicago] PHP 2. ZipArchive->extractTo() C:\emr-wamp\www\interface\weno\update_prescription_drug_table.php:76
[18-Sep-2016 02:24:24 America/Chicago] PHP Warning: ZipArchive::close(): Invalid or unitialized Zip object in C:\emr-wamp\www\interface\weno\update_prescription_drug_table.php on line 77
[18-Sep-2016 02:24:24 America/Chicago] PHP Stack trace:
[18-Sep-2016 02:24:24 America/Chicago] PHP 1. {main}() C:\emr-wamp\www\interface\weno\update_prescription_drug_table.php:0
[18-Sep-2016 02:24:24 America/Chicago] PHP 2. ZipArchive->close() C:\emr-wamp\www\interface\weno\update_prescription_drug_table.php:77
I was going to vote to delete this question but I thought it would be better to leave it over the long run.
The answer is
How to get PHP ZipArchive to work with variable
It seems that the whole name cannot be subbed as a variable. But if you sub part of the name it is allowed.
$zipObj = getcwd()."/update/prescription/".$fileName;
It has to be subbed like
$z->open("update/".$r.".zip"){
//do something here
}

move_uploaded_file() fails to open stream due to invalid argument - PHP

I have this code to move my uploaded file to a specific directory:
if (isset($_FILES["image"]["name"])){
if (!is_dir('pf/' . $uid)) {
mkdir('pf/' . $uid);
$large_image_location = "pf/" . $uid;
}else {
$large_image_location = "pf/" . $uid;
}
chmod ($large_image_location, 0777);
move_uploaded_file("$userfile_tmp", "$large_image_location/$userfile_tmp");
}
However that gives the following error:
( ! ) Warning: move_uploaded_file(pf/BfyhieniKJGGqTNm/C:\wamp\tmp\phpF08A.tmp) [function.move-uploaded-file]: failed to open stream: Invalid argument in C:\wamp\www\mingle\upload_dp.php on line 26
Any help on how to sort this out would be greatly appreciated!
This is 90% of your woes:
move_uploaded_file("$userfile_tmp", "$large_image_location/$userfile_tmp");
You using the moved to path at the beginning of the upload path. Try:
move_uploaded_file("$userfile_tmp", "$large_image_location/".$_FILES['image']['name']);
That should work better.
The error itself is pretty clear, pf/BfyhieniKJGGqTNm/C:\wamp\tmp\phpF08A.tmp is not a valid filename.
Don't change the contents of $_FILES[n]['tmp_name'] (or $userfile_tmp for that matter), since it will always contain the full path to the uploaded file.

Opening a directory through php code

I am making a page on which i have to show thumb images, which later on will show in Light Box control.
For this i have to open the images folder, to get images. I use the following code for opening directory:
$handle = opendir('images')
But this code gives lot of errors, unable to open directory.
Instead when i use this code, given below, The whole page works fine, images are shown as thumbs and also in lightbox.
$handle = opendir('.')
Please any body, tell me how can i open a folder "images" placed in the same directory as my page.
You need to do this with opendir in this way:
<?php
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?>
As told at : http://www.php.net/manual/en/function.opendir.php
Or you will may be interested in using scandir. That is much more simpler:
<?php
$dir = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);
print_r($files1);
print_r($files2);
?>
As told here: http://www.php.net/manual/en/function.scandir.php
Try out the glob method, it automatically opens the directory handler for you.
http://php.net/manual/en/function.glob.php
$handle = glob("images/*");
I also recommend you do a check for the right file type to prevent loading unnecessary items (if any).

can someone help me fix my code?

I have this code I been working on but I'm having a hard time for it to work. I did one but it only works in php 5.3 and I realized my host only supports php 5.0! do I was trying to see if I could get it to work on my sever correctly, I'm just lost and tired lol
Ol, sorry stackoverflow is a new thing for me. Not sure how to think of it. As a forum or a place to post a question... hmmm, I'm sorry for being rude with my method of asking.
I was wondering i you could give me some guidance on how to properly insert directory structures with how i written this code. I wasn't sure how to tell the PHP where to upload my files and whatnot, I got some help from a friend who helped me sort out some of my bugs, but I'm still lost with dealing with the mkdir and link, unlink functions. Is this how I am suppose to refer to my diretories?
I know php 5.3 uses the _ DIR _ and php 5.0 use dirname(_ _ FILE_ _), I have tried both and I get the same errors. My files are set to 0777 for testing purposes. What could be the problem with it now wanting to write and move my uploaded file?
} elseif ( (file_exists("\\uploads\\{$username}\\images\\banner\\{$filename}")) || (file_exists("\\uploads\\{$username}\\images\\banner\\thumbs\\{$filename}")) ) {
$errors['img_fileexists'] = true;
}
if (! empty($errors)) {
unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
}
// Create thumbnail
if (empty($errors)) {
// Make directory if it doesn't exist
if (!is_dir("\\uploads\\{$username}\\images\\banner\\thumbs\\")) {
// Take directory and break it down into folders
$dir = "uploads\\{$username}\\images\\banner\\thumbs";
$folders = explode("\\", $dir);
// Create directory, adding folders as necessary as we go (ignore mkdir() errors, we'll check existance of full dir in a sec)
$dirTmp = '';
foreach ($folders as $fldr) {
if ($dirTmp != '') { $dirTmp .= "\\"; }
$dirTmp .= $fldr;
mkdir("\\".$dirTmp); //ignoring errors deliberately!
}
// Check again whether it exists
if (!is_dir("\\uploads\\$username\\images\\banner\\thumbs\\")) {
$errors['move_source'] = true;
unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
}
}
if (empty($errors)) {
// Move uploaded file to final destination
if (! move_uploaded_file($_FILES[IMG_FIELD_NAME]['tmp_name'], "/uploads/$username/images/banner/$filename")) {
$errors['move_source'] = true;
unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
} else {
// Create thumbnail in new dir
if (! make_thumb("/uploads/$username/images/banner/$filename", "/uploads/$username/images/banner/thumbs/$filename")) {
$errors['thumb'] = true;
unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
}
}
}
}
// Record in database
if (empty($errors)) {
// Find existing record and delete existing images
$sql = "SELECT `bannerORIGINAL`, `bannerTHUMB` FROM `agent_settings` WHERE (`agent_id`={$user_id}) LIMIT 1";
$result = mysql_query($sql);
if (!$result) {
unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>");
}
$numResults = mysql_num_rows($result);
if ($numResults == 1) {
$row = mysql_fetch_assoc($result);
// Delete old files
unlink("/uploads/$username/images/banner/" . $row['bannerORIGINAL']); //delete OLD source file
unlink("/uploads/$username/images/banner/thumbs/" . $row['bannerTHUMB']); //delete OLD thumbnail file
}
// Update/create record with new images
if ($numResults == 1) {
$sql = "INSERT INTO `agent_settings` (`agent_id`, `bannerORIGINAL`, `bannerTHUMB`) VALUES ({$user_id}, '/uploads/$username/images/banner/$filename', '/uploads/$username/images/banner/thumbs/$filename')";
} else {
$sql = "UPDATE `agent_settings` SET `bannerORIGINAL`='/uploads/$username/images/banner/$filename', `bannerTHUMB`='/uploads/$username/images/banner/thumbs/$filename' WHERE (`agent_id`={$user_id})";
}
$result = mysql_query($sql);
if (!$result) {
unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>");
}
}
// Print success message and how the thumbnail image created
if (empty($errors)) {
echo "<p>Thumbnail created Successfully!</p>\n";
echo "<img src=\"/uploads/$username/images/banner/thumbs/$filename\" alt=\"New image thumbnail\" />\n";
echo "<br />\n";
}
}
I get the following errors:
Warning: move_uploaded_file(./uploads/saiyanz2k/images/banner/azumanga-wall.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/services/webdata/phpupload/phpVoIEQj' to './uploads/saiyanz2k/images/banner/azumanga-wall.jpg' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
One way is to check from within your code whether a certain command/function is available for use. You can use the function_exists function for that eg:
if (function_exists('date_default_timezone_set'))
{
date_default_timezone_set("GMT");
}
else
{
echo 'date_default_timezone_set is not supported....';
}
Ahh! I'm sorry, didn't mean to vent my frustration on you guys. But I have been at this for hours now it seems.
Like i mentioned this code works but since my server is picky I can't user the 5.3 syntax I coded. This is my attempt to make it work on the 5.0 php my server has.
In particular I think there is something wrong with the mkdir() and the unlink() functions.
if you go to www.helixagent.com log in with test/test then in the url go to /upload2.php then you will see the errors its throwing at me.
well, it works perfect if i use 5.3 and DIR but since I'm on 5.0 i tried a different method
the errors i get are
Warning: move_uploaded_file(./uploads/saiyanz2k/images/banner/azumanga-wall.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/services/webdata/phpupload/phpVoIEQj' to './uploads/saiyanz2k/images/banner/azumanga-wall.jpg' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
It looks like you don't have access to the folder (or file)
/uploads/$username/images/banner/$filename
which could be because of a basedir restriction on the host (e.g. you may not leve the parent directory /services/webdata/) or just a missing permission in the os.
Try to (temporary) set permission of /uploads/ to 777 or execute the script from console to see if you have a basedir restriction.
Take a closer look at the paths in the error messages:
./uploads/saiyanz2k/images/banner/azumanga-wall.jpg
/services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php
The destination is a relative path, most likely relative to upload2.php's directory. The one relative path I see is the line:
// Take directory and break it down into folders
$dir = "uploads\\{$username}\\images\\banner\\thumbs";
Which should probably be:
// Take directory and break it down into folders
$dir = "\\uploads\\{$username}\\images\\banner\\thumbs";
Actually, it should be
$dir = "/uploads/{$username}/images/banner/thumbs";
since PHP supports using a forward slash as directory separator on all platforms, while the backslash is only supported on MS platforms.

Categories