0

I am creating a social site that allows people to upload pictures. I am using tempnam() to make each image name unique. But I have a problem.

The tempnam() function seems to be saving the full path in the DB even though I am not trying to use the full path and because of that I can't retrieve the pictures from the folder. There doesn't seem to be any other questions related to mine. Can someone help me ?

$picToUpload =  tempnam("assets/images/profile_pics/", '');

            $withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $picToUpload);

            $fileExtension = ".png";
            rename($picToUpload, $withoutExt . $fileExtension);

            $new_file_name = $withoutExt . $fileExtension;

            if( !move_uploaded_file($file_tmp, $picToUpload)) {
                
                $errors = "Error uploading files";
                die();
            }

            $path = move_uploaded_file($new_file_name, "assets/images/profile_pics/");

            $file_path = $new_file_name;

            unlink($picToUpload);

            $stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?");
            $stmt->bind_param('ss', $file_path, $username);
            $stmt->execute();
            $stmt->close();

            header('Location: profile.php');
            exit();
user13477176
  • 119
  • 6
  • See this for [unique and temporary file names](https://stackoverflow.com/a/460168/231316). The documentation for [`tempnam`](https://www.php.net/manual/en/function.tempnam.php) says "Returns the new temporary filename (with path)" – Chris Haas Jan 14 '22 at 14:02
  • @ChrisHaas damn. Ok but the file gets uploaded to the correct path and the image still doesn't show. – user13477176 Jan 14 '22 at 14:04
  • Put your files in a folder, and store the folder's name as a configuration variable to your application. This will allow you to change that globally in one spot if you ever move your code, want to host locally, or possibly use a CDN in the future. Give your files a unique name such as a UUID, and save them in that folder, and store just that name in the database. Skip `tempnam`, PHP has already uploaded the files using something that is effectively that already. – Chris Haas Jan 14 '22 at 14:08

0 Answers0