Home > Software engineering >  how to upload jpegs with their metadata to mysql column
how to upload jpegs with their metadata to mysql column

Time:12-16

I was trying to write a PHP code that uploads all images to mysql db and shows the images metadata in columns. in my code it uploads the images but does not show the metadata. for example I tried to insert the width of the image, I made a column for that and when I upload the image the width is always 0. can someone check my code and help me find a solution for than?

<?php 
// Include the database configuration file 
include_once 'dbconfig.php'; 

if(isset($_POST['submit'])){
    // File upload configuration 
    $targetDir = "C:\\xampp\\htdocs\\uploaded\\"; 
    $allowTypes = array('jpg','png','jpeg','gif'); 

    $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = ''; 
    $fileNames = array_filter($_FILES['files']['name']); 
    
    if(!empty($fileNames)){
    
        function getExif( $filename, $key1, $key2) {
            $width = 0;
            $allowedFiletypes = array("jpg","jpeg","tif","tiff");
            if(in_array(strtolower(substr($filename, -3)),$allowedFiletypes)) {
                if(exif_read_data($filename) == true) {
                    $exif = exif_read_data($filename, 0, true);

                    foreach ($exif as $key => $section) {
                        foreach ($section as $name => $val) {
                            if($key === $key1 AND $name === $key2){
                                $width = $val;
                            }
                        }
                    }
                }
                    return $width;
            } else {
                print "filetype not supported";
            }
        }

        $key1 = "IFD0";
        $key2 = "ImageWidth";

        foreach($_FILES['files']['name'] as $key=>$val){
            // File upload path 
            $fileName = basename($_FILES['files']['name'][$key]); 
            $width = getExif( $fileName, $key1, $key2);

            $targetFilePath = $targetDir . $fileName; 
            // Check whether file type is valid 
            $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION); 
            if(in_array($fileType, $allowTypes)){
                // Upload file to server 
                if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFilePath)){ 
                    // Image db insert sql 
                    $insertValuesSQL .= "('".$fileName."', NOW(), '".$width."'),"; 
                }else{ 
                    $errorUpload .= $_FILES['files']['name'][$key].' | '; 
                } 
            }else{ 
                $errorUploadType .= $_FILES['files']['name'][$key].' | '; 
            } 
        }
        
        // Error message 
        $errorUpload = !empty($errorUpload)?'Upload Error: '.trim($errorUpload, ' | '):''; 
        $errorUploadType = !empty($errorUploadType)?'File Type Error: '.trim($errorUploadType, '    | '):''; 
        $errorMsg =      !empty($errorUpload)?'<br/>'.$errorUpload.'<br/>'.$errorUploadType:'<br/>'.$errorUploadType; 

        if(!empty($insertValuesSQL)){
            $insertValuesSQL = trim($insertValuesSQL, ','); 
            
            // Insert image file name into database 
            $insert = $db->query("INSERT INTO images(file_name, uploaded_on, image_width) VALUES      $insertValuesSQL"); 
            if($insert){ 
                $statusMsg = "Files are uploaded successfully.".$errorMsg; 
            }else{ 
                $statusMsg = "Sorry, there was an error uploading your file."; 
            } 
        }else{ 
            $statusMsg = "Upload failed! ".$errorMsg; 
        } 
    }else{ 
        $statusMsg = 'Please select a file to upload.'; 
    }
}

?>
    <form action="upload1.php" method="post" enctype="multipart/form-data">
        Select Image Files to Upload:
        <input type="file" name="files[]" multiple >
        <input type="submit" name="submit" value="UPLOAD">
    </form>

my goal is to upload images with all their metadata

CodePudding user response:

You are incorrectly passing in the filename rather than the file itself - and a name does not have any EXIF data attributes. One other issue that you will encounter with EXIF perhaps is that not every camera adds the same details so there ar eno guarantees that a particular property will exist within a particular section so forking the processing logic around that is needed.

You can simplify the getExif function using array_key_exists rather than the nested loops which can be prone to issues. For example, a bare-bones piece of PHP without the SQL portion.

The getExif below either returns exactly the item requested or the entire exif response which can be used to fork the logic as mentioned. In testing I found just one image that contained both the section and required parameter ($key1,$key2- renamed for clarity)

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title></title>
    </head>
    <body>
        <form method="post" enctype="multipart/form-data">
            Select Image Files to Upload:
            <input type="file" name="files[]" multiple />
            <input type="submit" />
        </form> 
        <?php

            error_reporting( E_ALL );
            ini_set( 'display_errors', 1 );
            
            
            
            function uploaderror( $error ){ 
                switch( $error ) { 
                    case UPLOAD_ERR_INI_SIZE: return "The uploaded file exceeds the upload_max_filesize directive in php.ini"; 
                    case UPLOAD_ERR_FORM_SIZE: return "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; 
                    case UPLOAD_ERR_PARTIAL: return "The uploaded file was only partially uploaded"; 
                    case UPLOAD_ERR_NO_FILE: return "No file was uploaded"; 
                    case UPLOAD_ERR_NO_TMP_DIR: return "Missing a temporary folder"; 
                    case UPLOAD_ERR_CANT_WRITE: return "Failed to write file to disk"; 
                    case UPLOAD_ERR_EXTENSION: return "File upload stopped by extension"; 
                    default: return "Unknown upload error";
                }
            }
            function getExif( $filename, $section=false, $param=false ) {
                if( $section & $param ){
                    
                    $exif = @exif_read_data( $filename,0, true );
                    if( array_key_exists( $section, $exif ) && array_key_exists( $param, $exif[ $section ] ) )return $exif[ $section ][ $param ];
                    
                    return $exif;
                }
                return false;
            }

            
            
            
            if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_FILES['files'] ) ){
                
                $exts = array('jpg','jpeg','tif','tiff');
                $files=(object)$_FILES['files'];
                
                foreach( $files->name as $i => $void ){
                    $name = $files->name[$i];
                    $size = $files->size[$i];
                    $type = $files->type[$i];
                    $tmp  = $files->tmp_name[$i];
                    $error= $files->error[$i];
                    $errors=array();
                    
                    if( !$error == UPLOAD_ERR_OK )$errors[]=uploaderror( $error );
                    
                    if( empty( $errors )){
                        
                        $ext = strtolower( pathinfo( $name, PATHINFO_EXTENSION ) );
                        $targetDir = __DIR__ . '/uploads';
                        $targetFile = sprintf('%s/%s',$targetDir,$name);
                        
                        if( in_array( $ext, $exts )){
                            
                            /*
                                What you wish to find in the exif...
                            */
                            $section = "IFD0";
                            $param = "ImageWidth";
                            /*
                                find and process...
                            */
                            $result = getExif( $tmp, $section, $param );
                            
                            
                            if( !is_numeric( $result ) or is_array( $result ) ){
                                $errors[]=sprintf('Unable to locate property "%s" within designated section: "%s"',$param,$section);
                                $errors[]=$result;
                            }else{
                                
                                # just to show the data...
                                printf('<pre>%s</pre>',print_r( $result, true ) );
                                
                                
                                /*
                                    save file to disk...
                                */
                                $status=move_uploaded_file( $tmp, $targetFile );
                                if( !$status )$errors[]='Failed to save file';
                                
                                /*
                                    sql... use a Prepared Statement!
                                */
                                $sql='insert into images( `file_name`, `uploaded_on`, `image_width` ) values (?,?,?)';
                                /*
                                $stmt=$db->prepare($sql);
                                $args=array(
                                    $name,
                                    date('Y-m-d H:i:s'),
                                    $result
                                );
                                $stmt->bind_param('sss',...$args);
                                $stmt->execute();
                                */
                            }
                        }else{
                            $errors[]='unknown file extension: '.$ext;
                        }
                    }
                    
                    if( !empty( $errors ) )printf('<pre>%s</pre>',print_r($errors,true));
                }
            }
        ?>
    </body>
</html>
  •  Tags:  
  • php
  • Related