PHP: Get file extension not working on uploads to S3

后端 未结 12 638
我寻月下人不归
我寻月下人不归 2020-12-06 17:49

I am using the Amazon S3 API to upload files and I am changing the name of the file each time I upload.

So for example:

Dog.png > 3Sf5f.png

Now I got

相关标签:
12条回答
  • 2020-12-06 18:38

    You need to first find out what the original extension is and not rename the entire file. So keep the extension and rename de file name.

    Assuming you have image name in $image_name:

    $image_name = "image.png";
    $random_string = "random";
    
    list($filename,$fileext) = explode(".",$image_name);
    $new_name = $random_string.'.'.$fileext;
    rename($image_name,$new_name);  
    
    0 讨论(0)
  • 2020-12-06 18:39

    A simple solution to re-name a file and compute the extension:

    $fileName = 'myRandomFile.jpg';
    
    // separate the '.'-separated parts of the file name
    $parts = explode( '.', $fileName );
    
    // Solution will not work, if no extension is present
    assert( 1 < count( $parts ) );
    
    // keep the extension and drop the last part
    $extension = $parts[ count( $parts ) - 1 ];
    unset( $parts[ count( $parts ) - 1 ] );
    
    // finally, form the new file name
    $newFileName = md5( 'someSeedHere' + implode( '.', $parts )) . '.' . $extension;
    
    echo $extension             // outputs jpg
       . ' - ' 
       . $newFileName           // outputs cfcd208495d565ef66e7dff9f98764da.jpg
       ;
    

    Note, that md5() is always 32 bytes long and non unique regarding the computed value. For for many practical instances, it's unique enough.

    Addendum

    Additionally, you may use this solution to trace variable changes:

    abstract class CSTReportDelegate {
    
        abstract public function emitVariableChange( $variableName, $oldValue, $newValue );
        abstract public function emitVariableSetNew( $variableName, $newValue );
    
    }
    
    class CSTSimpleReportDelegate extends CSTReportDelegate {
    
        public function emitVariableChange( $variableName, $oldValue, $newValue ) {
            echo '<br />[global/change] '. $variableName . ' : ' . print_r( $oldValue, true ) . ' &rarr; ' . print_r( $newValue, true );
        }
    
        public function emitVariableSetNew( $variableName, $newValue ) {
            echo '<br />[global/init] '. $variableName . '   &rarr; ' . print_r( $newValue, TRUE );
        }
    
    }
    
    
    class CSysTracer {
    
        static protected 
            $reportDelegate;
    
        static private 
            $globalState = array();
    
        static private  
            $traceableGlobals = array();
    
        static private 
            $globalTraceEnabled = FALSE;
    
        const 
            DEFAULT_TICK_AMOUNT = 1;
    
        static public 
        function setReportDelegate( CSTReportDelegate $aDelegate ) {
            self::$reportDelegate = $aDelegate;
        }
    
    
        static public 
        function start( $tickAmount = self::DEFAULT_TICK_AMOUNT ) {
    
            register_tick_function ( array( 'CSysTracer', 'handleTick' ) );
    
        }
    
    
        static public 
        function stop() {
    
            unregister_tick_function( array( 'CSysTracer', 'handleTick' ) );
    
        }
    
        static public 
        function evalAndTrace( $someStatement ) {
    
            declare( ticks = 1 ); {
                self::start();
                eval( $someStatement );
                self::stop();
            }
        }
    
        static public 
        function addTraceableGlobal( $varName ) {
    
            if ( is_array( $varName )) {
                foreach( $varName as $singleName ) {
                    self::addTraceableGlobal( $singleName ); 
                }
                return;
            }
    
            self::$traceableGlobals[ $varName ] = $varName;
    
        }
    
        static public 
        function removeTraceableGlobal( $varName ) {
            unset( self::$traceableGlobals[ $varName ] );   
        }
    
        /**
         * Main function called at each tick. Calls those functions, which
         * really perform the checks.
         * 
         */
        static public 
        function handleTick( ) {
    
            if ( TRUE === self::$globalTraceEnabled ) { 
                self::traceGlobalVariable();
            }
    
        }
    
        static public 
        function enableGlobalsTrace() {
            self::$globalTraceEnabled = TRUE;   
        }
    
    
        static public 
        function disableGlobalsTrace() {
            self::$globalTraceEnabled = FALSE;  
        }
    
        static public 
        function traceGlobalVariable( ) {
    
            foreach( self::$traceableGlobals as $aVarname ) {
    
                if ( ! isset( $GLOBALS[ $aVarname ] )) {
                    continue;
                }
    
                if ( ! isset( self::$globalState[ $aVarname ] ) ) {
    
                    self::$reportDelegate->emitVariableSetNew( $aVarname, $GLOBALS[ $aVarname ] );
                    self::$globalState[ $aVarname ] = $GLOBALS[ $aVarname ];
                    continue;
                }
    
               if ( self::$globalState[ $aVarname ] !== $GLOBALS[ $aVarname ]) {
    
                 self::$reportDelegate->emitVariableChange( $aVarname, self::$globalState[ $aVarname ], $GLOBALS[ $aVarname ] );
    
               }
    
               self::$globalState[ $aVarname ] = $GLOBALS[ $aVarname ];
    
            }
    
        }
    
    }
    

    A sample use case:

    ini_set("display_errors", TRUE);
    error_reporting(E_ALL);
    
    require_once( dirname( __FILE__ ) . '/CStatementTracer.inc.php' );
    
    /* Ticks make it easy to have a function called for every line of PHP
     *  code. We can use this to track the state of a variable throughout
     * the execution of a script.
     */
    
    
    
    CSysTracer::addTraceableGlobal( array( 'foo', 'bar' ));
    
    CSysTracer::setReportDelegate( new CSTSimpleReportDelegate() ); 
    CSysTracer::enableGlobalsTrace();
    
    CSysTracer::start(); 
    declare( ticks = 1 );
    
       //
       // At this point, tracing is enabled. 
       // Add your code or call your functions/methods here
       //
    
    CSysTracer::stop();
    
    0 讨论(0)
  • 2020-12-06 18:43

    if you're uploading images try this

    $dim = getimagesize($file);
    $type = $dim[2];
    if( $type == IMAGETYPE_JPEG ) $ext=".jpg"; 
    if( $type == IMAGETYPE_GIF ) $ext=".gif"; 
    if( $type == IMAGETYPE_PNG ) $ext=".png";
    
    $params->key = rand_string(5).$ext;
    
    0 讨论(0)
  • 2020-12-06 18:45

    I think something as simple as below should work to extract file extension from the file-name:

    function getFileExtension($fileName)
    {
        $ext = '';
        if(strpos($fileName, ".") !== false)
        {
            $ext = end(explode(".", $fileName));
        }
        return $ext;
    }
    
    0 讨论(0)
  • 2020-12-06 18:49

    Untested, but simple enough to work:

    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    

    will return the extension part (without the '.')

    0 讨论(0)
  • 2020-12-06 18:49

    How about this?

    $temp = rand_string(5).'${filename}';         //should be 3Sf5fDog.png
    $ext = pathinfo($temp, PATHINFO_EXTENSION); //should be .png
    $temp2 = rand_string(5) . $ext;             //should be 4D47a.png
    
    0 讨论(0)
提交回复
热议问题