mysql – I can't get the rename() function in PHP to work (or any of the file modifcation functions for that matter)-ThrowExceptions

Exception or error:

Thanks for your time.

So, I have a LAMP stack web server, and want to change the path to a file that got uploaded.

For example, a user uploads a picture via the front-end, the PHP code reads it, renames the file to a hashed string so that files won’t overlap and have the same names in the picture upload directory, and point the picture column on the user’s row to the new path in the SQL table.

So I’ve got everything working except renaming the file.

The file name gets passed in successfully (i.e. ball.png)

    $fileName = basename($_FILES["file"]["name"]); //This works, and let's pretend that it is "ball.png" in this example.

    $baseDir = "uploads/profiles"; //This code works as it should.
    $targetPath = $baseDir.$fileName; //This code works as it should.

    $newFileName = $randomString.$fileExtension;
    //The random string variable is generated in a previous function, and it works. Let's pretend that it is "e7635hasf1 in this example."
    //The file extension variable is generated in a previous function, and it works. Let's pretend that it is ".png" in this example.

    rename($targetPath, $newFileName);
    //This is the code that does not work. I've tried changing permissions, doing it in the same directory to simplify things, but can't get rename() to work at all.

    updateTables();
    //This code works as it should. The SQL picture column for the row of the user that uploaded the picture now reads "uploads/profiles/e7635f1.png"

I’m using PHP 7 if that helps at all. This code works fine if I don’t rename anything (e.x. if I do my updateTables() function and pass “uploads/profiles/ball.png” rather than “uploads/profiles/e7653hasf1.png”). This basically pinpoints that the issue is in the rename() function, so that is the specific one-liner that is not working.

Thanks again for your time. If you have questions, please let me know.

How to solve:
$targetPath = $baseDir.'/'.$fileName;

$newFileName = $baseDir.'/'.$randomString.$fileExtension;

Leave a Reply

Your email address will not be published. Required fields are marked *