How to get a certain text from this function? - php

I'd like to know how to get the text Physical Address. . . . . . . . . : xx-xx-xx-xx-xx-xx from $cmd = system('ipconfig /all').
When I write $ cmd = system('ipconfig /all') there is atext displayed in my screen. Even without echoing the $cmd. How to remove the text but some portion of the text. I'd like to get 38 chars after the text Physical Address
note: more importantly to get a rid of the displayed text of system('ipconfig /all') but still contain it in a variable

You need to test a bit because i dont know exactly your IPCONFIG results (varies from OS to OS) but here is a very close to what you want:
<?php
$command = "ipconfig /all";
$output = shell_exec($command);
$output = explode(PHP_EOL, $output);
$output = $output[0];
$result = explode("Physical Address",$output);
echo substr($result[1],20,17);
?>
Keep in mind you may need to change echo substr($result[1],20,15); to fit your needs, as it varies depending how many network cards you have etc.

In addition to Mohammad's answer you could use output buffering.
something like:
ob_start();
system('ipconfig /all');
$output = ob_get_clean();
print_r( $output);
should capture everything coming back from the command. You can then manipulate it however you like as a string.

$val = shell_exec('ipconfig /all');
echo $val;

You can send second parameter to system function to get output of command:
system('ipconfig /all', $output); //$output is result of command
Also you can use shell_exec function to only return output and not echo by default as below:
$output = shell_exec('ipconfig /all');

Related

How do I properly log only files changed with PHP shell_exec?

I have created a script which copies changed files from a development site to a live site that works flawlessly.
I'm now trying to log which files were changed and then add that list to a DB table that keeps track of changes.
I use shell_exec to run rsync for the copy and then am trying to trim the output and add \n for formatting.
The output is something like "sending incremental file list portalMaint.php sent 27,659 bytes received 81 bytes 55,480.00 bytes/sec total size is 101,582,367 speedup is 3,661.95".
Here is the code I have:
$command = "sudo -S rsync -av ".$exclude." ".$source." ".$dest." --delete 2>&1";
// --- Issue command and check for errors.
$exErrors = shell_exec($command);
if (stripos($exErrors, "error:") !== false || stripos($exErrors, "[sudo]")) {
$error = "Uh-OH, we have a problem! Don't Panic!";
$errors = $exErrors;
include("head.php");
include("template_".$currentPage.".html");
include("foot.php");
exit();
}else{
$filesCopied = $exErrors;
$filesCopied = substr($filesCopied, 0, strrpos($filesCopied, " sent "));
$filesCopied = preg_replace("/\s+/", "\n", $filesCopied);
}
This does NOT work. $filesCopied ends up being blank.
If I comment out $filesCopied = substr($filesCopied, 0, strrpos($filesCopied, " sent ")); I get the entire output unformatted.
What am I doing wrong? I just need the files that were changed 1 per line.
Thanks.
If your unformatted output have same pattern:
sending incremental file list file1.php sent ...
sending incremental file list file2.php sent ...
sending incremental file list file3.php sent ...
you can use preg_match_all() to capture the file names into array:
if (preg_match_all('/file list (.*?) sent /', $result, $matches)) {
$filesCopied = $matches[1];
} else {
echo 'Pattern does not match';
}
Found the answer!
As it turns out although the shell output was echoing as one line it was masking line breaks. So when it came to formatting the output the regex wasn't matching.
What I did was send the shell output to a file where I could see that it was line breaking.
So I took the shell output variable $filesCopied and ran it through preg_replace() using \R as the pattern. I found that here: Replace multiple newlines, tabs, and spaces
Thank you #Anggara as your code was better than mine for formatting and is what I am using.
Here is my final code:
$command = "sudo -S rsync -av ".$exclude." ".$source." ".$dest." --delete 2>&1";
// --- Issue command and check for errors.
$exErrors = shell_exec($command);
if (stripos($exErrors, "error:") !== false || stripos($exErrors, "[sudo]")) {
$error = "Uh-OH, we have a problem! Don't Panic!";
$errors = $exErrors;
include("head.php");
include("template_".$currentPage.".html");
include("foot.php");
exit();
}else{
// -- Strip invisible line breaks
$filesCopiedRaw = preg_replace('#\R+#', ' ', $exErrors);
// -- Strip all but files and folders from string and build an array
preg_match_all('/file list (.*?) sent /', $filesCopiedRaw, $matches);
$result = $matches[1];
// -- Convert array to single string
$filesCopied = "";
foreach($result as $file) {
$filesCopied .= $file." ";
}
// -- Replace spaces in string with line breaks
$filesCopied = preg_replace("/\s+/", "\n", $filesCopied);
}

How to highlight strings in a file to download?

I have a text file "output.txt" which is an output of a shell command. I want to highlight certain words taken as $_GET['word'] in that file and then allow to download using href.
I have seen multiple questions but none of them seems to be working in this case.
Highlight multiple keywords from a given string
highlight the word in the string, if it contains the keyword
Code:
$cmd = shell_exec("/usr/local/bin/clustalw2 -infile=input.txt -tree -type=protein -case=upper &");
$file = 'output.txt';
$content = explode("\n",file_get_contents("output.txt"));
$keyword = $_GET['word'];
$content = str_replace($keyword,'<span style="color:red">'.$keyword.'</span>',$content);
$file = file_put_contents($file, $content);
echo "<a href='http://some.thing.com/folder/output.txt'>Download Result file</a>";
It is not giving any error neither highlighting the text.
I suspect the trouble is with opening the initial file. The following did work for me.
I created /home/input.txt:
this is a test
that may
or may not work.
Then ran:
$cmd = shell_exec(" cp /home/input.txt output.txt");
$file = 'output.txt';
$content = explode("\n",file_get_contents("output.txt"));
$keyword = "may";
$content = str_replace($keyword,'<span style="color:red">'.$keyword.'</span>',$content);
$file = file_put_contents($file, implode("\n", $content));
echo "<a href='http://some.thing.com/folder/output.txt'>Download Result file</a>";
And the output.txt is now:
this is a test
that <span style="color:red">may</span>
or <span style="color:red">may</span> not work.

Executing Python Script with PHP Variables

I am writing a simple application that uses information from a form, passes it through $_POST to a PHP script that executes a python script and outputs the results. The problem I am having is that my python script is not actually running with the arguments being passed in.
process3.php file:
<?php
$start_word = $_POST['start'];
$end_word = $_POST['end'];
echo "Start word: ". $start_word . "<br />";
echo "End word: ". $end_word . "<br />";
echo "Results from wordgame.py...";
echo "</br>";
$output = passthru('python wordgame2.py $start_word $end_word');
echo $output;
?>
Output:
Start word: dog
End word: cat
Results from wordgame.py...
Number of arguments: 1 arguments. Argument List: ['wordgame2.py']
At the top of my wordgame2.py, I have the following (for debugging purposes):
#!/usr/bin/env python
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
Why isn't the number of arguments being passed = 3?
(Yes, my form does send the data correctly.)
Any help is greatly appreciated!
Edit: I might add that it does run when I explicitly tell it the start and end word... something like this:
$output = passthru('python wordgame2.py cat dog');
echo $output
Update -
Now that I am aware of PHP, the mistake lies in using the single-quotes '. In PHP, single quoted strings are considered literals, PHP does not evaluate the content inside it. However, double quoted " strings are evaluated and would work as you are expecting them to. This is beautifully summarized in this SO answer. In our case,
$output = passthru("python wordgame2.py $start_word $end_word");
would work, but the following won't -
$output = passthru('python wordgame2.py $start_word $end_word');
Original answer -
I think the mistake lies in
$output = passthru("python wordgame2.py $start_word $end_word");
Try this
$output = passthru("python wordgame2.py ".$start_word." ".$end_word);
Thank you for your contributions. I have figured out my problem with this simple fix:
$command = 'python wordgame2.py ' . $start_word . ' ' . $end_word;
$output = passthru($command);
In order for passthru to properly handle the php variables, it needs to be concatenated into the string before executing.
well if I understood you want pass a big amount of text like content of something, so the right way is;
$output = passthru("python wordgame2.py ".json_encode($end_word)." ".json_encode($start_word));

PHP exec capture text

I am having a problem with capturing text when I make an exec call to a perl script that just prints a lot of text. What happens when I run the following code is I get a 1 word result: "Array". I need to be able to capture the results so that I can change them around just a little bit. Here is the code:
<?php
$lastline = exec("perl parseOutput.pl",$retVal);
echo $retVal;
?>
How do I work around this?
You have an array of the lines of text that was outputted.
Do something like this:
echo implode( "\n", $retVal);
Or
echo implode( "<br />\n", $retVal);
And you'll see all of the output generated by the perl script.
just use shell_exec()
$fullResult = shell_exec("perl parseOutput.pl");
echo $fullResult;

Find specific text in multiple TXT files in PHP

I want to find a specific text string in one or more text files in a directory, but I don't know how. I have Googled quite a long time now and I haven't found anything. Therefor I'm asking you guys how I can fix this?
Thanks in advance.
If it is a Unix host you're running on, you can make a system call to grep in the directory:
$search_pattern = "text to find";
$output = array();
$result = exec("/path/to/grep -l " . escapeshellarg($search_pattern) . " /path/to/directory/*", $output);
print_r($output);
// Prints a list of filenames containing the pattern
You can get what you need without the use of grep. Grep is a handy tool for when you are on the commandline but you can do what you need with just a bit of PHP code.
This little snippet for example, gives you results similar to grep:
$path_to_check = '';
$needle = 'match';
foreach(glob($path_to_check . '*.txt') as $filename)
{
foreach(file($filename) as $fli=>$fl)
{
if(strpos($fl, $needle)!==false)
{
echo $filename . ' on line ' . ($fli+1) . ': ' . $fl;
}
}
}
If you're on a linux box, you can grep instead of using PHP. For php specifically, you can iterate over the files in a directory, open each as a string, find the string, and save the file if the string exists.
Just specify a file name, get the contents of the file, and do regex matching against the file contents. See this and this for further details regarding my code sample below:
$fileName = '/path/to/file.txt';
$fileContents = file_get_contents($fileName);
$searchStr = 'I want to find this exact string in the file contents';
if ($fileContents) { // file was retrieved successfully
// do the regex matching
$matchCount = preg_match_all($searchStr, $fileContents, $matches);
if ($matchCount) { // there were matches
// $match[0] will contain the entire string that was matched
// $matches[1..n] will contain the match substrings
}
} else { // file retrieval had problems
}
Note: This will work irrespective of whether or not you're on a linux box.

Categories