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

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 "").

Related

How can I use the minor sign < in a .bat file to take it as text [duplicate]

Special characters in batch files are a pain, but I haven't found the right workaround for properly escaping the first two characters of this particular string I'm trying to pass the application.
SET pass=^&AntiBatchfileString
A_Program.exe /pass=%pass%
Things I have tried:
:: Escaping the escape twice, first for ^, second for &.
SET pass=^^^^&AntiBatchfileString
echo %pass%
:: Combining escapes.
SET first=^^
SET second=^^&AntiBatchfileString
SET pass=%first%%second%
echo %pass%
:: Preventing expansion
SET first=^^
SET second=^^&AntiBatchfileString
SET pass=!first!%second%
echo %pass%
:: I got this to print correctly
SET "pass=^&AntiBatchfileString"
echo ^^%pass%
Still when passing the last one it doesn't accept the login, I don't know what the final output is. That got me thinking maybe it was trying to do another expansion when passing the parameter to the application, so I quoted that as well.
SET "pass=^&AntiBatchfileString"
A_Program.exe "/pass=^^%pass%"
It's still not working, I'm not sure what I'm missing at this point.
Supposing you want the string ^&AntiBatchfileString literally, this is the best set syntax, as most special characters (^ & ( ) < > | and also the standard delimiters , ; = SPACE TAB) lose their particular meaning as soon as ther are placed in between "", and the "" themselves do not become part of the variable value:
set "pass=^&AntiBatchfileString"
This works only as long as the command extensions are on, which is the Windows default anyway (type cmd /? and see the /E option).
When expanding (reading) a variable like "%pass%" (with enclosing ""), special characters are still treated literally.
However, as soon as you expand it like %pass% (no ""), they get back their special meaning. So you have the following options:
Use set "pass=^^^&AntiBatchfileString", where ^^ escapes the literal ^ and ^& the literal & when reading like %pass%.
Enable delayed expansion (see set /? about how it works and setlocal /? or cmd /? about how to enable it), where the variable value is expanded (read) at a point of time where parsing of special characters has already been completed.
I prefer the latter approach, because no special escaping is necessary, and it can also deal with " appearing in the string value (even if unsymmetrically present).
By the way, " can also be escaped by ^", as long as this does not appear within unescaped "".
Nevertheless, % signs cannot be escaped like ^% in a batch file, because percent expansion happens before escaping, but you need to double them like %% to get one literal one each, independent whether or not the string is in between "".
Note that on the console, %% does not work.
Finally, literal ! are consumed by the delayed expansion feature when enabled, therefore you need to pay particular attention to those in case, by escaping them like ^!, or also by intelligently toggling delayed expansion (hence to enable it only when it is actually needed and to disable it otherwise, when a literal string is provided, like in a set command line, for instance, when expanding a standard variable like %pass% and when reading a for variable like %%I (batch file) or %I (console), for example). Of course this is also not the ultimate solution, because you need setlocal and endlocal to enable/disable delayed expansion, which are intended to localise environment changes, so any variable changes since the most recent setlocal command are lost as soon as endlocal is executed (there are some tricks for passing a variable value over the endlocal barrier though).
If you want to use % as a string without escaping in a batch file:
Like %20, you can use %%%20.
git clone "https:// abc.com /D%%%220an"

how to escape single quote from ODBC query [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Correct way to escape input data before passing to ODBC
the error I am getting from querying a ODBC query is this:
(pos: 72 '...M = 'Owen O'^Donavon' AND...') - syntax error
and when I try to escape it:
(pos: 73 '... = 'Owen O\'^Donavon' AND...') - syntax error
the ^ means that is where it is breaking
I have tried the following:
NAM = '".$var."'
And also this:
NAM = '".mysql_escape_string($var)."'
then I got desperate
NAM = \"".$var."\"
Where $var is any name that contains a ' in it.
if you need the whole query:
UPDATE TABLE SET COLUMN1 = 'ERR' WHERE COLUMN_NAM = '".mysql_escape_string($var)."' AND COLUMN7 = 0");
does anybody know how I can get the quote properly escaped?
To include a single quote within a MySQL string literal (which is delimited by single quotes), use two single quote characters. e.g.
'I don''t like it'
Effectively, When MySQL parses that, it will see the two single quote characters, and will interpret that as one single quote within a literal, rather than seeing the "end" of the string literal.
But (as you are finding out) when you have only one single quote in there, the MySQL parser has a hissy fit over it. Consider this example:
'I don't like it'
What the MySQL parser sees there is a string literal, five characters in length, containing 'I don'. Then MySQL sees that literal as being followed by some more tokens that need to be parsed: t like it. The parser does NOT see that as part of a string literal. That previous single quote marked the end of the string literal.
So now, the MySQL parser can't make heads or tails of what t like it is supposed to be. It sees the single quote following these tokens as the beginning of another string literal. (So, you could be very clever about what appears there, and manage to get something that MySQL does understand... and that would probably be even worse.)
(NOTE: this issue isn't specific to ODBC; this affects clients that make use of string literals in MySQL query text.)
One way to avoid this type of problem is to use bind variables in your query text, vs. string literals. (But with MySQL, what's happening anyway, is that escaping, what gets sent to the MySQL server (behind the scenes, so to speak) is a string literal.
Sometimes we DO need to include string literals in our query text, and we shouldn't be required to use bind variables as a workaround. So it's good to know how to "escape" a single quote within a string literal which is enclosed in single quotes.

php singlequote not working on sprintf properly

I use sprintf() on my program to output some tabs and newlines. I noticed a part of my program not working properly.
As I inspected the part that isn't working, I noticed that I used a single quote ' instead of a doublequote " and the program actually outputs a \t instead of a inivisible tab space.
I thought the two are similar and the reason for having two delimeters for php is for us to be able to insert single or doublequote in a string or echo them without inserting escape characters.
Would there be a difference in assigning variables aside from the one I discovered
$a = "qq";
$b = 'qq';
Would they be stored in the computer's memory in a different manner?
you can refer to the manual that specifies that single quotes in php consider most escape sequences as litterals, contrary ot double quotes:
http://php.net/manual/en/language.types.string.php
single quote is faster than double
double quote can parse php variable. i.e. $a=2; and if you use echo "a is: $a"; then it will print a is: 2 but single quote will print a is: $a
if you use single quotes for the format string (like you should do, since there
aren't any variable conversions to do as long as you don't need any special chars),
the given examples won't work because of the backslash before the $ (needs to be
escaped in double quoted strings - but not in single quoted!) http://php.net/manual/en/function.sprintf.php

PHP: literal \n rather than new line

I have a php var which, when echoed, writes a JS function into the source of a page. The function loops through a CSV and so it has the following line within it:
$str="var lines = data.split('\n');";
At the present time, when echoed, I get this 'correct' JS written into the source:
var lines = data.split('
');
Instead, I want to echo the literal string \n into the source of the page.
Can anyone point me in the right direction? Thanks.
Escape the slash.
"\\n"
So that it is treated as a slash instead of an escape character.
Try this:
$str="var lines = data.split('\\n');";
you can escape \ like this: \\.
But I would put the whole JS functionality into a .js file, include that from the generated HTML, and call the specific function when needed. And generate a minimalistic js code, like var config = {....} if I have to communicate some page related information.
You almost never need dynamically generated JS code. It's a lot harder to read and you're wasting CPU and network bandwidth...
Either the solutions in the earlier answers, or invert the quotes by using single quotes as the PHP string delimiter:
$str='var lines = data.split("\n");';
Or escape the inner quotes, if you want to keep single quotes for javascript as well when using single quotes as the PHP string delimiter.
$str='var lines = data.split(\'\n\');';
See the docs on quoted strings in PHP as well about how single quoted strings and double quoted strings behave differently.

Why are escaped characters read from database, using PHP, displaying as normal text on output during regular expression replace?

I am trying to store regular expression search and substitution strings in a database. At runtime, I read the database, placing the strings into arrays, and then use the PHP preg_replace() method to update large strings written by users with fixes that my client wants.
Here is a sample string pair I am using:
Search string: /([^\r\n+])(\[url)/i
Substitute string: $1\n\n$2
If I place the string in code like this:
preg_replace("/([^\r\n]+)(\[url)/i", "$1\r\n\r\n$2", ProcessString);
Everything works beautifully. This finds instances of a bbCode tag "[url" that does not have a carriage-return/linefeed combination directly in front of it and places that in front of the "[url" tag.
However, when I run the code as I stated using strings from the database (MySql), the "\r\n\r\n" print literals instead of actually creating carriage-return line feeds. The strings are displayed in a "textarea" tag in HTML.
I have looked at the difference between single and quoted strings and my problem would seem to be this, I am assuming? Thinking that the problem is that the strings coming from the database or inserted into the array I'm looping through are created as single-quoted strings, I tried this:
preg_replace($findKey, "{$replaceValue}", ProcessString);
Where $replaceValue = the string '$1\r\n\r\n$2' (again, I am assuming that reading from the database and/or placing the value into an array (mysql_fetch_assoc($result)) is placing the string value into a single-quoted string and therefore the escaped characters are printing as literals instead of the characters the escaped characters actually represent. However, this did not work.
Here is the code I'm using to insert into the database:
INSERT INTO ISG_TCS_Replacements (FindPhrase, ReplacePhrase, ReplacementGroupID, Description, IsRegEx, IsActive, ProcessGroup, ProcessSequence)
VALUES ("/([^\\r\\n]+)(\\[url)/i","$1\\r\\n\\r\\n$2", 0, "Add a new line after [url] tags that are not on a new line currently.", 1, 1, 0, 1);
The fields are varchar(100).
The issue is that \r\n escapes only work in double quoted strings.
print "\r\n";
Whereas your database usage is likely akin to:
$replaceValue = '\r\n';
print "{$replaceValue}"; // uses the literal character string
You are inserting your replacement string with single quotes into the DB. Otherwise you would get the the actual linebreaks back. Mysql does escape them while inserting, but you always get the original string data back.
Reading from a MySQL TEXT/CHAR column is no different than reading from files really. Check your database with mysqladmin, if you see the literal \r\n then there is your problem.
(A literal '\r\n' btw works in the regex, but not in the replacement string.)
Something else. ([^\r\n+]) is probably meant to be ([^\r\n]+). The quantifier must be outside of the character class.

Categories