Home > database >  Hash the name of a created folder in PHP?
Hash the name of a created folder in PHP?

Time:03-06

so the below PHP code that I have takes the user's ID and checks to see if that user has a profile folder on the server or not, where all of their profile data will be stored eventually--if the user doesn't already have one, it will automatically make a folder based off of the user's username.

I want to make it so the folder doesn't get named the exact same as the user's profile name. I want to hash it. I'm having difficulty doing that, and was wondering if there is a way to add in a hash function to this code to make the created folder hashed. I'd prefer the sha256 hash algorithm but I'm not sure if that's the best choice for this situation, or if it even matters. P.S.: I've already tried just hashing the variable but obviously I'm doing something wrong here. The code is below:

<!-- The following checks if the user already has a profile folder, and if not, it creates one equal to the username of the user -->
<?php
$userID = $_SESSION["username"];

// Define path where file will be uploaded to
//   User ID is set as directory name
$profileFolder = "profiles/$userID";

hash('sha256', $profileFolder);

// Check to see if directory already exists
$exist = is_dir($profileFolder);

// If directory doesn't exist, create directory
if(!$exist) {
mkdir("$profileFolder");
chmod("$profileFolder", 0755);
}
else { echo "<p id='welcome-msg'>Welcome, <p id='userfolder'>$userID</p></p>"; }
?>

I already know the code works, at least for the main purpose of checking/creating the user's folder. I just don't want the created folder to be the exact same as the user's username.

CodePudding user response:

Apparently, you are hashing the whole path, not just the user folder.

$profileFolder = hash('sha256', $userID);

$hashed_folder = "profiles/{$profileFolder}" ;

// Check to see if directory already exists
$exist = is_dir($hashed_folder);

CodePudding user response:

Not sure if I am supposed to reply to my own post to show the solution that worked, but I tried this instead and this is what works, and it does so perfectly, thank you guys:

<?php
$userID = $_SESSION["username"];

// Define path where file will be uploaded to
//   User ID is set as directory name

$hashedFolder = hash('sha256', $userID);

$profileFolder = "profiles/$hashedFolder";

// Check to see if directory already exists
$exist = is_dir($profileFolder);

// If directory doesn't exist, create directory
if(!$exist) {
mkdir("$profileFolder");
chmod("$profileFolder", 0755);
}
else { echo "<p id='welcome-msg'>Welcome, <p id='userfolder'>$userID</p></p>"; }
?>```
  • Related