PHP: echo return parameters from powershell script - php

I want to execute powershell script through PHP, And want return parameters in PHP variable. So for testing, I have tried to get windows version from powershell script.
<?php
exec("C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe gwmi win32_operatingsystem | % caption",$output );
echo( '<pre>' );
var_dump( $output );
echo( '</pre>' );
?>
output:
C:\wamp64\www\py\indexPHP.php:6:
array (size=0)
empty
but it returns an empty array.

Your call is incorrect.
exec("C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -Command (GWMI Win32_OperatingSystem).Caption", $Output);

Related

How execute Powershell script in PHP and output result?

Studying the interaction of Php with Powershell
Try the simplest script:
<?php
$query = shell_exec("powershell.exe -File E:\test.ps1");
echo $query;
?>
In the script test.ps1 - for example "Test-Connection Server"
Need to the answer in Powershell returned to the page Php, but in response to a white paper...
Please tell me some solution for this problem.. do Not have shell_exec. There may be other options?
You can store the output of powershell script in a variable and then echo it. Just change $psDIR to your PowerShell path (e.g. %SystemRoot%\system32\WindowsPowerShell\v2.0\)
<?php
$psPath = "powershell.exe";
$psDIR = "PathToPowrshell";
$psScript = "E:\test.ps1";
$runScript = $psDIR. $psScript;
$runCMD = $psPath." ".$runScript;
$output= shell_exec($runCMD);
echo( '<pre>' );
echo( $output );
echo( '</pre>' );
?>

Execute Python Script From PHP Script

I have python file which is newtry.py and this is my code:
print ("hello world")
I also have php file which is importKeyword.php and this is my code:
<?php
$python = `python newtry.py`;
echo $python;
echo "yes";
?>
I want to print "hello world" from python in the browser but it only print "yes" which is from php file. I have look at this solution which is using backquote operator ( enter link description here ) and wondering why I can't make it.
You can use exec function
exec('python newtry.py', $output);
var_dump($output);
use 2>&1 to redirect the output
<?php
exec("python newtry.py 2>&1", $python);
print_r($python);
echo "yes";
?>

PHP Echo with System Command

i need to call a variable ($id) within a php system command. I'm automating a solr curl delete command, and it works with a static id, but i need to echo the $id so it deletes the correct document.
code is:
<?php
echo '<pre>';
$last_line = system('curl http://localhost:8983/solr/imagedb/update?commit=true --data \'<delete><query>id\:<?php echo $id; ?></query></delete>\' -H \'Content-type:text/xml; charset=utf-8\'', $retval);
// Printing additional info
echo '
</pre>
<hr />Last line of the output: ' . $last_line . '
<hr />Return value: ' . $retval;
?>
The code shows no error but the document is not deleted so it is not grabbing the $id variable. Its an echo within a php system command. How to make it work?
You can't use <?php echo $id; ?> inside a string. That only works when you're out of PHP execution mode. Use string concatenation.
$last_line = system('curl http://localhost:8983/solr/imagedb/update?commit=true --data \'<delete><query>id\:' . $id . '</query></delete>\' -H \'Content-type:text/xml; charset=utf-8\'', $retval);
Remove php tags and enclose a variable in single quotes in your system call. Now your variable along with php tags is passed as a string.
so update this line:
$last_line = system('curl http://localhost:8983/solr/imagedb/update?commit=true --data \'<delete><query>id\:<?php echo $id; ?></query></delete>\' -H \'Content-type:text/xml; charset=utf-8\'', $retval);
to:
$last_line = system('curl http://localhost:8983/solr/imagedb/update?commit=true --data \'<delete><query>id\:'.$id.'</query></delete>\' -H \'Content-type:text/xml; charset=utf-8\'', $retval);

PHP json_decode does not work

I am trying the following code to receive JSON . However the decode does not give a result. It works for a copy of the same string with escape slashes.
<?php
$input = file_get_contents('php://input');
logToFile("post.txt",$input);
#Output: {"id":"id1","model":"model1","version":"v1","software":["s1","s2","s3"]}
$data = json_decode($input,true);
logToFile("post.txt",$data['version']);
#Output:Empty result
### Works
$data1 = json_decode("{\"id\":\"id1\",\"model\":\"model1\",\"version\":\"v1\",\"software\":[\"s1\",\"s2\",\"s3\"]}",true);
logToFile("post.txt",$data1['version']);
#Output:v1
function logToFile($filename,$msg)
{
$fd=fopen($filename,"a");
$str="[".date("Y/m/d h:i:s")."]".$msg;
fwrite($fd,$str."\n");
fclose($fd);
}
?>
I am using PHP 5.4. So it's not a problem in magic quotes. Any help?
I don't think the problem is with the json_decode.
$input = '{"id":"id1","model":"model1","version":"v1","software":["s1","s2","s3"]}';
$data = json_decode($input,true);
echo $data['version'];
Works fine.
So if you go:
echo "<pre>";
print_r( $input );
echo "</pre>";
After you get the $input from the file. Does it appear OK ?

Shortcut for echo "<pre>";print_r($myarray);echo "</pre>";

Is there a Shortcut for
echo "<pre>";
print_r($myarray);
echo "</pre>";
It is really annoying typing those just to get a readable format of an array.
This is the shortest:
echo '<pre>',print_r($arr,1),'</pre>';
The closing tag can also be omitted.
Nope, you'd just have to create your own function:
function printr($data) {
echo "<pre>";
print_r($data);
echo "</pre>";
}
Apparantly, in 2018, people are still coming back to this question. The above would not be my current answer. I'd say: teach your editor to do it for you. I have a whole bunch of debug shortcuts, but my most used is vardd which expands to: var_dump(__FILE__ . ':' . __LINE__, $VAR$);die();
You can configure this in PHPStorm as a live template.
You can set the second parameter of print_r to true to get the output returned rather than directly printed:
$output = print_r($myarray, true);
You can use this to fit everything into one echo (don’t forget htmlspecialchars if you want to print it into HTML):
echo "<pre>", htmlspecialchars(print_r($myarray, true)), "</pre>";
If you then put this into a custom function, it is just as easy as using print_r:
function printr($a) {
echo "<pre>", htmlspecialchars(print_r($a, true)), "</pre>";
}
Probably not helpful, but if the array is the only thing that you'll be displaying, you could always set
header('Content-type: text/plain');
echo '<pre>' . print_r( $myarray, true ) . '</pre>';
From the PHP.net print_r() docs:
When [the second] parameter is set to TRUE, print_r() will return the information rather than print it.
teach your editor to do it-
after writing "pr_" tab i get exactly
print("<pre>");
print_r($);
print("</pre>");
with the cursor just after the $
i did it on textmate by adding this snippet:
print("<pre>");
print_r(\$${1:});
print("</pre>");
If you use VS CODE, you can use :
Ctrl + Shift + P -> Configure User Snippets -> PHP -> Enter
After that you can input code to file php.json :
"Show variable user want to see": {
"prefix": "pre_",
"body": [
"echo '<pre>';",
"print_r($variable);",
"echo '</pre>';"
],
"description": "Show variable user want to see"
}
After that you save file php.json, then you return to the first file with any extension .php and input pre_ -> Enter
Done, I hope it helps.
If you are using XDebug simply use
var_dump($variable);
This will dump the variable like print_r does - but nicely formatted and in a <pre>.
(If you don't use XDebug then var_dump will be as badly formated as print_r without <pre>.)
echo "<pre/>"; print_r($array);
Both old and accepted, however, I'll just leave this here:
function dump(){
echo (php_sapi_name() !== 'cli') ? '<pre>' : '';
foreach(func_get_args() as $arg){
echo preg_replace('#\n{2,}#', "\n", print_r($arg, true));
}
echo (php_sapi_name() !== 'cli') ? '</pre>' : '';
}
Takes an arbitrary number of arguments, and wraps each in <pre> for CGI requests. In CLI requests it skips the <pre> tag generation for clean output.
dump(array('foo'), array('bar', 'zip'));
/*
CGI request CLI request
<pre> Array
Array (
( [0] => foo
[0] => foo )
) Array
</pre> (
<pre> [0] => bar
Array [1] => zip
( )
[0] => bar
[0] => zip
)
</pre>
I just add function pr() to the global scope of my project.
For example, you can define the following function to global.inc (if you have) which will be included into your index.php of your site. Or you can directly define this function at the top of index.php of root directory.
function pr($obj)
{
echo "<pre>";
print_r ($obj);
echo "</pre>";
}
Just write
print_r($myarray); //it will display you content of an array $myarray
exit(); //it will not execute further codes after displaying your array
Maybe you can build a function / static class Method that does exactly that. I use Kohana which has a nice function called:
Kohana::Debug
That will do what you want. That's reduces it to only one line. A simple function will look like
function debug($input) {
echo "<pre>";
print_r($input);
echo "</pre>";
}
function printr($data)
{
echo "<pre>";
print_r($data);
echo "</pre>";
}
And call your function on the page you need, don't forget to include the file where you put your function in for example: functions.php
include('functions.php');
printr($data);
I would go for closing the php tag and then output the <pre></pre> as html, so PHP doesn't have to process it before echoing it:
?>
<pre><?=print_r($arr,1)?></pre>
<?php
That should also be faster (not notable for this short piece) in general. Using can be used as shortcode for PHP code.
<?php
$people = array(
"maurice"=> array("name"=>"Andrew",
"age"=>40,
"gender"=>"male"),
"muteti" => array("name"=>"Francisca",
"age"=>30,
"gender"=>"Female")
);
'<pre>'.
print_r($people).
'</pre>';
/*foreach ($people as $key => $value) {
echo "<h2><strong>$key</strong></h2><br>";
foreach ($value as $values) {
echo $values."<br>";;
}
}*/
//echo $people['maurice']['name'];
?>
I generally like to create my own function as has been stated above. However I like to add a few things to it so that if I accidentally leave in debugging code I can quickly find it in the code base. Maybe this will help someone else out.
function _pr($d) {
echo "<div style='border: 1px solid#ccc; padding: 10px;'>";
echo '<strong>' . debug_backtrace()[0]['file'] . ' ' . debug_backtrace()[0]['line'] . '</strong>';
echo "</div>";
echo '<pre>';
if(is_array($d)) {
print_r($d);
} else if(is_object($d)) {
var_dump($d);
}
echo '</pre>';
}
You can create Shortcut key in Sublime Text Editor using Preferences -> Key Bindings
Now add below code on right-side of Key Bindings within square bracket []
{
"keys": ["ctrl+shift+c"],
"command": "insert_snippet",
"args": { "contents": "echo \"<pre>\";\nprint_r(${0:\\$variable_to_debug});\necho \"</pre>\";\ndie();\n" }
}
Enjoy your ctrl+shift+c shortcut as a Pretty Print of PHP.
Download AutoHotKey program from the official website: [https://www.autohotkey.com/]
After Installation process, right click in any folder and you will get as the following image: https://i.stack.imgur.com/n2Rwz.png
Select AutoHotKey Script file, open it with notePad or any text editor Write the following in the file:
::Your_Shortcut::echo '<pre>';var_dump();echo '</pre>';exit();
the first ::Your_Shortcut means the shortcut you want, I choose for example vard.
Save the file.
Double-click on the file to run it, after that your shortcut is ready.
You can test it by write your shortcut and click space.
For more simpler way
echo ""; print_r($test); exit();

Categories