PHP: passing php variables as arguments? - php

In my php code I need to invoke a script and passing it some arguments. How can I pass php variables (as arguments) ?
$string1="some value";
$string2="some other value";
header('Location: '...script.php?arg1=$string1&arg2=$string2');
thanks

header('Location: ...script.php?arg1=' . $string1 . '&arg2=' . $string2);

Either via string concatenation:
header('Location: script.php?arg1=' . urlencode($string1) . '&arg2=' . urlencode($string2));
Or string interpolation
$string1=urlencode("some value");
$string2=urlencode("some other value");
header("Location: script.php?arg1={$string1}&arg2={$string2}");
Personally, I prefer the second style. It's far easier on the eyes and less chance of a misplaced quote and/or ., and with any decent syntax highlighting editor, the variables will be colored differently than the rest of the string.
The urlencode() portion is required if your values have any kind of url-metacharacters in them (spaces, ampersands, etc...)

You could use the function http_build_query
$query = http_build_query(array('arg1' => $string, 'arg2' => $string2));
header("Location: http://www.example.com/script.php?" . $query);

Like this:
header("Location: http://www.example.com/script.php?arg1=$string1&arg2=$string2");

It should work, but wrap a urlencode() incase there is anything funny breaking the url:
header('Location: '...script.php?'.urlencode("arg1=".$string1."&arg2=".$string2).');

Related

redirecting to a URL query string

I am trying to redirect a page to:
product_page.php?rest_id=$rest_id&area=$rest_city
for example:
product_page.php?rest_id=3&area=Enfield
At the moment the page is redirecting to:
http://localhost/PhpProject2/product_page.php?rest_id=&area=
Even though i have specified :
if (isset($_GET['rest_id'])){
$rest_id = mysqli_real_escape_string($dbc,$_GET['rest_id']);
}
if (isset($_GET['area'])){
$area = mysqli_real_escape_string($dbc,$_GET['area']);
}
if (isset($_GET['add_item'])) {
(int)$_GET['add_item']]){
$_SESSION['Shopping_cart_' . (int) $_GET['add_item']]+='1';
//redirect
echo"<script>window.open('product_page.php?rest_id=$rest_id&area=$rest_city','_self')</script>"; //header does not work
}
How would i go about getting the echo to re-direct to the correct page.
What i have tried:
Calling both add_item, rest_id and rest_city in the same if asset.
Moving the $_GET rest_id and rest_city closing tag after the echo.
The two above options just stop the page from re-directing all together, this is my first time doing this, any suggestions or tips would be greatly appreciated.
You should use double qotes ["string $variable string"] for variable to work inside a string or if not you should concatenate the string with [.] sign.
echo"<script>window.open('product_page.php?rest_id=$rest_id&area=$rest_city','_self')</script>";
This will not work because of single qoute [']
Regards
There are many syntax errors in your code. Also, the way you echo the string is wrong. You need to concat the variables with the string, using the PHP concatenation operator, else use double quotes.
Below fixed your errors:
if (isset($_GET['rest_id'])){
$rest_id = mysqli_real_escape_string($dbc,$_GET['rest_id']);
}
if (isset($_GET['area'])){
$area = mysqli_real_escape_string($dbc,$_GET['area']);
}
if (isset($_GET['add_item'])) {
$_SESSION['Shopping_cart_'] = (int) $_GET['add_item']+='1';
echo"<script>window.open('product_page.php?rest_id=" . $rest_id . "&area=" . $rest_city . "','_self')</script>";
}

PHP: Complicated String With Single and Double Quotes

I'm trying to pass GET variables inside the URL with a bit of html inside of my PHP but can't figure out the quotes situation. I need to embed two variables inside the URL. I have one in but don't know how to embed the other. Here is the string:
echo "<a href='?id=".($id-1)."' class='button'>PREVIOUS</a>";
and here is what I need to go inside
&City=$City
Thanks for the help
Its pretty simple,
echo "<a href='?id=".($id-1)."&city=" . $City . "' class='button'>PREVIOUS</a>";
In php double quotes "" can eval variables inside them.
$test = "123;"
echo "0$test456"; // prints 0123456
In your case you better use single quote ''.
echo '<a href=\'?id=' . ($id-1) . '&City=' . $City . '\' class=\'button\'>PREVIOUS</a>';
or better
echo 'PREVIOUS';
Use something like this:
echo "<a href='?id=".$id."&City=".$city."'>";
You do need (well, it's good practice anyway) to use & for your ampersand. Otherwise it's fairly straight forward;
echo "<a href='?id=".($id-1)."&City=$City' class='button'>PREVIOUS</a>";
This is because you are using double quotes, which means you can put variables directly into the string (there are some exceptions which you might need to put in curly brackets {}).
I suggest you get a text editor with syntax highlighting, such as jEdit (other editors are available).
Hope this helps.
Maybe is it better to use the sprintf function
$id = 100;
$previousId = $id - 1;
$City = 'Amsterdam';
$link = 'PREVIOUS';
echo sprintf($link, $id, $City);

PHP making an URL link work inserting the $variables the right syntax way

I have this link that works.
echo '<a href="?country=Estonia&from_language=Russian&into_language=Latvian&submitted=true&
page='.$x. '">'.$x.'</a> ';
But I need the nouns Estonia, Russian and Latvian replaced by scalar variables like $country, $from_language, $into_language.
I have tried all possible combinations of dots and single and double quotes. I always get syntax errors. I don't know how the embed the variables there.
Anybody knows?
thank you
Do yourself a massive favour and use http_build_queryDocs:
<a href="?<?php echo http_build_query(array(
'country' => $country,
'fromLanguage' => $fromLanguage,
'somethingElse' => $somethingElse,
'...' => '...'
), '', '&'); ?>">Link</a>
use something easy one like sprintf or printf.
eg:
printf('<a href="?country=%s&from_language=%s&into_language=%s&submitted=true&
page=%s">%s</a>', $country, $fromLanguage, $toLanguage, $pageID, $dispText);
You could also use something like encoding with double quote sign like:
echo "<a href=\"?country={$country}&from_language={$fromLanguage}&into_language={$toLanguage}&submitted=true&
page={$pageID}\">{$dispText}</a>"
Avoid to put variables directly into string when not extremely simple. Use concatenation instead, and escape string if you want to make something good:
echo '<a href="?country=' . htmlentities($country) .
'&from_language=' . htmlentities($from_language) .
'&into_language=' . htmlentities($into_language) .
'&submitted=true&page=' . intval($x) . '">' . htmlentities($x) . '</a> ';
Anyway, if you really want it the complex way, you have to consider that you need doble quotes for HTML attributes, but double quotes are needed to wrap the PHP string because you want to put variables in it. So, you must escape HTML double quotes. Try:
echo "' . $x . ' ';
Combining the answers of Corbin and KoolKabin gives you this easy-to-read snippet:
printf('%s',
htmlspecialchars(
http_build_query(array(
'country' => $country,
'from_language' => $from_language,
'into_language' => $into_language,
'submitted' => 'true',
'page' => $x
))
),
htmlspecialchars($x));
Parametrization
printf and sprintf are very useful for adding parameters to strings. They make it easy to add escaping or complex values without making the string itself unreadable. You can always see at a glance what string it is by the first parameter.
http_build_query is also a way of parametrizing, but for the querystring. The main use is that you don't need to focus on the syntax of querystrings at all.
Escaping
htmlspecialchars makes sure that the data is fit for insertion into HTML code. It's similar to escaping in SQL queries to avoid SQL injections, only here we want to avoid HTML injections (also called XSS or cross-site scripting).
http_build_query will automatically make sure that all values are escaped for insertion as an URL in the address field in a browser. This does not guarantee fitness for insertion into HTML code. htmlspecialchars is therefore needed for the querystring as well!
If you scripts output HTML, consider to configure the output setting for argument separators arg_separator.output:
ini_set('arg_separator.output', '&');
You can then simply create the URI query info path by using http_build_query:
$country = 'de';
$fromLanguage = 'en_EN';
?>
Link
Which will give you a perfectly validly encoded output, which is immune to injections:
Link
Full Demo
$country = 'Estonia';
$from_language = 'Russian';
$into_language = 'Latvian';
echo ''.$x.' ';
OR
echo "$x";
OR
echo "{$x}";

PHP preg_replace problem

This is a follow-up question to the one I posted here (thanks to mario)
Ok, so I have a preg_replace statement to replace a url string with sometext, insert a value from a query string (using $_GET["size"]) and insert a value from a associative array (using $fruitArray["$1"] back reference.)
Input url string would be:
http://mysite.com/script.php?fruit=apple
Output string should be:
http://mysite.com/small/sometext/green/
The PHP I have is as follows:
$result = preg_replace('|http://www.mysite.com/script.php\?fruit=([a-zA-Z0-9_-]*)|e', ' "http://www.mysite.com/" .$_GET["size"]. "/sometext/" .$fruitArray["$1"]. "/"', $result);
This codes outputs the following string:
http://mysite.com/small/sometext//
The code seems to skip the value in $fruitArray["$1"].
What am I missing?
Thanks!
Well, weird thing.
Your code work's perfectly fine for me (see below code that I used for testing locally).
I did however fix 2 things with your regex:
Don't use | as a delimiter, it has meaning in regex.
Your regular expression is only giving the illusion that it works as you're not escaping the .s. It would actually match http://www#mysite%com/script*php?fruit=apple too.
Test script:
$fruitArray = array('apple' => 'green');
$_GET = array('size' => 'small');
$result = 'http://www.mysite.com/script.php?fruit=apple';
$result = preg_replace('#http://www\.mysite\.com/script\.php\?fruit=([a-zA-Z0-9_-]*)#e', ' "http://www.mysite.com/" .$_GET["size"]. "/sometext/" .$fruitArray["$1"]. "/"', $result);
echo $result;
Output:
Rudis-Mac-Pro:~ rudi$ php tmp.php
http://www.mysite.com/small/sometext/green/
The only thing this leads me to think is that $fruitArray is not setup correctly for you.
By the way, I think this may be more appropriate, as it will give you more flexibility in the future, better syntax highlighting and make more sense than using the e modifier for the evil() function to be internally called by PHP ;-) It's also a lot cleaner to read, IMO.
$result = preg_replace_callback('#http://www\.mysite\.com/script\.php\?fruit=([a-zA-Z0-9_-]*)#', function($matches) {
global $fruitArray;
return 'http://www.mysite.com/' . $_GET['size'] . '/sometext/' . $fruitArray[$matches[1]] . '/';
}, $result);
i write it again, i don't understand good where is the error, the evaluation of preg results is very weird in php
preg_replace(
'|http\://([\w\.-]+?)/script\.php\?fruit=([\w_-]+)|e'
, '"http://www.$1/".$_GET["size"]."/sometext/".$fruitArray["$2"]."/";'
, $result
);
It looks like you have forgotten to escape the ?. It should be /script.php\?, with a \? to escape properly, as in the linked answer you provided.
$fruitArray["\$1"] instead of $fruitArray["$1"]

PHP keep me from eval ;) Variables inside string

For reasons I'd rather not get into right now, I have a string like so:
<div>$title</div>
that gets stored in a database using mysql_real_escape_string.
During normal script execution, that string gets parsed and stored in a variable $string and then gets sent to a function($string).
In this function, I am trying to:
function test($string){
$title = 'please print';
echo $string;
}
//I want the outcome to be <div>please print</div>
This seems like the silliest thing, but for the life of me, I cannot get it to "interpret" the variables.
I've also tried,
echo html_entity_decode($string);
echo bin2hex(html_entity_decode($string)); //Just to see what php was actually seeing I thought maybe the $ had a slash on it or something.
I decided to post on here when my mind kept drifting to using EVAL().
This is just pseudocode, of course. What is the best way to approach this?
Your example is a bit abstract. But it seems like you could do pretty much what the template engines do for these case:
function test($string){
$title = 'please print';
$vars = get_defined_vars();
$string = preg_replace('/[$](\w{3,20})/e', '$vars["$1"]', $string);
echo $string;
}
Now actually, /e is pretty much the same as using eval. But at least this only replaces actual variable names. Could be made a bit more sophisticated still.
I don't think there is a way to get that to work. You are trying something like this:
$var = "cute text";
echo 'this is $var';
The single quotes are preventing the interpreter from looking for variables in the string. And it is the same, when you echo a string variable.
The solution will be a simple str_replace.
echo str_replace('$title', $title, $string);
But in this case I really suggest Template variables that are unique in your text.
You just don't do that, a variable is a living thing, it's against its nature to store it like that, flat and dead in a string in the database.
If you want to replace some parts of a string with the content of a variable, use sprintf().
Example
$stringFromTheDb = '<div>%s is not %s</div>';
Then use it with:
$finalString = sprintf($stringFromTheDb, 'this', 'that');
echo $finalString;
will result in:
<div>this is not that</div>
If you know that the variable inside the div is $title, you can str_replace it.
function test($string){
$title = 'please print';
echo str_replace('$title', $title, $string);
}
If you don't know the variables in the string, you can use a regex to get them (I used the regex from the PHP manual).
function test($string){
$title = 'please print';
$vars = '/(?<=\$)[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/';
preg_match_all($vars, $string, $replace);
foreach($replace[0] as $r){
$string = str_replace('$'.$r, $$r, $string);
}
echo $string;
}

Categories