Porter Goh
Porter Goh

Reputation: 9

php argument return a string with newline

i have a php script that takes in 1 argument for e.g. and i need to capture that argument and do a urlencode

Here is a sample code to show the issue

<?php

$input=$argv[1];
#$input="How are you.\nAre you free?";
echo "$input\n";
$escape_input = urlencode("$input");
echo "$escape_input";

?>

$ php test.php "How are you.\nAre you free?"

The output would be How+are+you.%5CnAre+you+free%3F% which is incorrect as the new line is not encoded properly.

But if you hardcode the same string in the code, it would work Correct output: How+are+you.%0AAre+you+free%3F%

Upvotes: 0

Views: 1640

Answers (1)

sauerburger
sauerburger

Reputation: 5138

The problem is with the input of your code. As you have pointed out

echo urlencode("Hello\nWorld.");

prints Hello%0AWorld., because \n is interpreted as the new line character if it is used inside the quotes in php, and thus \n is replaced with the new line character before it is passed to urlencode.

When you execute the code with php test.php "How are you.\nAre you free?" (lets say in bash), $argv[1] is a string with contains the backslash character followed by n. urlencode encodes the backslash and leaves n as is.

In order to run the code with a new line character, you should hit enter where the line break should be.

$ php test.php "How are you.
Are you free?"

Alternatively you can also manually interpret the sequence \n in the input and replace it with the new line character.

$input = str_replace("\\n", "\n", $argv[1]);

Please note that the first argument, the search pattern, is the string \n (backslash followed by n), and the second argument, the replace string, is the new line character.

Upvotes: 2

Related Questions