I have a joomla page on which I want to install a few extensions. However due to the chmod permissions I am unable to upload and install the packages. Following the guide here I can see that in order for the plugins to be installed there are too many folders which permissions have to be changed.
For that I am creating a script which will iterate through each of the required folders and will change the permissions from 0775 to 0777.
<?php
// SET THE DESIRED CHMOD VALUE
if ($_GET['chmod']) {
$ftp_chmod = $_GET['chmod'];
}
else {
$ftp_chmod = "0755";
}
echo "chmod=" . $ftp_chmod . '<br />';
echo getcwd() . '<br />';
$currdir = getcwd(); // get current directory
// ESTABLISH AN FTP LOGIN SESSION
$ftp_server='example.com';
$ftp_user='username';
$ftp_pass='*****';
$conn_id = ftp_connect("$ftp_server");
if ( ftp_login($conn_id, $ftp_user, $ftp_pass) ) {
echo 'FTP CONNECTION IS SUCCESSFULL <br />';
}
else {
echo 'BAD CREDENTIALS';
exit();
}
// Define the folders for which the CHMODE will change the values
// There must be a leading space in front of the path in order for CHMOD to work
$folder_path = array(
' ' . $currdir . '/modules/',
' ' . $currdir . '/plugins/'
' ' . $currdir . '/tmp/',
' ' . $currdir . '/cache/'
);
echo '<br />';
foreach ( $folder_path as $key => $value )
{
$path = trim($value); // The leading space must be trimed fo is_dir() function to work
if ( is_dir($path) == true ) {
echo $path . ' -- ' . '<span style="color: #00B200">OK</span><br />';
echo 'CHMOD ' . $ftp_chmod . ' ' . $value . '<br />';
if (ftp_site($conn_id, 'CHMOD ' . $ftp_chmod . $value)) {
echo 'CHMOD ' . $ftp_chmod . ' IS <span style="color: #00B200">SUCCESSFULL</span><br /><br />';
}
else {
echo '<span style="color: crimson">CHMOD FAILED!</span><br /><br />';
}
}
else {
echo $path . ' -- ' . '<span style="color: crimson"><b>NOT EXIST</b></span><br />';
} // end if ( is_dir($path) == true ) else
} // end foreach ( $folder_path as $key => $value )
ftp_close($conn_id);
?>
Please note that the actual script is much larger due to the many folders that need to be changed. The folders shown in $folder_path = array() are just an example
When I execute the script on my server i get the folowind output:
chmod=0777
/var/www/example/data/www/example.com
FTP CONNECTION IS SUCCESSFULL
/var/www/example/data/www/example.com/modules/ -- OK
CHMOD 0777 /var/www/example/data/www/example.com/modules/
CHMOD FAILED!
/var/www/example/data/www/example.com/plugins/ -- OK
CHMOD 0777 /var/www/example/data/www/example.com/plugins/
CHMOD FAILED!
/var/www/example/data/www/example.com/tmp/ -- OK
CHMOD 0777 /var/www/example/data/www/example.com/tmp/
CHMOD FAILED!
/var/www/example/data/www/example.com/cache/ -- OK
CHMOD 0777 /var/www/example/data/www/example.com/cache/
CHMOD FAILED!
DOES ANYONE HAVE ANY IDEA ON HOW TO CHANGE THE CHMOD VALUE ON SO MANY FOLDERS?
UPDATE:
I also have to mention that I have tried to change the CHMOD value on each folder individually via FTP client and it is successfull. The problem comes when i have to change them through the script. The same acc with root privilege access is used from the FTP client and the script to change the files!
I have found a solution to the problem. What I did was a small modification to the foreach part of the script which made it work. Basically I just subtracted the required number of characters from the path returned from the getcwd() and that solved my problem.
Here is the change that i did:
---- REST OF THE SCRIPT OMITED -----
foreach ( $folder_path as $key => $value )
{
$path = trim($value); // The leading space must be trimed fo is_dis() function to work
if ( is_dir($path) == true ) {
$value_short = substr($value, 19); // <------------- Subtruct the required number od chars in order to create a relative path
echo $path . ' -- ' . '<span style="color: #00B200">OK</span><br />';
echo 'CHMOD ' . $ftp_chmod . ' ' . $value_short . '<br />';
if (ftp_site($conn_id, "CHMOD $ftp_chmod $value_short")) { // <-------------- Use the relative path in the function
echo 'CHMOD ' . $ftp_chmod . ' IS <span style="color: #00B200">SUCCESSFULL</span><br /><br />';
}
else {
echo '<span style="color: crimson">CHMOD FAILED!</span><br /><br />';
}
}
else {
echo $path . ' -- ' . '<span style="color: crimson"><b>NOT EXIST</b></span><br />';
} // end if ( is_dir($path) == true ) else
} // end foreach ( $folder_path as $key => $value )
---- REST OF THE SCRIPT OMITED -----
Did you try just enabling Joomla's FTP layer before installing components/plugins etc?
Related
I am working on a PHP code as shown below in which conversion of mp4 into mp3 is happening at Line B.
I have added if block after system command to print Conversion Completed on the webpage once the conversion is complete but it doesn't seem to work.
Php code:
if (isset($_POST['id']))
{
for($i=0; $i <count($mp4_files); $i++) {
if($i == $_POST['id']) {
$f = $mp4_files[$i];
$parts = pathinfo($f);
switch ($parts['extension'])
{
case 'mp4' :
$filePath = $src_dir . DS . $f;
print_r($f); // Line A
system('ffmpeg -i ' . $filePath . ' -map 0:2 -ac 1 ' . $destination_dir . DS . $parts['filename'] . '.mp3', $result); // Line B
if($result)
{
echo "Conversion Completed";
}
}
}
}
}
Problem Statement:
I am wondering what changes I should make in the PHP code above so that once the conversion is complete; on the webpage, it should print Conversion Completed.
You can use shell_exec to get a return value and then put that in an if statement like this
$output = shell_exec('ffmpeg -i ' . $filePath . ' -map 0:2 -ac 1 ' . $destination_dir . DS . $parts['filename'] . '.mp3');
if ($output) {
echo "Conversion Completed!";
// or redirect here
}
Also, make sure to sanitize your inputs as they are exposed to a CLI interface.
I am organizing my folders, the thing is I can't move my files due to permissions but when I checked, folder being created, files being moved and upper level folder is associated with same user and group apache:apache. I am also running this php code with apache user. What could be the problem?
Quick view;
exec('mv '.$path.$result->token.'-*.mp4 '.$path.getWeekNo($result->date).'/ 2>&1', $moveOut, $moveResult);
Code:
function processFilesByID($db, $path, $id, $type ='token')
{
$result = $db->get_row('SELECT id,token,title,date FROM DB_TABLE where id="' . $id . '";');
/* Debug - Start */
$db->debug();
// return "ID: " . $result->id . "<br />Token: " . $result->token . "<br />Title: " . $result->title . "<br />Date: " . $result->date;
/* Debug - End */
if (isset($result)) {
// Check if any file exists with given token command.
exec('ls -1 ' . $path . $result->token . '-* | wc -l', $out, $res);
// Check if noOfFile is greater than 0 and less than 10. Also check if command succeed.
if ($res == 0 && $out[0] > 0 && $out[0] < 10) {
// Move its media files [WHERE PROBLEM OCCURS]
exec('mv '.$path.$result->token.'-*.mp4 '.$path.getWeekNo($result->date).'/ 2>&1', $moveOut, $moveResult);
if($moveResult == 0){
// Double check if it's moved succesfully.
exec('ls -1 ' . $path.getWeekNo($result->date).'/'. $result->token . '-* | wc -l', $newOut, $newRes);
if ($newRes == 0 && $newOut[0] > 0 && $newOut[0] < 10) {
// Update DB with new path
if($db->query("UPDATE DB_TABLE SET token = '".getWeekNo($result->date).'/'.$result->token."' WHERE id= '".$result->id."'")){
}else{
}...
Output
Array
(
[0] => mv: cannot move '/###PATH###/+++FILE-NAME1+++' to '/###PATH###/16401c4a73848b7be4720d2e13a50a430c7b/+++FILE-NAME1+++': Permission denied
[1] => mv: cannot move '/###PATH###/+++FILE-NAME2+++' to '/###PATH###/16401c4a73848b7be4720d2e13a50a430c7b/+++FILE-NAME2+++': Permission denied
[2] => mv: cannot move '/###PATH###/+++FILE-NAME3+++' to '/###PATH###/16401c4a73848b7be4720d2e13a50a430c7b/+++FILE-NAME3+++': Permission denied
)
I also tried with php's built-in command but no luck so far.
I'm trying the PEAR Net_Nmap package from here:
https://pear.php.net/package/Net_Nmap/
I have Nmap installed on my Windows 10 machine.
I found the following code that should do the job.
Is there something I should configure before I use PEAR?
I'm getting 2 errors:
Warning: require_once(XML/Parser.php): failed to open stream: No such file or directory in C:\xampp\htdocs\Net_Nmap-master\Net\Nmap\Parser.php on line 31
Fatal error: require_once(): Failed opening required 'XML/Parser.php' (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\Net_Nmap-master\Net\Nmap\Parser.php on line 31
<?php
// Scan network to retrieve hosts and services information.
require_once 'Net/Nmap.php';
//Define the target and options
$target = array('193.95.13.16','www.google.com');
$options = array('nmap_binary' => 'C:\Program Files (x86)\Nmap');
try {
$nmap = new Net_Nmap($options);
$nmap_options = array(
'os_detection' => true,
'service_info' => true,
'port_ranges' => 'U:53,111,137,T:21-25,80,139,8080',
// Only specified ports
);
$nmap->enableOptions($nmap_options);
// Scan
$res = $nmap->scan($target);
// Get failed hosts
$failed_to_resolve = $nmap->getFailedToResolveHosts();
if (count($failed_to_resolve) > 0) {
echo 'Failed to resolve given hostname/IP: ' .
implode (', ', $failed_to_resolve) .
"\n";
}
//Parse XML Output to retrieve Hosts Object
$hosts = $nmap->parseXMLOutput();
//Print results
foreach ($hosts as $key => $host) {
echo 'Hostname: ' . $host->getHostname() . "\n";
echo 'Address: ' . $host->getAddress() . "\n";
echo 'OS: ' . $host->getOS() . "\n";
echo 'Status: ' . $host->getStatus . "\n";
$services = $host->getServices();
echo 'Number of discovered services: ' . count($services) . "\n";
foreach ($services as $key => $service) {
echo "\n";
echo 'Service Name: ' . $service->name . "\n";
echo 'Port: ' . $service->port . "\n";
echo 'Protocol: ' . $service->protocol . "\n";
echo 'Product information: ' . $service->product . "\n";
echo 'Product version: ' . $service->version . "\n";
echo 'Product additional info: ' . $service->extrainfo . "\n";
}
}
}
catch (Net_Nmap_Exception $ne) {
echo $ne->getMessage();
}
?>
You did not use the PEAR installer to install the net_nmap package, but probably downloaded the .tgz file and extracted it.
Now you are missing the dependencies which are listed on the bottom left of the Net_NMap page. Install them.
I am not getting Output though i include all the files
<?php
/**
* Scan network to retrieve hosts and services information.
*/
require_once 'C:/xampp/php/pear/Net/Nmap.php';
//Define the target to scan
$target = array('127.0.0.1','localhost');
$options = array('nmap_binary' => 'C:/Program Files (x86)/Nmap');
try {
$nmap = new Net_Nmap($options);
//Enable nmap options
$nmap_options = array('os_detection' => true,
'service_info' => true,
'port_ranges' => 'U:53,111,137,T:21-25,80,139,8080',//to scan only specified ports
);
$nmap->enableOptions($nmap_options);
//Scan target
$res = $nmap->scan($target);
//Get failed hosts
$failed_to_resolve = $nmap->getFailedToResolveHosts();
if (count($failed_to_resolve) > 0) {
echo 'Failed to resolve given hostname/IP: ' .
implode (', ', $failed_to_resolve) .
"\n";
}
//Parse XML Output to retrieve Hosts Object
$hosts = $nmap->parseXMLOutput();
//Print results
foreach ($hosts as $key => $host) {
echo 'Hostname: ' . $host->getHostname() . "\n";
echo 'Address: ' . $host->getAddress() . "\n";
echo 'OS: ' . $host->getOS() . "\n";
echo 'Status: ' . $host->getStatus . "\n";
$services = $host->getServices();
echo 'Number of discovered services: ' . count($services) . "\n";
foreach ($services as $key => $service) {
echo "\n";
echo 'Service Name: ' . $service->name . "\n";
echo 'Port: ' . $service->port . "\n";
echo 'Protocol: ' . $service->protocol . "\n";
echo 'Product information: ' . $service->product . "\n";
echo 'Product version: ' . $service->version . "\n";
echo 'Product additional info: ' . $service->extrainfo . "\n";
}
}
} catch (Net_Nmap_Exception $ne) {
echo $ne->getMessage();
}
?>
if your program do not have any output, it means you have syntax error, fatal error or segment error.
change php.ini setting, enable, dispaly_errors, and error_reporting with E_ALL
usually, this is enough. you can see the error message and fix the bug.
if there still not error message, try create a simple file, only show phpinfo().
if this is ok, usually, you do not have start up error, if not, enable display_startup_errors in php.ini
if you still have no error, check your apache or nginx configure, you probably config the site wrong.
if you still have no error, congratulation! you got segment error.
use gdb to find the reason.
I'm using a Linux local computer and need to backup/mirror some very large file structures regularly. I only have access to SFTP.
I was after a simple one click solution. I originally tried to write the little script in BASH but I've never used it before and am not up to scratch with the syntax so I resorted to PHP. (I do understand PHP is not designed for this kind of work, but I'm on a tight time scale and don't have the time to get into BASH atm)
<?php
//init
parse_str(implode('&', array_slice($argv, 1)), $_GET);
$error = array();
$lPrefix = '/home/hozza/Sites/';
$archiveLocation = '/home/hozza/Backups/';
$lDir = isset($_GET['l']) ? $_GET['l'] : $error[] = 'Local Directory Required';
$rDir = isset($_GET['r']) ? $_GET['r'] : $error[] = 'Remote Directory Required';
$bookmark = isset($_GET['b']) ? $_GET['b'] : $error[] = 'lftp Bookmark Required';
//Check for args
if(count($error) == 0) {
$archiveName = end(explode('/', $lDir)) . '_' . date('Y-m-d_H-i');
//Validate local dir
if(is_dir($lPrefix . $lDir)) {
//preserve Sublime Text 2 config SFTP files
$ST2_SFTP_conf = false;
if(file_exists($lPrefix . $lDir . '/sftp-config.json')) {
$ST2_SFTP_conf = file_get_contents($lPrefix . $lDir . '/sftp-config.json');
unlink($lPrefix . $lDir . '/sftp-config.json');
}
//Start mirror
$lftOutput = explode("\n", shell_exec('lftp -e "mirror -e -p --parallel=10 --log=' . $archiveLocation . 'logs/' . $archiveName . '.txt ' . $rDir . '/ ' . $lPrefix . $lDir . '/; exit top" ' . $bookmark));
//Tar regardless of lftp error or success
$tarOutput = shell_exec('cd ' . $lPrefix . ' && tar -czf ' . $archiveLocation . $archiveName . '.tar.gz ' . $lDir);
//Output completion or errors
shell_exec('notify-send -i gnome-network-properties -t 0 "Mirror & Archive Complete" "' . $archiveName . '\n\n' . implode('\n', $lftOutput) . $tarOutput . '"');
//put back ST2 SFTP conf
if($ST2_SFTP_conf != false) file_put_contents($lPrefix . $lDir . '/sftp-config.json', $ST2_SFTP_conf);
exit;
}
else shell_exec('notify-send -i error -t 0 "Mirror & Archive Error" "' . date('Y-m-d') . ' ' . date('H-i') . '\n' . $lDir . ' \n Does not exist! D:"');
}
else shell_exec('notify-send -i error -t 0 "Mirror & Archive Error" "' . date('Y-m-d') . ' ' . date('H-i') . '\n' . implode('\n', $error) . '"');
?>
It can be run for many sites via a short-cut like so...
terminator -T "Mirror & Archive" -e "php ~/Programs/mirror.php l=local-dir_path r=./ b=lftp-bookmark-name"
If no password is in the LFTP bookmark (there shouldn’t be as it's stored in plain text) the terminal prompts for a password, after the script has run, a nice notification is given with some info about files/folders/speed etc.
However, when the script is running in a terminal, only the "input password" bit is output to the terminal, I would like all the output displayed in the terminal (normally that would display what file/folder is currently working with etc.)
Anyone know how to do that?
IIRC the reason that you see the password prompt output to the terminal is that it is using stderr. You could try redirecting stdout to stderr for your commands which should show you the 'real-time' progress. Tack this on to the end of the shell_exec() command: 1>&2
ie:
shell_exec('lftp -e "mirror -e -p --parallel=10 --log=' . $archiveLocation . 'logs/' . $archiveName . '.txt ' . $rDir . '/ ' . $lPrefix . $lDir . '/; exit top" ' . $bookmark . ' 1>&2')
However, this will preclude you from having anything returned by shell_exec for logging purposes. What I would suggest is something like:
$log_stem = '/tmp/' . time() . '_'; // ie: /tmp/1357581737_
$lfOutfile = $log_stem . 'lftp.log';
$tarOutfile = $log_stem . 'tar.log';
shell_exec('lftp -blah | tee ' . $lfOutfile ' 1>&2' );
shell_exec('tar -blah | tee ' . $tarOutfile ' 1>&2' );
$lfOut = file_get_contents($lfOutfile);
$tarOut = file_get_contetns(tarOutfile);
// remove tmp files
unlink($lfOutfile);
unlink($tarOutfile);
Which will capture a copy of the output to a file before redirecting the output to stderr so you can watch it live.
However, if you want to run this via cron I would recommend against writing anything to stderr that is not an error, otherwise cron will send a warning email every time it is run.
I think the last answer was close:
Either this:
shell_exec('lftp -blah |& tee ' . $lfOutfile );
shell_exec('tar -blah |& tee ' . $tarOutfile );
Or if that still doesn't work try this:
shell_exec('lftp -blah 2>&1 | tee ' . $lfOutfile );
shell_exec('tar -blah 2>&1 | tee ' . $tarOutfile );