How insert an XML in a command line [duplicate] - php

I got one error while passing the arguments to outlook_DataParsing.sh:
$ sh outlook_DataParsing.sh delete node doc('/opt/ws40/contacts.xml')//Directory/Contacts/Contact[#id='22222']
and I am reading all the arguments as:
str=$#
The error is following:
-bash: syntax error near unexpected token `('
Can anybody help me?

There are a number of "special" characters in a shell command, including $()[]
Most of these can simply be passed by enclosing the parameter in double quotes
foo "(hello)[]"
This however will not fix the $ sign, as it is intended for variables. You can instead use single quotes to pass a $ sign
foo '$im_not_a_variable'
If all else fails, ANY character can be escaped with a backslash \ including a space (no quotes needed)
foo \(hello\)\[\]\ \$im_not_a_variable

Related

Losing part of a url while passing it from powershell to batch

I've got some powershell that connects to my server and returns an address to be passed to a batch file.
This batch file is a requirement, as it's an HTA/Batch Hybrid that allows me to run a created UI for the project. The URL is being passed as an iframe source to load some results from the server.
I have a variable $content in powershell, which equals http://example.com/selectMultiple.php?choice=[{"id":51,"p":100},{"id":52,"p":94}] (Slightly modified to protect my server address)
I then launch the batch file, while passing that $content variable to it like this
"Launching $content"
Start-Process "files\hybrid.bat" "$content"
In the batch file I have some code that echo's the value that was passed to it.
set "link=%~1"
echo %link%
But after being passed, some of the variable is trimmed. This echos http://example.com/selectMultiple.php?choice - which leads me to believe that there is something with the = sign that is breaking the string.
I've tried urldecode methods in powershell and from my server (php) and neither fixed the issue.
I am at a loss here and would much appreciate any help resolving this issue./
(I tagged PHP as well, to show that I do have the ability to work with the code that is returning the URL)
Start-Process "files\hybrid.bat" """$content"""
Note that $content variable contains characters (e.g. = and ,) which are treated as parameter delimiters in batch scripting:
Delimiters separate one parameter from the next - they split the
command line up into words.
Parameters are most often separated by spaces, but any of the
following are also valid delimiters:
Comma (,)
Semicolon (;)
Equals (=)
Space ( )
Tab ( )
The called batch (see set "link=%~1" command) strips the first supplied parameter from enclosing double quotes in the right way. Hence, you need to pass the string from $content variable enclosed in double quotes from powershell. Use doubled inner double quotes as follows:
# ↓ ↓ string delimiters are not supplied
Start-Process "files\hybrid.bat" """$content"""
# ↑↑ ↑↑ escaped inner double quotes are supplied
Double-Quoted Strings (")
When you enclose a string in double quotation marks, any variable
names in the string such as "$myVar" will be replaced with the
variable's value when the command is processed. … Any embedded
double quotes can be escaped using the grave-accent as `" or
doubled (replace " with "").

awk command to find average of a column from a file

I have written an awk command to read from a log file and get the average of a specific column.
The command is :
awk '{sum += $NF} END {print sum/NR}' /serach_grater500ms_test.txt
Everything is working fine on terminal but when I try to execute this command in php script as follow :
$no_of_request=exec("awk '{sum += $NF} END {print sum/NR}' /serach_grater500ms_test.txt");
print_r($no_of_request);
It throw me a syntax error
PHP Notice: Undefined variable: NF in /home/javed/Downloads/read_log.php on line 11
awk: line 1: syntax error at or near }
How can I solve it ?
If you want to pass a string into a shell script, you need to quote it properly for the shell. The easiest way to do this is to make it a single-quoted literal; this requires transforming the single quotes inside the string.
exec('awk \'{sum += $NF} END {print sum/NR}\' /serach_grater500ms_test.txt');
In your example the php string is between double-quote ". The character ' inside has no special meaning, you dont need to escape it. On the other hand the $ (like in sum += $NF) is interpreted, so the php replaces $NF with its value (empty!).
With Inian's answer the php string is between single-quote '. So the php does not look for variable inside ($NF is protected); but you have to escape further \' inside.
You can also have it work with the double-quote of your example; but you escape only the \$ of $NF :
$no_of_request=exec("awk '{sum += \$NF} END {print sum/NR}' filee");

How can execute php scripts in bash?

I need parse uri in shell scripts. So, I tried to use php in bash as below.
#!/bin/sh
uri="http://www.google.com?key=value
key="host"
value=$(php -r "$parse = parse_url('$uri'); echo $parse['$key']")
It has showing the following error.
PHP Parse error: syntax error, unexpected '=' in Command line code on line 1
Some body can help how to use embedded php in bash ?
A cheap way of debugging this is to use echo to see what you're passing in to php:
echo "$parse = parse_url('$uri'); echo $parse['$key']"
shows
= parse_url('http://www.google.com?key=value'); echo ['host']
You're already using $uri to mean "the value of the shell variable uri", so it's not surprising that $parse is also considered a shell variable and expanded to its value (unset, nothing).
Use \$ when you want a literal dollar sign in your double quoted string:
value=$(php -r "\$parse = parse_url('$uri'); echo \$parse['$key']")
You can use it easily, but you must be careful because of escaping in bash.
I recommend to use single quotes (you do not need to escape anything) and exit from the quotes when you want to do something special. Your example:
php -r '$parse=parse_url("'$url'"); echo $parse["'$part'"];'
Note that
you do not need to escapes $parse
you need to exit from single quotes when inserting bash variable: '$url'
you cannot use single quotes in the single quotes! do use double quotes " instead.
Update:
Just for the clarification - parse error happened because $parse was interpreted as bash variable (empty string) so the php command incorrectly started with =.

making close button with java script in php

For closing a <div>, I use onclick="this.parentNode.style.display='none';" (in HTML) and it works. But in PHP it doesn't work!
error:
Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in /home/u381013597/> public_html/index.html on line 311
When I change 'none' to "none" there is no error but the close item doesn't work.
What is the problem?
When you print in PHP you have to watch out with strings. You define a string with single or double quotes. If your string contains for example single quotes and you defined the string with a single quote the quote in the string itself will mean end of string, so you have to escape them:
echo 'onclick="this.parentNode.style.display=\'none\';"';
As you see I used single quotes for printing here, and I escaped every single quote in the string itself with the backslash character: \
Otherwise, the string would ended before none (because there is a unescaped single quote that means the end of the string) and the parser would except a ; character that means end of command or a , character that marks that there will be other parameters, but you give none of them, it gets none instead. Thats why it throws that he get an unexpected T_STRING. If you look at your error message, you will see that it says the same as I did, just in a compact way:
error: Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in /home/u381013597/> public_html/index.html on line 311
It also says that there is a Parse error: syntax error that means you mistyped something, and he also says where does the problem occurs.
Error messages are your friends, they give a hint about the problem. Read (or at least search for) them and you will be able to develop much faster.

PHP exec() with double quote argument

I've been having trouble running a command using PHP's exec() function on Windows. Per a comment on PHP's site on exec():
In Windows, exec() issues an internal call to "cmd /c your_command".
My command looks like:
"path\to\program.exe" -flag1 attribute1 -flag2 attribute2 -flag3 "attribute3 attribute4"
Under regular execution of this command in my local command prompt, without the /c flag, the command runs fine. However, with the introduction of the /c flag, command prompt tells me that "The system cannot find the path specified."
I think the command prompt is interpreting the double-quoted argument as a path to another file, but that's the furthest I've gotten with this problem.
Does anybody have any ideas on how to get past this? Thanks!
I also encountered this issue, and the cause of it is, indeed, the internal use of "cmd /c" as described in your own answer.
I have done some investigation, and have found that this was resolved in PHP 5.3, which is why some commenters were unable to reproduce it.
It was fixed in the following commit:
https://github.com/php/php-src/commit/19322fc782af429938da8d3b421c0807cf1b848a#diff-15f2d3ef68f383a87cce668765721041R221
For anyone who still needs to support PHP 5.2, it is fairly easy to replicate the fix in your own code. Instead of:
$cmd = "...any shell command, maybe with multiple quotes...";
exec($cmd);
use
function safe_exec($cmd, &$output = null, &$result_code = null) {
if (strtoupper(substr(php_uname('s'), 0, 3)) == "WIN"
&& version_compare(PHP_VERSION, "5.3", "<"))
{
$cmd = '"' . $cmd . '"';
}
return exec($cmd, $output, $result_code);
}
$cmd = "...any shell command, maybe with multiple quotes...";
safe_exec($cmd);
This replicates the behaviour of PHP 5.3 and above, in the same way as in the above-linked commit.
Note that this applies to all shell commands, not just exec() as used in my example.
I've figured out the answer by myself...
After perusing cmd.exe's /? and trying to decipher that, I've noticed one important section:
If all of the following conditions are met, then quote characters on the command line are preserved:
No /S switch (Strip quotes)
Exactly two quote characters
No special characters between the two quote characters, where special is one of: & < >( ) # ^ |
There are one or more whitespace characters between the the two quote characters
The string between the two quote characters is the name of an executable file.
Otherwise, old behavior is to see if the first character is a quote character and if so, strip the leading character and remove the last quote character on the command line, preserving any text after the last quote character. To negate this behaviour use a double set of quotes "" at the start and end of the command line.
It seems as though if there more than one pair of quotes at any time, quotation marks will be stripped from the second pair of quotes and on.
A relevant question: How do I deal with quote characters when using cmd.exe but not completely relevant, since PHP will not allow you to modify its exec() command by putting an /S flag on its call (which would definitely be a lot easier).
I've managed to work around this problem by directly changing directories with chdir() to the folder where the .exe is located, then chdir()'ing back to my original working directory. It's an extremely hacky solution, given the case that I'm lucky that I only have one set of arguments using double quotes. If anybody were to have multiple arguments using double quotes, I wouldn't know how to solve that...
Just a guess (I am not familiar with PHP on windows): maybe escape the quotes as " becoming ""?
"path\to\program.exe" -flag1 attribute1 -flag2 attribute2 -flag3 ""attribute3 attribute4""
Whatever the solution is, make sure that when there's some form of user-input that gets passed to this command as arguments that you use escapeshellarg and/or escapeshellcmd.
I hope it will help
escapeshellarg() — Escape a string to be used as a shell argument
escapeshellcmd() — Escape shell metacharacters

Categories