PHP Mkdir will not work - php

I have a simple script that all I need it to do is create a directory with the name of the GET variable. When I run this script, it doesn't seem to create the directory. I would like this directory to be in the same directory as the PHP file.
$dir = $_GET['dir'];
umask(000);
mkdir($_SERVER['DOCUMENT_ROOT']."/".$dir."/",0777);

Put some error handling in there. Most of the time the error is self evident. The following snippet, lifted from PHP manual, shows you how.
$rs = #mkdir( $dirPath, 0777 );
if( $rs )
{
// success
}else{
// print error information
echo 'an error occurred. Attempting create folder';
echo '<br>dirPath: ' . $dirPath;
echo '<br>php_errormsg: ' . $php_errormsg;
}

Related

Detect a WordPress Installation

How to detect if a folder is having a WordPress installation or not ?
WP-CLI does that and gives the error This does not seem to be a WP installation, and detects correctly if the directory has a WP install even if it is in any of the subfolders (wp-includes/images or wp-includes/js ) .
I went through the code and it searches for index.php and compares content with the original index.php . One more thing it does is to check for the presence of wp-includes/version.php . Got the idea but how it works on subfolders like those mentioned above is still not clear . Do anybody have any idea on how to do this ? Thanks in advance .
Look for the wp-config.php file. If you find it, require it, then try to use its constants DB_HOST, DB_USER, DB_PASSWORD and DB_NAME to connect to the WordPress database associated with the WordPress instance. If that works, you very likely have a working WordPress instance.
If your current working directory doesn't have wp-config.php look at parent directories recursively until you (a) find it or (b) come to the top level directory.
wp-cli does more elaborate things. But this should work for you.
So i have scribbled a script that detects a WP install . It works as expected inside a wp install folder , but if it is not inside a WordPress install it executes an infinite loop . Can somebody guide on how to stop at top level directory as mentioned by #O.Jones ? Here is my code .
<?php
function get_wp_index($dir=null) {
if(is_null($dir)){
$dir = getcwd();
}
echo "Currently Looking \n";
echo $dir;
$name = $dir.DIRECTORY_SEPARATOR."index.php";
if ( file_exists( $name ) ) {
$index_code = (file_get_contents($name));
if ( preg_match( '|^\s*require\s*\(?\s*(.+?)/wp-blog-header\.php([\'"])|m', $index_code, $matches ) ) {
echo "Is a WP Install";
return;
} else {
echo "Has index File but not one with wp-blog-header";
echo "\n\n";
//Go one directory up
$up_path = realpath($dir. DIRECTORY_SEPARATOR . '..');
get_wp_index($up_path);
}
} else {
echo 'No Index File Found';
echo "\n\n";
//Go one directory up
$up_path = realpath($dir. DIRECTORY_SEPARATOR . '..');
echo $up_path;
get_wp_index($up_path);
}
}
get_wp_index();
?>

PHP ftp_nlist returning false when retrieving large directory?

What I'm trying to do:
Use PHP ftp_nlist to retrieve the contents of a directory on the FTP server
The problem:
For directories that contain a lot of files (the one I encountered the problem on has nearly 40 thousand files, and no subfolders), the ftp_nlist function is returning false. For directories that are not as large, the ftp_nlist function returns an array of filenames as expected.
What I've tried:
Enabling passive mode (it already was enabled, but I see it as a common suggestion)
Adding ftp_set_option($conn_id, FTP_USEPASVADDRESS, false); after my ftp_login
using ftp_chdir, although my folder names never have spaces anyways
echoing error_get_last() after ftp_nlist returns false. The error show seems unrelated, but is shown below.
My code:
In case it is useful, here is the function I have created. What it is supposed to do is...
take in $fm (filemaker, unrelated to this problem)
take in $FTPConnectionID (the ftp connection I established in the prior to the function call)
take in $FolderPath (the path of the folder on the FTP server for which I want to list files/subfolders recursively - ex: "SomeFolder/Testing")
take in $TextFile (I am writing the paths of every file found on the FTP server to a text file, which was created prior to calling the function)
function createAuditFile($fm, $FTPConnectionID, $FolderPath, $TextFile) {
echo "createAuditFile called for " . $FolderPath . "\n";
//Get the contents of the given path. Will include files and folders.
$FolderContents = ftp_nlist($FTPConnectionID, $FolderPath);
if($FolderContents == false) {
echo "Couldn't get " . $FolderPath . "\n";
echo "ERROR: " . print_r(error_get_last()) . "\n";
} else {
print_r($FolderContents);
}
//Loop through the array, call this function recursively if a folder is found.
if(is_array($FolderContents)) {
foreach($FolderContents as $Content) {
//Create a varaible for the folder path
$ContentPath = $FolderPath . "/" . $Content;
//Call the function recursively if a folder is found
if(pathinfo($Content, PATHINFO_EXTENSION) == "") {
createAuditFile($fm, $FTPConnectionID, $ContentPath, $TextFile);
echo "Recursive call for " . $ContentPath . "\n";
//If a file is found, add the file ftp path to our array
} else {
echo "Writing to file: " . $ContentPath . "\n";
fwrite($TextFile, $ContentPath . "\n");
}
}
}
}
I can provide other code if needed, but I think my question is less of a coding issue, and more of an understanding ftp_nlist issue. I've been stuck on this for hours, so any help is appreciated. And like I said, this function works just fine for most folder paths passed to it, the problem is when there are tens of thousands of files within the folder. Thank you!

php file saved via move_file_upload works when called directly not via exec()

This is the dilemma. I have a script that works perfectly for writing small video files into S3 bucket and local docker.
I need to update the script so it can handle larger files. In order to do that I am using the exec() method in which I run a php script to upload the file so it runs it in the background. This is the code I'm using:
$tempFile = $_FILES['form-file-input']['tmp_name'][$i];
$directory = $config['content_directory'];
echo (is_file($tempFile) ? 'Tempfile is a file' : 'Tempfile is not a file');
echo (is_readable($tempFile) ? ' and tempfile is readable.' : ' and tempfile is not readable.');
echo '<br>'.'This is the file name: '.$newFileName.'<br>';//already defined
chdir('/var/www/webApp/_apps/training_videos/');//required to find i-did-it.php - tested and doesn't affect saving functionality
exec("php i-did-it.php $tempFile $directory $newFileName 2>&1", $out);
var_dump($out);
//$resultado = move_uploaded_file($tempFile, $directory . '/_' . 'videos' . '/' . $newFileName);
//var_dump($resultado);
exit;
BELOW ARE THE CONTENTS OF i-did-it.php
Note that the code reviews before and after executing if the the param is a readable file and that the other params have a valid value. Also note that I set all errors, set a log file and try to catch the last error.
//Set all errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ini_set('log_errors',1);
ini_set('error_log','/var/www/siteContent/logs/log.txt');//verified that log file can be written to
//Get the params
$tempFile = $argv[1];
$directory = $argv[2];
$newFileName = $argv[3];
//Verify that it arrives as a readable file
echo (is_file($tempFile) ? 'Tempfile is a file' : 'Tempfile is not a file');
echo (is_readable($tempFile) ? ' and tempfile is readable.' : ' and tempfile is not readable.');
//Display the params
echo ' Temp file name: '.$tempFile;
echo ', the directory: '.$directory;
echo ' and new file name: '.$newFileName.' *** ';
//Move the file and dump results
$putResult = move_uploaded_file($tempFile, $directory . '/_' . 'videos' . '/' . $newFileName);//original
var_dump($putResult);
print_r(error_get_last());
So what is the problem?
move_uploaded_file commmand is not working when called via exec().
Note that if I replace this line
exec("php i-did-it.php $tempFile $directory $newFileName 2>&1", $out);
with this one
$resultado = move_uploaded_file($tempFile, $directory . '/_' . 'videos' . '/' . $newFileName);
it works!
Note that it is commented in the first snippet.
Those are the results I get
In order to troubleshoot I need to know why the move_uploaded_file command is not working since it only throws true or false. It's known it is false since it doesn't work. I would like to get more errors than that. The method recommended for the task I cannot use since my file is not set like this: $_FILES['file'] but as a variable (It has to be done that way since I'm passing it as a param) so I cannot check errors towards: $_FILES['file']['error']
Reference for the error obtaining approach
https://www.php.net/manual/en/features.file-upload.errors.php
Following the previous example I tried applying it to the var that holds the file to no avail:
if ($tempFile === UPLOAD_ERR_OK) {
//uploading successfully done
} else {
throw new UploadException($tempFile);
}
What do I need to continue?
At this point it would be helpful to know these 2 things:
How can I get the error/warning from move_uploaded_file that is coming back as false?
Any ideas why move_file_upload will work perfectly fine when called directly but fails when called via exec("php myfile.php $param1 $param2 $param3 2>&1", $output)

fuse python script not running in background using php

i am trying to run a file sytem for dropbox ff4d ( from github) in background using php
the purpose if that user will get his dropbox files mount on the server and then i will give the path to a web based explorer (like eXtplorer) so user can manage his file
the script is working fine when using command shell
but when i using the exec function it working printing out the last line of the command shell
and that it . i can not get the folder mount
here the code in php :
$folder = $_POST['foldername'];
$oldumask = umask(0000);
$path = "/var/www/cloudsite/" . $folder;
if(mkdir($path, 0777, true)) {
echo $path . " success directory created ";
} else {
echo $path . "error directory not created ";
}
umask($oldumask);
#$command = '/usr/bin/python /var/www/cloudsite/ff4d/./ff4d.py '. $path .'c7ZYof8Bl0YAAAAAAAAAARThZwAUexbukmv3rMEprPJWFcoQSKGWtWHQBYM40OgC';
$result = exec($command);
if ($result){
echo " </br> execution success";
}else{
echo "</br> error not success";
}
echo $result;
and here what i get in the browser it seems like it working but just hang here nothing mount in the created directory :
var/www/cloudsite/chao success directory created
execution successStarting FUSE...
Within the latest release of my ff4d.py script I've added a "background" switch (-bg).
https://github.com/realriot/ff4d
BTW: Please remove your access key (and revoke it afterwards) because it holds your personal information and ALL your data...

fopen Permission denied on a file with 777 permissions

Since the title of this post is pretty much self-explanatory, I'll just jump to the code :
echo sprintf('%o', fileperms('test.txt'))."<br/>";
fopen("test.txt", "w");
And with this I get :
100777
fopen(test.txt): failed to open stream: Permission denied
Any ideas ?
Edit : Problem solved : there were access control lists on the server that were not configured correctly.
Thanks !
I think its possible that you have write/read permissions on the file but not on the folder. Try this in the public root of your website and see if you can read or write the file.
For safe mode (http://php.net/manual/en/function.fopen.php), php doc's say the following:
Note: When safe mode is enabled, PHP checks whether the directory in
which the script is operating has the same UID (owner) as the script
that is being executed.
Last you also need to be sure that php has access to the folder you are trying to write to.
I had same issue: folder was 777, but fopen does not worked. fopen said permission deny. Make sure your script have a 'good' permissions. maybe it will help you:
echo $dst, file_exists($dst) ? ' exists' : ' does not exist', "\n";
echo $dst, is_readable($dst) ? ' is readable' : ' is NOT readable', "\n";
echo $dst, is_writable($dst) ? ' is writable' : ' is NOT writable', "\n";
$fh = fopen($dst, 'w');
if ( !$fh ) {
echo ' last error: ';
var_dump(error_get_last());
}
I think the problem you are having is file ownership issue ... you can use this to find out the problem
error_reporting(E_ALL);
ini_set('display_errors','On');
$file = "a.jpg";
echo sprintf ( '%o', fileperms ( $file ) ), PHP_EOL;
echo posix_getpwuid ( fileowner ( $file ) ), PHP_EOL; // Get Owner
echo posix_getpwuid ( posix_getuid () ), PHP_EOL; // Get User
if (is_file ( $file )) {
echo "is_file", PHP_EOL;
;
}
if (is_readable ( $file )) {
echo "is_readable", PHP_EOL;
;
}
if (is_writable ( $file )) {
echo "is_readable", PHP_EOL;
}
fopen ( $file, "w" );
I just ran into this issue, and unfortunately the error message provided no clue to the actual reason. I had to give 777 to the file of the class included in the file that gave the error message. The error message only said the php file that calls that class, which already had 777.
So, check the file that is mentioned in the error message (let's say index.php), and then check which classes are instantiated within that file (class-file.php, class-writer.php, etc). Then check the permissions of those files (class-file.php, class-writer.php).
Once I gave permissions for the class file, it worked normally. Perhaps the webhost changed something in their config, since everything worked until a few days ago.

Categories