How to change name of uploaded file in php? [closed]

ⅰ亾dé卋堺 提交于 2019-12-23 06:57:57

问题


I have this code to upload jpg files. I need to rename the file that someone uploads to newtexture.jpg'.

<?php
$demo_mode = false;
$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg');

if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
    exit_status('Error! Wrong HTTP method!');
}

if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
    $pic = $_FILES['pic'];
    if(!in_array(get_extension($pic['name']),$allowed_ext)){
        exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
    }   
    if($demo_mode){
        $line = implode('       ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
        file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
        exit_status('Uploads are ignored in demo mode.');
    }
    if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
        exit_status('File was uploaded successfuly!');
    }
}
exit_status('Something went wrong with your upload!');

function exit_status($str){
    echo json_encode(array('status'=>$str));
    exit;
}

function get_extension($file_name){
    $ext = explode('.', $file_name);
    $ext = array_pop($ext);
    return strtolower($ext);
}
?>

PS. It says that it is mostly coded so to add more details? What else... I am a student and I need it for my Capstone project and it is an emergency...


回答1:


The second argument in move_uploaded_file() is the new filename, so all you need to do is change it to what you want.

if(move_uploaded_file($pic['tmp_name'], $upload_dir.'newtexture.jpg')){



回答2:


move_uploaded_file takes two arguments:

  1. The temporary file name to move.
  2. The new permanent file path.
bool move_uploaded_file ( string $filename , string $destination )

So, You'll have to specify the second parameter (path + the new file name). E.g.

move_uploaded_file($pic['tmp_name'], $upload_dir.'newtexture.jpg')



回答3:


Pass your file name as a second argument in move_uploaded_file()

$fileName = 'newtexture.jpg';

if(move_uploaded_file($pic['tmp_name'], $upload_dir.$fileName)){


来源:https://stackoverflow.com/questions/20444798/how-to-change-name-of-uploaded-file-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!