Alb
Alb

Reputation: 45

Need to rename an image after upload

i have this code here which outputs me an image.. I need to change it because for the moment it gives me something like : test.jpg, what i need is for it to give me test_s.jpg

Using the rename function i guess!

$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetPath = str_replace('//','/',$targetPath);
$targetFile = $targetPath . $_FILES['Filedata']['name'];
tamano_nuevo_foto($stempFile, 420, $stargetFile);

Upvotes: 0

Views: 147

Answers (4)

Hurmpf
Hurmpf

Reputation: 26

You should use pathinfo and move_uploaded_file

$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/'; // should make this more secure, like a fixed path or in a whitelist
$targetPath = str_replace('//','/',$targetPath);
$ext = pathinfo($_FILES['Filedata']['name'], PATHINFO_EXTENSION);
$basename = pathinfo($_FILES['Filedata']['name'], PATHINFO_BASENAME);
$targetFile = $targetPath . $basename . "_s" . $ext;
move_uploaded_file ( $tempFile , string $targetFile)
//tamano_nuevo_foto($stempFile, 420, $stargetFile); // move and resize ??

Upvotes: 0

MatejG
MatejG

Reputation: 1423

Or you can use this function:

function add_s($file){
    $fName = substr($file, 0,strpos($file, "."));
    $fExtension = substr($file, strpos($file, "."));
    $newFName = $fName."_s".$fExtension;
    return $newFName;
}

Upvotes: 0

Erwin Moller
Erwin Moller

Reputation: 2408

First: You seem to have a path that can be manipulated by the the user. Your usage of $_REQUEST['folder'] directly in your path is bad. The user could put ANYTHING in there, even stuff like ../../../ to move around your filesystem!

To change the name, simply:

$targetFile = $targetPath . "myfilename.png";

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

You could do:

$extension = array_pop( explode(".", $_FILES['Filedata']['name']) ); //get extension
$targetFile = $targetPath . "some_new_name".$extension;
tamano_nuevo_foto($tempFile, 420, $targetFile);

Upvotes: 2

Related Questions