removing items from url strings in PHP - php

I would appreciate some help here:
What I want to do:
remove &itemsperpage=10 from:
http://localhost/thi/search/filter.html?type=featured&page=2&itemsperpage=10
and create a link from it:
http://localhost/thi/search/filter.html?type=featured&page=2&itemsperpage=15
here's what I have come up with so far:
<a href="<?php echo url::site(url::current()) . http_build_query($_GET) // don't know what follows ?>"
the framework functions I'm using are:
url::current() = returns current url in controller/action format
url::site() = returns absolute url i.e http://localhost/site/controller/action
so I have to remove '&itemsperpage' from the resulting string in the http_build_query function
but I am having trouble with character encodings and such! please help!
so here's the problem with character encoding:
$needle = '&itemsperpage';
$querystring = http_build_query($_GET) . '<br/>';
// echo $querystring . '<br/>';
$pos = strpos($querystring, $needle);
$remove = substr($querystring, ((int)$pos));
echo substr(str_replace($remove, '', $querystring), 1); // returns ';'
I can't remove the string '&itemsperpage' from the result of http_build_query which is:
'type=featured&page=2&itemsperpage=10' and functions like strstr outputs nothing

I would just do this:
$array = $_GET;
$array['itemsperpage'] = 15;
Then just use your code, but with the new variable (and the ?):
<a href="<?php echo url::site(url::current()) . '?' . http_build_query($array)">

The HttpQueryString class has several methods for getting, setting, modifying query strings and 'translating' their charsets.

You can achieve the effect you're looking for by removing the itemsperpage element from the $_GET array before building the query string.
unset($_GET['itemsperpage']);
And then just use the code you already wrote:
<a href="<?php echo url::site(url::current()) . http_build_query($_GET); ?>">
EDIT: I misread your post. I thought you only wanted to remove the field / value pair from the GET request. All you have to do is overwrite the value with the value you want:
$_GET['itemsperpage'] = 15;
And then use the code you already wrote.

Related

How to use echo in url

i am trying to use echo inside url. i have store data from the form in database and now i am also fetching it on my page and its working well. Now i am trying to print that data i.e. number and date in url.
Is it possible and if possible please help me out
here is my data that i am fetching and it prints the output
echo $number;
echo $yyyymmdd;
and here is my url in which i want to insert ' echo $number; ' and ' echo $yyyymmdd; ' on the place of and .
$json= file_get_contents("http://api.com/api/a2/live/apikey/fc5a69f870fdb03/number/<number>/date/<yyyymmdd>/");
I have also tried something like this but it gives error of syntex error.
$json= file_get_contents("http://api.com/api/a2/live/apikey/fc5a69f870fdb03/number/"echo $number;"/date/"echo $yyyymmdd;"/");
Another way to add changing parameters to a URL (or string) is by using sprintf(). You define your URL and a type specifier like %d as a placeholder for numbers, and %s for strings. See the php doc for the full list of type specifiers.
$urlFormat = "http://api.com/api/a2/live/apikey/fc5a69f870fdb03/number/%d/date/%s/"
^ ^
Then call sprintf with the changing parameters in order of appearance.
$url = sprintf($urlFormat, $number, $yyyymmdd);
$json = file_get_contents($url);
This becomes more convenient especially if you are calling file get contents in a loop.
Create two variables and append those two inside double-quote or single quote, depending upon the quotes which you have opened and close it.
<?php
$number=123;
$yyyymmdd='2018-10-9';
$json= file_get_contents("http://api.com/api/a2/live/apikey/fc5a69f870fdb03/".$number."/<number>/date/<".$yyyymmdd.">/");
?>
$json= file_get_contents("http://api.com/api/a2/live/apikey/fc5a69f870fdb03/number/".$number."/date/".$yyyymmdd."/");
When you compose text, you do not need "echo" but just can write variable.
You can directly use variables in double quotes like this
file_get_contents("http://api.com/api/a2/live/apikey/fc5a69f870fdb03/number/$number/date/$yyyymmdd/");
Sample code below
$number = 344;
$yyyymmdd = "20180301";
$url1 = "http://api.com/api/a2/live/apikey/fc5a69f870fdb03/number/$number/date/$yyyymmdd/";
echo "url1 ".$url1."\n";
$url2 = "http://api.com/api/a2/live/apikey/fc5a69f870fdb03/number/".$number."/date/".$yyyymmdd."/";
echo "url2 ".$url2. "\n";

parse non encoded url

there is an external page, that passes a URL using a param value, in the querystring. to my page.
eg: page.php?URL=http://www.domain2.com?foo=bar
i tried saving the param using
$url = $_GET['url']
the problem is the reffering page does not send it encoded. and therefore it recognizes anything trailing the "&" as the beginning of a new param.
i need a way to parse the url in a way that anything trailing the second "?" is part or the passed url and not the acctual querystring.
Get the full querystring and then take out the 'URL=' part of it
$name = http_build_query($_GET);
$name = substr($name, strlen('URL='));
Antonio's answer is probably best. A less elegant way would also work:
$url = $_GET['url'];
$keys = array_keys($_GET);
$i=1;
foreach($_GET as $value) {
$url .= '&'.$keys[$i].'='.$value;
$i++;
}
echo $url;
Something like this might help:
// The full request
$request_full = $_SERVER["REQUEST_URI"];
// Position of the first "?" inside $request_full
$pos_question_mark = strpos($request_full, '?');
// Position of the query itself
$pos_query = $pos_question_mark + 1;
// Extract the malformed query from $request_full
$request_query = substr($request_full, $pos_query);
// Look for patterns that might corrupt the query
if (preg_match('/([^=]+[=])([^\&]+)([\&]+.+)?/', $request_query, $matches)) {
// If a match is found...
if (isset($_GET[$matches[1]])) {
// ... get rid of the original match...
unset($_GET[$matches[1]]);
// ... and replace it with a URL encoded version.
$_GET[$matches[1]] = urlencode($matches[2]);
}
}
As you have hinted in your question, the encoding of the URL you get is not as you want it: a & will mark a new argument for the current URL, not the one in the url parameter. If the URL were encoded correctly, the & would have been escaped as %26.
But, OK, given that you know for sure that everything following url= is not escaped and should be part of that parameter's value, you could do this:
$url = preg_replace("/^.*?([?&]url=(.*?))?$/i", "$2", $_SERVER["REQUEST_URI"]);
So if for example the current URL is:
http://www.myhost.com/page.php?a=1&URL=http://www.domain2.com?foo=bar&test=12
Then the returned value is:
http://www.domain2.com?foo=bar&test=12
See it running on eval.in.

GET method... Extract variables

Can someone help me how to extract the url parameters from the following url using GET method in php?
http://domainname.com/?formBuilderForm%5BFormBuilderID%5D=29&formBuilderForm%5Brandomizer%5D=508398db941a26.20741366&formBuilderForm%5Bvw_sre_ticker_name%5D=TPX&formBuilderForm%5Bvw_sre_entry_price%5D=100&formBuilderForm%5Bvw_sre_entry_date%5D=21%2F10%2F2012
I believe the variable name is formBuilderForm [FormBuilderID] and value is 29. I tried the following code but it didn't work.
<?php
$_vw_sre_ticker_name_in = $_GET["formBuilderForm [FormBuilderID ]"];
echo 'vw_sre_ticker_name'.$vw_sre_ticker_name_in;
?>
I believe, it something to do with ASCII and Non-ASCII stuff.
%5D stands for [ in url encodings
So you could probably try
<?php
$_vw_sre_ticker_name_in = $_GET["formBuilderForm[FormBuilderID]"];
echo 'vw_sre_ticker_name'.$vw_sre_ticker_name_in;
?>
You needed to remove the spaces.
However as pointed out by Seth, this is really really basic debugging a simple
print_r($_GET);
Would have provided you with the information you needed rather than asking on Stackoverflow.
You can use foreach on $_GET
foreach($_GET as $key=>$value) {
echo $key . ':' . $value;
}

How to bold a variable?

How can I have text within a php variable be bold??
function show_balance_header ($balance, $currency)
{
(string)$display_output = null;
$display_output = fees_main::display_amount(abs($balance), $currency, true);
return $display_output;
}
I want to bold $balance. Is there an easy way or do I need to edit display_amount?
I've tried doing this:
"<b>".$balance"</b>" but this did not get the correct variable,
thanks in advance!!
Needs to be "<b>" . $balance . "</b>". Concatenate <b> to $balance and concatenate again to </b>
Edit:
Assuming this does the printing/formatting: fees_main::display_amount(abs($balance)
You want fees_main::display_amount('<b>' . abs($balance) . '</b>', $currency, true).
abs($balance) gets the absolute value as a number, and the concatenation (explained above) automatically casts them to strings. The rest of the parameters are passed the same way (unmodified, unbolded).
(string)$display_output = null; is unnecessary
On your element html, example:
<p> text <?php echo "<b>{$balance}</b>"; ?> text</p>
answer is to edit the inner function display_amount using Raeki's suggestion, for future questions, i think you must edit the inner-most function as only editing function show_balance_header did not get the correct variable

identify and execute php code on a string

I would like to know if it's possible to execute the php code in a string. I mean if I have:
$string = If i say <?php echo 'lala';?> I wanna get "<?php echo 'dada'; ?>";
Does anybody knows how?
[EDIT] It looks like nobody understood. I wanna save a string like
$string = If i say <?php count(array('lala'));?>
in a database and then render it. I can do it using
function render_php($string){
ob_start();
eval('?>' . $string);
$string = ob_get_contents();
ob_end_clean();
return $string;
}
The problem is that I does not reconize php code into "" (quotes) like
I say "<?php echo 'dada'; ?>"
$string = ($test === TRUE) ? 'lala' : 'falala';
There are lots of ways to do what it looks like you're trying to do (if I'm reading what you wrote correctly). The above is a ternary. If the condition evaluates to true then $string will be set to 'lala' else set to 'falala'.
If you're literally asking what you wrote, then use the eval() function. It takes a passed string and executes it as if it were php code. Don't include the <?php ?> tags.
function dropAllTables() {
// drop all tables in db
}
$string = 'dropAllTables();';
eval($string); // will execute the dropAllTables() function
[edit]
You can use the following regular expression to find all the php code:
preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);
$php_code will be an array where $php_code[0] will return an array of all the matches with the code + <?php ?> tags. $php_code[2] will be an array with just the code to execute.
So,
$string = "array has <?php count(array('lala')); ?> 1 member <?php count(array('falala')); ?>";
preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);
echo $php_code[0][0][0]; // <?php count(array('lala')); ?>
echo $php_code[2][0][0]; // count(array('lala'));
This should be helpful for what you want to do.
Looks like you are trying to concatenate. Use the concatenation operator "."
$string = "if i say " . $lala . " I wanna get " . $dada;
or
$string = "if i say {$lala} I wanna get {$dada}.";
That is what I get since your string looks to be a php variable.
EDIT:
<?php ?> is used when you want to tell the PHP interpreter that the code in those brackets should be interpreted as PHP. When working within those PHP brackets you do not need to include them again. So as you would just do this:
// You create a string:
$myString = "This is my string.";
// You decide you want to add something to it.
$myString .= getMyNameFunction(); // not $myString .= <?php getMyNameFunction() ?>;
The string is created, then the results of getMyNameFunction() are appended to it. Now if you declared the $myString variable at the top of your page, and wanted to use it later you would do this:
<span id="myString"><?php echo $myString; ?></span>
This would tell the interpreter to add the contents of the $myString variable between the tags.
Use token_get_all() on the string, then look for a T_OPEN_TAG token, start copying from there, look for a T_CLOSE_TAG token and stop there. The string between the token next to T_OPEN_TAG and until the token right before T_CLOSE_TAG is your PHP code.
This is fast and cannot fail, since it uses PHP's tokenizer to parse the string. You will always find the bits of PHP code inside the string, even if the string contains comments or other strings which might contain ?> or any other related substrings that will confuse regular expressions or a hand-written, slow, pure PHP parser.
I would consider not storing your PHP code blocks in a database and evaluating them using eval. There is usually a better solution. Read about Design Pattern, OOP, Polymorphism.
You could use the eval() function.

Categories