php exec('echo 1 > ~/cctv_config/cctvstatus') does not work - php

Here is part of the code that I have in php file:
function checkSetStatus($checkSet) {
//other if options here
if ($checkSet == '2') {
exec('echo 0 > ~/cctv_config/cctvstatus.log');
sleep(1);
exec('echo "$(date) | setOff" >> weblog.log');
return (int) exec('cat ~/cctv_config/cctvstatus');
}
}
Problem is with line:
exec('echo 0 > ~/cctv_config/cctvstatus.log');
When I trigger command
echo 0 > ~/cctv_config/cctvstatus.log
in linux commandline, it works fine. However if it is triggered indirectly by exec function in php file it does not make any changes in targeted file.
In apache error log file there is infomation that
file or directory ~/cctv_config/cctvstatus.log can not be created
(I already changed mode of cctvstatus.log to 777). Similar information is logged as a result of triggering this line:
exec('cat ~/cctv_config/cctvstatus');
In this case it is logged that such file or directory does not exist (There is one more issue - in exec with cat I am wondering if rather passthru function should not be used).

The home directory of the user of the PHP instance is not the same as the user you are testing the command with.
You are reffering to the home directory by using the ~ (tilde) before the path.
Change the path to the full path instead:
function checkSetStatus($checkSet) {
//other if options here
if ($checkSet == '2') {
exec('echo 0 > /home/myuser/cctv_config/cctvstatus.log');
sleep(1);
exec('echo "$(date) | setOff" >> weblog.log');
return (int) exec('cat /home/myuser/cctv_config/cctvstatus');
}
}

Related

How can I verify if a file exist inside container docker?

I can copy it with this code:
exec('docker cp selenium:"/home/seluser/Downloads/'.$fileName.'" '.$filePath.'.pdf');
but I need verify before if it exist
You could use: exec(ls <your file> > /dev/null 2>&1 && echo 0 || echo 1) which will output 1 if the file <your file> does not exist check the output or replace echo 0 with the command to execute in case the file exist

How to find out the process or script which call php bash script

I have php bash script that do some database processing. All I need to know is the caller of this script. I don't know if it's process or other script. So is there some way to know process id or script name of caller?
Script is running by some process and its code starts with interpreter path "#!/usr/bin/php". This file called as bash script only.
OS: Centos 6.5
You can try something like this
<?php
Check for a current process by filename
function processExists($file = false) {
$exists = false;
$file = $file ? $file : __FILE__;
// Check if file is in process list
exec("ps -C $file -o pid=", $pids);
if (count($pids) > 1) {
$exists = true;
}
return $exists;
}
?>
This will check against the filename that you're trying to track. If you need the process id, just adjust what's in in the exec or return the $pids.
try this ---
$mystring = "script_running";
exec("ps aux | grep \"${mystring}\" | grep -v grep | awk '{ print $2 }' | head -1", $out);
print "The PID is: " . $out[0];
ps aux is more descriptive of what's running.

Bash how to get full script name from PID

I have this php function that checks the script's name from the given PID, and compares it to itself.
function isRunning($pid) {
$filename = exec('ps -p '.$pid.' -o "%c"');
$self = basename($_SERVER['SCRIPT_NAME']);
return ($filename == $self) ? TRUE : FALSE;
}
From what I know, I usually use this command to get the script name from the PID:
ps -o PID -o "%c"
It returns me the filename, but only the first 15 characters.
Since my script's name is
daily_system_check.php
the function always returns FALSE, because it's comparing itself with
daily_system_ch
Is there another bash command for Centos 6 that will return me script's full name?
You didn't specify what is your OS, but in Ubuntu Linux I can see full name of the script with adding --context to the ps call:
# ps -p 17165 --context
PID CONTEXT COMMAND
17165 unconfined /bin/bash ./testing_long_script_name.sh
#
read the the proc cmdline file:
cat /proc/$pid/cmdline | awk 'BEGIN {FS="\0"} {print $2}'
There seems to be no flag or collumn in "ps" command to show the whole filename without the filepath or it being cutoff. PHP's basename() gets the job done.
function isRunning($pid) {
$filename = basename(exec('ps -o cmd= '.$pid));
$self = basename($_SERVER['SCRIPT_NAME']);
return ($filename == $self) ? TRUE : FALSE;
}

Running a python file from php does not generate the output file

I have a problem running another file from php. I want my php params to be the output of running a python file that calls another file itself.
Here is my php file:
<?php
if (isset($_POST['submit'])) {
$params = solve();
}
function solve() {
exec("python array.py", $output);
return $output;
}
?>
If array.py is simply:
if __name__ == "__main__":
print 1
print 2
print 3
print 4
I will get 1,2,3,4 for my output, but I as soon as I change array.py to the following file that calls os.system, I don't get anything. So the new array.py is:
import os
def main():
os.system("python test.py") #test.py creates tmp.txt with 4 lines w/ values 1,2,3,4
def output():
f = open("tmp.txt", "r")
myReturn = []
currentline = f.readline()
while currentline:
val = currentline[:-1] #Getting rid of '\n'
val = int(val)
myReturn = myReturn + [val]
currentline = f.readline()
f.close()
return myReturn
if __name__ == "__main__":
main()
o = output()
print o[0]
print o[1]
print o[2]
print o[3]
Also if I just run test.py, the output is the file tmp.txt:
1
2
3
4
So now, when I run my php file, the output tmp.txt is not even created in the directory and as a result I don't get any output from my php either.
I am not sure why this is happening because when I just run array.py myself, I get the desired output, and the tmp file is created.
EDIT:
I forgot to include: import os above.
Change exec to:
exec("python array.py 2>&1", $output)
Or check the web server or php error log. This will return the error output from the python script to your php script (not normally what you want in production).

Is there a better way of writing a git pre-commit hook to check any php file in a commit for parse errors?

What I have so far is
#!/bin/sh
php_syntax_check()
{
retval=0
for i in $(git-diff-index --name-only --cached HEAD -- | grep -e '\.php$'); do
if [ -f $i ]; then
output=$(php -l $i)
retval=$?
if [ $retval -gt 0 ]; then
echo "=============================================================================="
echo "Unstaging $i for the commit due to the follow parse errors"
echo "$output"
git reset -q HEAD $i
fi
fi
done
if [ $retval -gt 0 ]; then
exit $retval
fi
}
php_syntax_check
If the commit is a partial commit (not all the changes in the working tree are committed), then this make give incorrect results since it tests the working copy and not the staged copy.
One way to do this could be:
git diff --cached --name-only --diff-filter=ACMR | xargs git checkout-index --prefix=$TMPDIR/ --
find $TMPDIR -name '*.php' -print | xargs -n 1 php -l
Which would make a copy of the staged images into a scratch space and then run the test command on them there. If any of the files include other files in the build then you may have to recreate the whole staged image in the test tree and then test the changed files there (See: Git pre-commit hook : changed/added files).
I'm sorry if it's offtopic, but aren't you supposed to run some kind of automated tests (which would imply that the code has no syntax errors) before doing a commit?
If you've got the php5-cli installed you can write your pre-commit in PHP and use the syntax your more familiar with.
Just do something more like.
#!/usr/bin/php
<?php /* Your pre-commit check. */ ?>
My PHP implementation of the pre-commit hook checks whether the modified files in git are 'error free' and are as per PSR2 standard using either 'php-code-sniffer' or 'php-cs-fixer'
#!/usr/local/bin/php
<?php
/**
* Collect all files which have been added, copied or
* modified and store them in an array - output
*/
exec('git diff --cached --name-only --diff-filter=ACM', $output);
$isViolated = 0;
$violatedFiles = array();
// $php_cs_path = "/usr/local/bin/php-cs-fixer";
$php_cs_path = "~/.composer/vendor/bin/phpcs";
foreach ($output as $fileName) {
// Consider only PHP file for processing
if (pathinfo($fileName, PATHINFO_EXTENSION) == "php") {
$psr_output = array();
// Put the changes to be made in $psr_output, if not as per PSR2 standard
// php-cs-fixer
// exec("{$php_cs_path} fix {$fileName} --rules=#PSR2 --dry-run --diff", $psr_output, $return);
// php-code-sniffer
exec("{$php_cs_path} --standard=PSR2 --colors -n {$fileName}", $psr_output, $return);
if ($return != 0) {
$isViolated = 1;
$violatedFiles[] = $fileName;
echo implode("\n", $psr_output), "\n";
}
}
}
if ($isViolated == 1) {
echo "\n---------------------------- IMPORTANT --------------------------------\n";
echo "\nPlease use the suggestions above to fix the code in the following file: \n";
echo " => " . implode("\n => ", $violatedFiles);
echo "\n-----------------------------------------------------------------------\n\n\n";
exit(1);
} else {
echo "\n => Committed Successfully :-)\n\n";
exit(0);
}

Categories