$dir='users/'.$username;
mkdir($dir);
copy('default-profile_pic.png',$dir.'/default-profile_pic.png'
How to create a folder with an image inside of it PHP
-
11-10-2022 - |
题
When the user registers to my site, I want to create a folder with their username and the default profile pic image inside of it. I know how to make a folder, but how do I make a folder with a file in it.
The folder should look something like this:
/users/pcoulson/
(pcoulson would be the user's username)
and ../pcoulson/
should have the default profile pic in it like this:
/users/pcoulson/default-profile_pic.png
How would I do this with PHP
解决方案
其他提示
if(isset($_POST['add-user-submit']) && isset($_FILES['image']['name']))
{
#label the form inputs
$username = $_POST['username'];
$image = $_FILES["image"]["name"]; // The file name
$fileTmpLoc = $_FILES["image"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["image"]["type"]; // The type of file it is
$fileSize = $_FILES["image"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["image"]["error"]; // 0 = false | 1 = true
$kaboom = explode(".", $eventFlyer); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
if(!$fileTmpLoc)
{
$error = "Please insert ALL fields";
}
elseif($fileSize > 2097152 )
{
$error = "ERROR: Your file was larger than 2 Megabytes in size.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
}
elseif(!preg_match("/.(gif|jpg|png)$/i", $image))
{
$error = "ERROR: Your image was not .gif, .jpg, or .png.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
}
else if ($fileErrorMsg == 1)
{
$error = "ERROR: An error occured while processing the file. Try again.";
}
else
{
# move the file to a folder
$moveResult = move_uploaded_file($fileTmpLoc, "you file directory ex(../img/users/$username)");
if($moveResult != true) // there was an error uploading the file to the folder
{
$error = "ERROR: File not uploaded. Try again.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
}
I propose to save the image in the backing store, your database.
Doing it this way, the image is 'strongly related' to the user. And it won't get un-related, once the user name changes.
- You first have to create the folder
- Copy the picture to new genereated folder.
Assuming you retireved users data to $userdata
variable. You can make folder like these
And I assume your default_pic
is located in the same directory as users
.
$new_directory = 'users/'.$userdata['username'];
mkdir($new_directory,0777);
copy('default-profile_pic.png',$new_directory.'/default-profile_pic.png');