-2

I am using W3Schools example of file upload using PHP, I know they aren't the best when it comes to coding as it can be outdated and bad etc., but I don't need anything too fancy. But I am wondering how to change the file name when it is uploaded.

W3Schools code (slightly edited):

<?php

$username = $_POST['username'];

$target_dir = '../forum/uploads/'.strtolower($username).'/';
$target_file = $target_dir.'profile'.basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        $uploadOk = 1;
    } else {
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    unlink($target_file);
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 1) {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "Profile picture updated";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

I want to change the name to just profile, right now when I upload using this code it will upload the file as profile followed by the name of the file, like so, profilexxxx.jpeg.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
TheWelshManc
  • 495
  • 3
  • 13
  • how does this fail? can you elaborate? – Funk Forty Niner Mar 31 '18 at 01:17
  • Read the bottom of the post, I said it there. I want it to upload with the file name profile but it uploads as profilexxxx e.g. I upload an image called dog.jpg it would be profiledog.jpg. I just want it as profile.jpg – TheWelshManc Mar 31 '18 at 01:21
  • Its a little insecure, an attacker could just not send up the `$_POST["submit"]` and bypass your image validation, hopefully, `shell.php.jpg` does not get parsed by your server. – Lawrence Cherone Mar 31 '18 at 01:21
  • @LawrenceCherone I will add in validation at a later point, for now I just need this to work. – TheWelshManc Mar 31 '18 at 01:21
  • Whats `$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);` for? – Lawrence Cherone Mar 31 '18 at 01:22
  • This link may help you. https://stackoverflow.com/questions/18705639/how-to-rename-uploaded-file-before-saving-it-into-a-directory* – R. F. Mar 31 '18 at 01:22
  • @R.F. Already checked it, didn't help with my case – TheWelshManc Mar 31 '18 at 01:24
  • 1
    Yea the default state of the upload should be to fail `$uploadOk = 1;` should be `$uploadOk = 0;` it should only pass if some condition says it's ok. Even still some things could be fixed, for example once the upload is decided it should fail, none of the other code needs to run. – ArtisticPhoenix Mar 31 '18 at 01:29

2 Answers2

1

Like this

$target_file = $target_dir.'profile'.basename($_FILES["fileToUpload"]["name"]);

Remove

  $target_file = $target_dir.'profile'.strrchr($_FILES["fileToUpload"]["name"],'.');

But you should really try yourself.

This bit strrchr($_FILES["fileToUpload"]["name"],'.'); returns the extension from the file name. so if it's file.jpg it returns .jpg, and thus profile.jpg. I should mention it only returns the last extension. So if you have file.php.jpg it only returns .jpg

UPDATE

I didn't see you already have the extension parsed out, So given that, you can move this a bit.

 $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
 $target_file = $target_dir.'profile'.'.'.$imageFileType;

No need to do it twice.

Pathinfo - is probably the "proper" way. Just most the sandboxes have it turned off, so I was a bit to lazy to google it to see if it retained the . as in jpg vs .jpg (I always forget).

PS This is what sandbox says....

Warning: pathinfo() has been disabled for security reasons in [...][...] on line 7

Community
  • 1
  • 1
ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
0

I use this for uploading files and it works fine.

<?php

if(isset($_POST['submit'])){
  // Retrieve file from post method
  $file = $_FILES['file'];

  // Get file properties
  $fileName = $file['name'];
  $fileTmpName = $file['tmp_name'];
  $fileSize = $file['size'];
  $fileError = $file['error'];
  $fileType = $file['type'];

  //Separate name and file extension
  $fileExt = explode('.', $fileName);
  //Set to always lowercase
  $fileActualExt = strtolower(end($fileExt));

  //Set any extension allowed
  $allowed = array('jpg','jpeg','png');

  //Check whether file extension is allowed
  if(in_array($fileActualExt, $allowed)){
      if($fileError === 0){
          //Check file size criteria
          if($fileSize <= 150000){
              $NewName = "MyNewName"; //define new file name
              //Define your custom file name
              $fileNameNew = $NewName.".".$fileActualExt;
              //Define file destination
              $fileDestination = '../images/'.$fileNameNew;
              //php uploading files
              move_uploaded_file($fileTmpName, $fileDestination);

          } else{
              echo "file is too big";
          }
      } else{
          echo "upload error";
      }
  } else{
      echo "your extension is not allowed";
  }
}
?>