PHP: Rename file before upload

2019-06-12 14:41发布

问题:

I'm trying to rename each file before uploading to Amazon S3.

I am trying to use this exact method of which was answered by @Silvertiger: PHP - upload and overwrite a file (or upload and rename it)?

If exists, rename to a random name although somehow it doesn't work.

Here is the upload post Parameter from the Amazon S3 Class:

public static function getHttpUploadPostParams($bucket, $uriPrefix = '', $acl = self::ACL_PRIVATE, $lifetime = 3600,
    $maxFileSize = 5242880, $successRedirect = "201", $amzHeaders = array(), $headers = array(), $flashVars = false)
    {
        // Create policy object
        $policy = new stdClass;
        $policy->expiration = gmdate('Y-m-d\TH:i:s\Z', (time() + $lifetime));
        $policy->conditions = array();
        $obj = new stdClass; $obj->bucket = $bucket; array_push($policy->conditions, $obj);
        $obj = new stdClass; $obj->acl = $acl; array_push($policy->conditions, $obj);

        $obj = new stdClass; // 200 for non-redirect uploads
        if (is_numeric($successRedirect) && in_array((int)$successRedirect, array(200, 201)))
            $obj->success_action_status = (string)$successRedirect;
        else // URL
            $obj->success_action_redirect = $successRedirect;
        array_push($policy->conditions, $obj);

        if ($acl !== self::ACL_PUBLIC_READ)
            array_push($policy->conditions, array('eq', '$acl', $acl));

        array_push($policy->conditions, array('starts-with', '$key', $uriPrefix));
        if ($flashVars) array_push($policy->conditions, array('starts-with', '$Filename', ''));
        foreach (array_keys($headers) as $headerKey)
            array_push($policy->conditions, array('starts-with', '$'.$headerKey, ''));
        foreach ($amzHeaders as $headerKey => $headerVal)
        {
            $obj = new stdClass;
            $obj->{$headerKey} = (string)$headerVal;
            array_push($policy->conditions, $obj);
        }
        array_push($policy->conditions, array('content-length-range', 0, $maxFileSize));
        $policy = base64_encode(str_replace('\/', '/', json_encode($policy)));

        // Create parameters
        $params = new stdClass;
        $params->AWSAccessKeyId = self::$__accessKey;
        $params->key = $uriPrefix.'${filename}';
        $params->acl = $acl;
        $params->policy = $policy; unset($policy);
        $params->signature = self::__getHash($params->policy);
        if (is_numeric($successRedirect) && in_array((int)$successRedirect, array(200, 201)))
            $params->success_action_status = (string)$successRedirect;
        else
            $params->success_action_redirect = $successRedirect;
        foreach ($headers as $headerKey => $headerVal) $params->{$headerKey} = (string)$headerVal;
        foreach ($amzHeaders as $headerKey => $headerVal) $params->{$headerKey} = (string)$headerVal;
        return $params;
    }

Here is @Silvertiger's method:

// this assumes that the upload form calls the form file field "myupload"
$name  = $_FILES['myupload']['name'];
$type  = $_FILES['myupload']['type'];
$size  = $_FILES['myupload']['size'];
$tmp   = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
    // echo "The file $filename exists";
    // This will overwrite even if the file exists
    move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way

This is my upload form:

    <form method="post" action="<?php echo $uploadURL; ?>" enctype="multipart/form-data">
<?php
    foreach ($params as $p => $v)
        echo "        <input type=\"hidden\" name=\"{$p}\" value=\"{$v}\" />\n";
?>
        <input type="file" name="file" />&#160;<input type="submit" value="Upload" />
    </form>

And this is the Input info:

public static function inputFile($file, $md5sum = true)
    {
        if (!file_exists($file) || !is_file($file) || !is_readable($file))
        {
            self::__triggerError('S3::inputFile(): Unable to open input file: '.$file, __FILE__, __LINE__);
            return false;
        }
        return array('file' => $file, 'size' => filesize($file), 'md5sum' => $md5sum !== false ?
        (is_string($md5sum) ? $md5sum : base64_encode(md5_file($file, true))) : '');
    }

回答1:

You can do your renaming at this point in your code:

move_uploaded_file($tmp, $filelocation);

The $filelocation can be changed to whatever you want and the uploaded file will be renamed to that path.

Edit: The S3::getHttpUploadPostParams method always uses the file name from the upload to create the S3 resource. To change that you have to copy the method but change this line:

$params->key = $uriPrefix.'${filename}';

The '${filename} must be changed to a path of your choosing.



回答2:

Replace this:

// Create parameters
$params = new stdClass;
$params->AWSAccessKeyId = self::$__accessKey;
$params->key = $uriPrefix.'${filename}';

with this:

function rand_string( $length ) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  

            $size = strlen( $chars );
            for( $i = 0; $i < $length; $i++ ) {
                $str .= $chars[ rand( 0, $size - 1 ) ];
            }

            return $str;
        }       

        // Create parameters
        $params = new stdClass;
        $params->AWSAccessKeyId = self::$__accessKey;
        $params->key = $uriPrefix.rand_string(5).'${filename}';


回答3:

You can easily put this code.. 100 percent working.

<?php
$file=$_FILES['file']['name'];
$path ="upload/".$file;
$ext=pathinfo($path,PATHINFO_EXTENSION);
$name=pathinfo($path,PATHINFO_FILENAME);
if(file_exists($path))
{
    echo "File alredy exists .So name is changed automatically & moved";
    $path1="upload/";
    $new_name=$path1.$name.rand(1,500).".".$ext;
    move_uploaded_file($_FILES['file']['tmp_name'],$new_name);
}
else
{
echo"uploaded Sucessfully without any change";
move_uploaded_file($_FILES['file']['tmp_name'],$path);
}
?>