When a user creates a profile and uploads a profile picture, the PHP "move_uploaded_file" function is used to move a temporary copy of this image to the project directory.
While my current code works perfectly fine on my Windows 10 machine, it doesn't work on my Mac because of incorrect file permissions.
I have already tried the method provided in other answers and nothing changes after running the terminal command:
sudo chmod 644 /opt/lampp/htdocs/yourfolder
This is true for any variation including:
sudo chmod -R 777 /opt/lampp/htdocs/yourfolder
Note that I DO have admin permissions on the laptop
Other users have stated that these commands have fixed their problems, so I suspect that mine is different.
PHP Code Snippet:
$username = $_POST["username"];
$password = $_POST["password"];
$ext = null;
/* Debugging information
echo $_FILES["profile_pic"]["name"]."<br>";
echo $_FILES["profile_pic"]["tmp_name"]."<br>";
echo $_FILES["profile_pic"]["size"]."<br>";
echo $_FILES["profile_pic"]["error"]."<br>";
*/
if (strrpos($_FILES["profile_pic"]["name"], ".jpg") != null || strrpos($_FILES["profile_pic"]["name"], ".jpeg") != null) {
$ext = ".jpg";
};
if (strrpos($_FILES["profile_pic"]["name"], ".png") != null) {
$ext = ".png";
};
$path = __DIR__ . "\data\users\images\\" . uniqid() . $ext;
if (move_uploaded_file($_FILES["profile_pic"]["tmp_name"], $path)) {
echo("File successfully uploaded");
} else {
echo("Upload failed");
};
Returned: Upload failed
Error thrown:
move_uploaded_file(/opt/lampp/htdocs/Test-Site\data\users\images\5c1dadd52bb71.jpg): failed to open stream: Permission denied in /opt/lampp/htdocs/Test-Site/signup_confirm.php on line 27
Expected: user profile picture is inserted into the .../htdocs/Test-Site/data/users/images folder
Actual: above error about incorrect file permissions is thrown
The reason for the error is that I was using incorrect directory separators ("\" instead of "/" for Mac). Changing these made the profile picture move to the intended location.
Related
What I am trying to do
Connect to FTP server
Create new directories
Upload file into one of those new directories
What's going wrong?
Ok, so there is nothing wrong with the ftp connection, I am logging in with the credentials, switching to the relevant starting directory, which in this case is a directory on the server called "test".
At the start, this "test" directory is empty, as I just created it.
What I am then doing is taking a file from my local machine and attempting to upload that the remote path test/Folder1/Sub1/Sub2/Myfile.txt on the server.
To do this, I first split the path by "/" and check to see if I can switch to each of those directories, and if I can't, then I create them:
(You'll have to excuse the debugging dumps in the code)
// Split the path by directories and try and create all of them if they don't exist
$workingDir = $this->dir;
$newPath = str_replace($this->dir, "", $path);
$split = array_filter( explode("/", $newPath) );
if ($split)
{
foreach($split as $dir)
{
// Can we change to it?
if (!#ftp_chdir($this->conn, $workingDir . '/' . $dir)){
// Try and make the directory
if (!#ftp_mkdir($this->conn, $workingDir . '/' . $dir)){
var_dump("failed to make: " .$workingDir . '/' . $dir );
return false;
}
// Set the permissions to the default
$this->chmod = 0777;
ftp_chmod($this->conn, $this->chmod, $workingDir . '/' . $dir);
var_dump("Successfully made directory: " . $workingDir . '/' . $dir . " with permissions: " . $this->chmod);
}
$workingDir .= '/' . $dir;
}
}
This works fine, and I get the output of:
'Successfully made directory: /home/conn/test/Folder1 with permissions: 511' (length=74)
'Successfully made directory: /home/conn/test/Folder1/Sub1 with permissions: 511' (length=79)
'Successfully made directory: /home/conn/test/Folder1/Sub1/Sub2 with permissions: 511' (length=84)
If i exit at this point I can confirm the directories now exist on the remote server, with permissions of 0777
Next bit is to do the file upload into the new directory:
var_dump("Use this new name: {$newName}");
$filename = (($newName) ? $newName : $file->getFileName());
var_dump("working in remote directory: {$this->dir}");
var_dump("upload to remote: {$filename}, from: {$file->getFullPath()}");
// Change to that directory?
$split = explode("/", $filename);
$realFileName = array_pop($split);
$filedir = implode("/", $split);
var_dump("calling ftp_chdir() to : {$filedir}");
if (!#ftp_chdir($this->conn, $filedir)){
var_dump("couldn't change to {$filedir}");
return false;
};
var_dump( ftp_pwd($this->conn) );
var_dump("actual file name: " . $realFileName);
return ftp_put($this->conn, $realFileName, $file->getFullPath(), FTP_BINARY);
And again, this works fine. I get all the expected dumps:
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:121:string 'Use this new name: Folder1/Sub1/Sub2/Myfile.txt' (length=47)
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:124:string 'working in remote directory: /home/conn/test' (length=44)
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:125:string 'upload to remote: Folder1/Sub1/Sub2/Myfile.txt, from: C:\Ampps\www\duckfusioncore\app\lotto\tmp\tmp-nsEMH1RsDX' (length=110)
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:131:string 'calling ftp_chdir() to : Folder1/Sub1/Sub2' (length=42)
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:139:string '/home/conn/test/Folder1/Sub1/Sub2' (length=33)
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:140:string 'actual file name: Myfile.txt' (length=28)
C:\Ampps\www\duckfusioncore\app\lotto\controllers\IndexController.php:28:boolean true
All the directories exist. The file is uploaded. All is well.
Except, if I now change the path I want to upload to and change toa new sub directory, which doesn't yet exist, e.g: Folder1/Sub1/NewSub/Myfile.txt
This is where it all goes wrong.
So the script runs through the create directory part again, and it successfully creates the new directory "NewSub", with the exact same permissions as before, and I can confirm that the directory exists on the remote server.
Except now when we get to the upload part, even though the directory exists, and this worked previously as we saw, it is unable to change to that new directory:
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:121:string 'Use this new name: Folder1/Sub1/NewSub/Myfile.txt' (length=49)
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:124:string 'working in remote directory: /home/conn/test' (length=44)
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:125:string 'upload to remote: Folder1/Sub1/NewSub/Myfile.txt, from: C:\Ampps\www\duckfusioncore\app\lotto\tmp\tmp-XJYdx8eduL' (length=112)
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:131:string 'calling ftp_chdir() to : Folder1/Sub1/NewSub' (length=44)
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:135:string 'couldn't change to Folder1/Sub1/NewSub' (length=38)
C:\Ampps\www\duckfusioncore\app\lotto\controllers\IndexController.php:28:boolean false
The directory 100% exists. And it has the same 0777 permissions as the other ones.
I'm just very confused as to why it is unable to switch to the directory, when it defintely exists and it has the same permissions as the other directories, which it had no problem switching to before...
Has anyone got any clue what might be the problem? Is there any extra debugging I can do on the ftp_chdir() function call to see if it gives me a reason?
Thanks.
$image_path ="images/";
$dir_perms = 0777; //0755;
$file_perms = 0644;
//sets PHP's umask to mask & 0777 and returns the old umask
$old_umask= umask(0);
echo " old umask == $old_umask";
if (mkdir($image_path, 0777, TRUE) )
echo "created $image_path";
else
{
echo " $image_path failed creation";
exit();
}
/*
//if (chmod($image_path, 0777) )
if( chmod( $image_path, $dir_perms))
echo " $image_path folder set as $dir_perms";
else
echo "$image_path failed to chmod to $dir_perms";
*/
//chmod( $create_path,0777);
$owner = "root";
// Set the user
if ( chown($image_path, $owner) )
{
echo "user changed to root ";
}
else
{
echo "\n -------- NOT changed to root! ";
exit();
}
My chown fails. According to some people this is a bad approach because it would let my script change ownership of a file in the "client"'s system.
My main concern is that I want my php script to access the directory it created!
I am probably making some silly mistake. So, when I try to access www-data permission folder, it fails.
If I try to show a image from a directory with root permission, a code I have work.
I have been using an upload script on my server, like below
$newname = time() . '_' . $_FILES[$file]["name"];
if (strtolower(end(explode('.', $_FILES[$file]["name"]))) != 'pdf' AND $file != "damage_attachment_damageform_1" AND $file != "damage_attachment_damageform_2" AND $file != "damage_attachment_damageform_3" AND $file != "damage_attachment_damageform_4") {
if (move_uploaded_file($_FILES[$file]["tmp_name"], $_SERVER['DOCUMENT_ROOT'] . '/components/com_fleet/uploads/docs/' . $newname)) {
$images[] = $_SERVER['DOCUMENT_ROOT'] . '/components/com_fleet/uploads/docs/' . $newname;
$docs[] = $_SERVER['DOCUMENT_ROOT'] . '/components/com_fleet/uploads/docs/' . $newname;
} else {
die();
}
}
It uploads an image fine, but since a few days a get a Warning: move_uploaded_file(): Unable to move error. Ive seen these a dozen of times while learning to program, so I did all the usual stuff, check paths, the $_FILES[$file]["error"] and check all the right CHMODs. All is fine, path is spot-on, chmod is too, no errors etc...
1 extra weird thing I noticed the file does get written to the right /docs map but its Filesize is empty, and move_upload_file still sends false...
What am I forgetting? CHOWN maybe? And how can I solve that, I dont have SSH access or something.
Graa after an hour I now found out what was wrong, server Disk Quota was exceeded. Maybe people can still benefit from my problems...
I'm trying to make a php script to connect to an afp server and get a directory listing (with each file size). The server is local in our office, but I'm unable to just make a script on the afp server side. On my machine, I use something like this:
$filesInDir = array();
$filesInMySQL = array();
if (is_dir($uploadDir)) {
$dh = opendir($uploadDir);
if ($dh) {
$file = readdir($dh);
while ($file != false) {
$path = $uploadDir . "/" . $file;
$type = filetype($path);
if ($type == "file" && $file != ".DS_Store" && $file != "index.php") {
$filesInDir[] = $file;
}
$file = readdir($dh);
}
closedir($dh);
} else {
echo "Can't open dir " . $uploadDir;
}
} else {
echo $uploadDir . " is not a folder";
}
But I can't connect to the afp server. I've looked into fopen it doesn't allow afp, and I don't think it'd allow directory listing:
opendir("afp://ServerName/path/to/dir/");
Warning: opendir() [function.opendir]: Unable to find the wrapper "afp" - did you forget to enable it when you configured PHP? in...
Warning: opendir(afp://ServerName/path/to/dir/) [function.opendir]: failed to open dir: No such file or directory in...`
I'm not looking to see if a file exists, but to get the entire directory listing. Eventually I'll also have to remotely copy files into an output directory.
eg.
mkdir afp://ServerName/output/output001/
cp afp://ServerName/path/to/dir/neededfile.txt afp://ServerName/output/output001/
Maybe use http://sourceforge.net/projects/afpfs-ng/ to mount it...
I'm developing on an Mac Mini, so I realised I could just mount the afp share, and use readdir. I had to mount the drive using the following:
sudo -u _www mkdir /Volumes/idisk
sudo -u _www mount_afp -i afp://<IP>/sharename/ /Volumes/idisk/
Further details here
How is one supposed to handle files that aren't in the current directory when using ftp_put? This piece of code is trying to upload a file that I know exists, but it always gives the following error:
"Warning: ftp_put() [function.ftp-put]: Requested action not taken, file not found or no access. in /path/to/files/domains/mydomain.com/html/scriptfile.php on line 1337"
Here's the snip:
$file_name = $this->GetFileName();
if ($file_name)
{
$resource = ftp_connect('ftp.remoteftpserver.com');
if ($resource && ftp_login($resource, $username, $pass))
{
ftp_pasv($resource, true);
//UPLOAD_DIRECTORY == '/IN' (it really exists, I'm sure)
//ORDER_DIRECTORY == /home/domains/mydomain.com/orders (came from $_SERVER['DOCUMENT_ROOT']
ftp_put($resource, UPLOAD_DIRECTORY . '/' . $file_name, ORDER_DIRECTORY . '/' . $file_name, FTP_ASCII);
ftp_close($resource);
}
else
{
echo "FTP Connection Failed!";
}
}
Check the permissions of the remote file. Make sure $username has write access to the file. Make sure you have execute access on the parent directory.