Connect to remote afp server using PHP - php

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

Related

Permission denied in /opt/lampp/htdocs/ when writing a file in PHP

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.

fopen is not working on elastic beanstalk php

I am using the following code in elastic beanstalk php to generate log file but I am getting this error.But the same code is working on another server. How can I make it work ?
Error:
Error opening file in write mode!
Code :
$path="/var/www/html/aws";
$fileName =$path.'/logs/data'.date('Y-m-d_H-i-s'). '_' . uniqid() . '.txt';
$file = fopen($fileName,'w') or die('Could not create report file: ' . $fileName);
foreach($_POST as $key => $value) {
$reportLine = $key." = ".$value."\n";
fwrite($file, $reportLine) or die ('Could not write to report file ' . $reportLine);
}
fputs($file,"log aws");
fclose($file);
Make sure your php user www-data have permission to write in $path.'/logs/ folder or just chmod that logs folder to 0777 permisson

rename file is not working on php

Hi i have problem with this code
with the code i can change whole my folder file to number like 1.mp4 2.mp4 ect...
i test the code and i print the name of the file from it and every thing is right
but rename function is not working
this is my code
$dir = opendir('.');
$i = 1;
// loop through all the files in the directory
while (false !== ($file = readdir($dir)))
{
// if the extension is '.mp4'
if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'mp4')
{
echo $file ;
// do the rename based on the current iteration
$newName = $i . '.mp4';
rename($file, $newName);
// increase for the next loop
$i++;
}
}
// close the directory handle
closedir($dir);
?>
what is the problem now ?
NEW iNFO
i tried the code inside my localhost and it's work but it's not working inside the server
It's more efficient to use glob()
foreach(glob(__DIR__ . '/*.mp4') as $key => $file) {
if(!rename($file, __DIR__ . '/' . ($key + 1) . '.mp4')) {
throw new Exception('Unable to write to '. $file);
}
}
I'll hazard a guess it's a write permissions issue though - I don't see anything directly wrong with the script.
Getting the real path can help:
$file = realpath($filename);
but it sounds like it could be a permissions issue or an SELinux issue also. You will need apache to be the group on the files in question, and the files should be writeable by the group.
Also, if you have SELinux enabled, you will need to use
semanage fcontext -a -t httpd_sys_rw_content_t "/path/to/images/folder(/.*)?"
and
restorecon -R -v /path/to/images/folder

PHP Zip function doesn't work (Debian, Apache, PHP5)

I've installed apache on a debian server and added php. But if i try to create a .zip file it doesn't work. There's no error message but the .zip file doesn't get created.
Code:
<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
$zip->addFile('Banner1.png', 'Banner1.png');
$zip->close();
?>
Most likely, the user that php is running as (on debian, www-data by default) doesn't have writing permissions to the directory. Check the result of the various functions like this:
<?php
$zip = new ZipArchive();
$res = $zip->open('test.zip', ZipArchive::CREATE);
if (!$res){
echo 'Error while creating zip file: ' . $zip->getStatusString();
exit();
}
if (! $zip->addFile('Banner1.png', 'Banner1.png')) {
echo 'Error while adding Banner1: ' . $zip->getStatusString();
exit();
}
if (! $zip->close()) {
echo 'Error while closing: ' . $zip->getStatusString();
exit();
}
On a debian with default configuraiton, you can configure permissions with chown and chmod. For example, to allow the webserver to write to that directory, try
sudo chown www-data /path/to/directory/with/php/file
sudo chmod u+rwx /path/to/directory/with/php/file
Sûre your $res is good ?
if ($res === TRUE) {
echo 'ok';
$zip->addFile('Banner1.png', 'Banner1.png');
$zip->close();
} else {
echo 'failed, code:' . $res;
}

How to get a directory content and move to another directory with PHP

I've been trying to get this done with no luck. I've got a php script that downloads and UNZIPS a file. No problem here.
After that, I need to get the unzipped files and replace all the files of the root directory with the files on this folder. Problem is, the folder is in the root directory.
Eg.: my directory is something like this
/
/folder 1
/folder 2
/folder 3
/file.php
/file2.php
etc...
After I run my download script I unzip the archive to a folder called update in the root of the dir
/update/--UNZIPED STUFF--
I need to delete virtually all files/dirs from the root DIR excluding the update folder I guess and a couple of other files and then move the files/folders inside the update folder to the root of the dir.
Any ideas?
UPDATE
Ok, so I've made a code that seems to be right but I get a lot of file permission to when using unlink or rename. How can I go about that?
Here is the bit of code I've made
echo '<table>';
$updateContents = scandir('./');
foreach($updateContents as $number=>$fileName){
if($fileName != 'update' && $fileName != 'config.ini' && $fileName != 'layout.php' && $fileName != '..' && $fileName != '.' && $fileName != '.git' && $fileName != '.gitignore'){
if(is_dir($fileName)){
moveDownload($fileName, 'old/'.$fileName);
} else {
if(rename($fileName, 'old/'.$fileName)){
echo '<tr><td>'.$fileName.' moved successfully </td><td><font color="green">OK</font></td></tr>';
} else {
echo '<tr><td>Could not move file '.$fileName.'</td><td><font color="red">ERROR</font></td></tr>';
}
}
}
}
echo '</table>';
and the moveDownload function is one I found here somewhere. It moves a non empty folder and it was slightly modified by me.
function moveDownload($src,$dst){
$dir = opendir($src);
while(false !== ($file = readdir($dir))){
if (($file != '.') && ($file != '..') && ($file != 'config.ini') && ($file != 'layout.php') && ($file != 'sbpcache') && ($file !='update')){
if (is_dir($src.'/'.$file)){
if(file_exists($dst.'/'.$file)){
rrmdir($dst.'/'.$file);
}
}
if(#rename($src . '/' . $file, $dst . '/' . $file)){
echo '<tr><td>'.$file.' moved successfully </td><td><font color="green">OK</font></td></tr>';
} else {
if(#chmod($src.'/'.$file, 0777)){
if(#rename($src . '/' . $file, $dst . '/' . $file)){
echo '<tr><td>'.$file.' moved successfully </td><td><font color="green">OK</font></td></tr>';
} else {
echo '<tr><td>Could not move file '.$file.'</td><td><font color="red">ERROR RENAME</font></td></tr>';
}
} else {
echo '<tr><td>Could not move file '.$file.'</td><td><font color="red">ERROR CHMOD</font></td></tr>';
}
}
}
}
closedir($dir);
}
I also do the same in the again but moving from the update folder.
So basically, first instead of deleting things I am just moving them to a folder called old and then I try to move the new things in, but I get permission problems everywhere. Some files move, some don't, even if I have ' sudo chmod 777 -R'. Any ideas?
PHP's opendir will allow you to iterate along all the files and directories inside the root directory. You can use unlink to delete the files or folders and add an if clause to check if the item is to be deleted or not.
Why don't you just get a list of all directories / files under root and then loop through them, delete them (using unlink) while ignoring the "backup" directory.
Next you can either run a php copy OR shell_exec mv * command to move the files from backup to root.
what for to use root folder. use /tmp
what the problem with unlink / rmdir

Categories