Alexander Richard
Alexander Richard

Reputation: 191

How to get file name from full path with PHP

This is my upload php:

  if (trim($_FILES['path_filename']['name']))
{
  if (File::upload($_FILES['path_filename'], dirname(realpath(__FILE__)) . '/../tests'))
  {
    $test->setPathFilename('../tests/' . $_FILES['path_filename']['name']);
  }
}
  }
  else
  {
if ($aux)
{
  $aux = str_replace("\\", "/", $aux);
  $aux = preg_replace("/[\/]+/", "/", $aux);
  $test->setPathFilename($aux);
}
  }
  $_POST["upload_file"] = $test->getPathFilename();

This above code is working well, I mean, upload to server is working and also getting Path File Name and insert into sql table is working too.

Example: When I upload a file for example: ABC.jpg , it will upload to tests folder and also Path File Name is (( ../tests/ABC.jpg )) and it will insert to sql table.

The problem is here:

I changed global function to rename files automatically by using this following code:

Before It was:

        $destinationName = $file['name'];

I changed it to:

$ext = pathinfo($file["name"], PATHINFO_EXTENSION);
$destinationName = sha1_file($file["tmp_name"]).time().".".$ext;

Now, After upload file to tests folder, it will be renamed automatically, but still Path File name is same, It's ABC.jpg not renamed file in tests folder.

How to get Renamed Path File Name ???

I really appreciate your help on this issue.

Thanks in advance

Upvotes: 1

Views: 2981

Answers (2)

Jorge Y. C. Rodriguez
Jorge Y. C. Rodriguez

Reputation: 3449

To rename the path file name you could use this:

if ( !file_exists( $path ) ) {
    mkdir( $path, 0777, true );
}

This will make sure the path exist and if it doesn't it will created. Now we can rename()

rename( __FILE__  "/new/path/".$file_name );

This will move it between directories if necessary.

Upvotes: 0

M. Eriksson
M. Eriksson

Reputation: 13635

Use basename() to get the filename from a path.

$filename = basename('/path/to/file.ext');

This will give you: file.ext

Upvotes: 2

Related Questions