1

I'm trying to rename the input file to be a .jpg after conversion, but for some reason I'm getting a file.png.jpg when I'm really looking for file.jpg

Here is my code:

$source = $path . $_POST['username']. "-" . $_FILES['t1']['name'];
$destination = $path . $_POST['username']. "-" . basename($_FILES['t1']['name']) . ".jpg";
Blynn
  • 1,411
  • 7
  • 27
  • 48

5 Answers5

2

Use pathinfo():

$source = $path . $_POST['username']. "-" . $_FILES['t1']['name'];
$path_parts = pathinfo( $_FILES['t1']['name'] );
$destination = $path . $_POST['username']. "-" . $path_parts['filename'] . ".jpg";
Andrey Volk
  • 3,513
  • 2
  • 17
  • 29
1

Let's say that the variable $filename contains your image name with the png extension.

In order to change the extension to jpg , simply run it through this function :

function replace_extension($filename) {
    return preg_replace('/\..+$/', '.' . '.jpg', $filename);
}
EnKrypt
  • 777
  • 8
  • 23
0

The basename() function includes the original files extension

Use the pathinfo() function to return an array of informatino about the file and use the filename with out the extension

Replace

$destination = $path . $_POST['username']. "-" . basename($_FILES['t1']['name']) . ".jpg";

with

$info = pathinfo($_FILES['t1']['name']);
$destination = $path . $_POST['username']. "-" . $info['filename'] . ".jpg";
fullybaked
  • 4,117
  • 1
  • 24
  • 37
0

You can either use the second parameter to basename to kill the suffix

$filename = basename($_FILES['t1']['name'], ".png");

or you could do some string manipulation

$filename = substr($_FILES['t1']['name],0, strrpos($_FILES['t1']['name'], ".") -1);
Orangepill
  • 24,500
  • 3
  • 42
  • 63
0

basename returns you the whole filename, including the file type suffix (i.e. ".jpg"). If you want to strip the suffix, you can call the function with a second parameter: basename($_FILES['t1']['name'], 'png').

But if you want to convert a png to a jpg, you can't just change the filename, you have to convert the file using special functions, see "Use PHP to convert PNG to JPG with compression?".

Community
  • 1
  • 1
Beat
  • 1,337
  • 15
  • 30