-1

I'm trying to rename the uploaded file by adding the uploader name($user) but all it does is showing user's name in the extension part, file.jpguser, here's the code,

if ((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error']         == 0)) {
  //Check if the file is JPEG image and it's size is less than 1.4MB
  $filename = basename($_FILES['uploaded_file']['name']);
  $ext = substr($filename, strrpos($filename, '.') + 1);

 if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") &&
($_FILES["uploaded_file"]["size"] < 10485760))
{

//Determine the path to which we want to save this file
  $newname = dirname(__FILE__).'/affichagesimg/'.$filename'by'.$user;
  //Check if the file with the same name is already exists on the server


  if (!file_exists($newname)) {
    //Attempt to move the uploaded file to it's new place
    if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname)))         {

echo "<script>
alert('votre affichage a était publié avec succés !');
window.location.href='.';

</script>";
LF00
  • 27,015
  • 29
  • 156
  • 295

3 Answers3

0

You need to split the original filename (or use built in functionality) to get the extension. for example:

<?php
...
$file_parts = explode('.', $uploaded_filename);
$extension = array_pop($file_parts);
$file_stub = implode('.', $file_parts);
$new_name = $file_stub . 'by' . $user . '.' . $extension;

Using your code, new filename is:

<?php
...
$new_filename = $filename . 'by' . $user . '.' . $ext;
Community
  • 1
  • 1
Unamata Sanatarai
  • 6,475
  • 3
  • 29
  • 51
0

use pathinfo function

$user = 'username';
$filename = $_FILES['uploaded_file']['name'];
$path_parts = pathinfo($filename);
$newname = "{$path_parts['filename']}_by_{$user}.{$path_parts['extension']}";
Kiyan
  • 2,155
  • 15
  • 15
0

You may be able to use pathinfo as well to parse the file name:

$file_parts = pathinfo($uploaded_filename);

$new_name = $file_parts['filename'].'by'.$user.'.'.$file_parts['extension'];

Chris
  • 111
  • 5