display + sign from the query string url using php - php

Im trying to send a query string in url
for ex : url : localhost/myfile.php?number=8777,+9822,+9883
in myfile.php when i give echo the query string :
echo $_REQUEST['number'];
output :
8777,9822,9883
but the expected output is :
8777,+9822,+9883
How can i display + sign also.
UPDATE :
actually that url is web request from the android/ios device app,
im providing webservice in php,
so android/ios developers are sending request with a querystring contains + sign
so how can i handle this situation?

+ is reserved. PHP is correct in translating an unencoded + sign to a space.
You can use urlencode() urldecode() for this.
The + must be submitted in PHP as the encoded value: %2B

You should then use urlencode() function to create that url:
<?php
var_dump($_GET['number']);
echo 'http://localhost/myfile.php?number='.urlencode('8777,+9822,+9883');
EDIT
If this is url that you receiving and cannot do anything with that you can use for example:
echo substr($_SERVER['REQUEST_URI'],strpos($_SERVER['REQUEST_URI'],'=')+1);
and you will get
8777,+9822,+9883

Sorry, i dont know what you're trying to do, but here's a suggestion
// where base64_encode('8777,+9822,+9883') = ODc3NywrOTgyMiwrOTg4Mw
localhost/myfile.php?number=ODc3NywrOTgyMiwrOTg4Mw
// on myfile.php
echo base64_decode($_REQUEST['number']);
// this will output -> 8777,+9822,+9883
UPDATE ---------------------------
if you have no other choice , you can use this
<?php
// get URL query string
$params = $_SERVER['QUERY_STRING'];
// if you have $params = www.mydomain.com/myfile.php?number=9988,+9876,+8768
$temp = explode('=', $params);
echo $temp[1] .'<hr>';
// if you have $params = www.mydomain.com/myfile.php?number=9988,+9876,+8768&number2=123,+456,+789
$params2 = $_SERVER['QUERY_STRING'];
$temp3 = explode('&', $params2);
foreach($temp3 as $val){
$temp4 = explode('=', $val);
// # // $GET = $temp4[0]; // if you need the GET VALUES
$VALUE = $temp4[1];
echo $VALUE .'<br>';
}
?>
Hope this helps.... :)

Related

Form post has "%10" written by user - json_decode() fails with urldecode()

Was so awesome of the customer to type "%10" instead of "10%"
0_o
$PACKAGE_json_decode = json_decode(urldecode(($_POST['textarea']), true);
print_r($PACKAGE_json_decode); // LENGTH 0
foreach($PACKAGE_json_decode as $row){
}
ERROR:
"Message: Invalid argument supplied for foreach()"
How do I urldecode without causing the %10 to take on a different meaning when sent back via AJAX?
And decode seems to produce that square character I cannot paste here... you know ... looks sorta like "[]"
*The string needs to be the same for the client when they get it back - they save it with a % they want it back with a %.
- Any suggestions about replacing it?
The % character is used in URL encoding. Either you remove % from the front end before passing to the server or you deal the same in the server side.
You could encode your request send by Ajax directly, such as below:
$.ajax({
type:'POST',
dataType: 'json',
...
Or like this:
JSON.stringify('%10');
Inside your PHP, just json_decode() now, as below.
$PACKAGE_json_decode = json_decode($_POST['textarea']);
Like this, your %10 will become "%10", et voila!!!
Please use the following code and let me know where is it breacking ?
<?php
$url_encode = urldecode("sampleTextWith%");
echo '<b>Ecoded URL </b>'. $url_encode."<br>";
$obj = new StdClass();
$obj->text = $url_encode;
$encoded_json = json_encode($obj);
echo '<b>Encoded JSON </b>'. $encoded_json."<br>";
$decoded_json = json_decode($encoded_json);
echo "<b>Decoded JSON </b>";
print_r($decoded_json);
echo "<br>";
foreach($decoded_json as $row){
echo "<b>Row Value : </b>". $row."<br>";
}
?>

changing get variable using parse_url not working in php

I've looked at every post on SO that remotely pertains to this and I just can't figure this out. This code is taken directly from another SO post and was marked as the correct working answer:
$query = $_GET;
// replace parameter(s)
$query['d'] = 'new_value';
// rebuild url
$query_result = http_build_query($query);
// new link
Link
Again, taken straight from another post. When I try this code, i change the $_GET to the actual URL that i want to alter. When the code gets to the $query['d'] part, it tells me I get an illegal string offset and the error is the index that's specified. So then I parse the URL, and then do parse_str($query, $output) which in turn allows me to do $output['d'] and THEN I can set a new value to that variable. If I echo it out, it's fine.
But then I get to the http_build_query line, and it tells me that it's expecting an array or object and I can't build the new URL. Here is my code:
$link = parse_url('https://www.google.com/search?source=hp&ei=85GhW6CNHoSqsgXnzoD4Ag&q=coding+tutorial&btnK=Google+Search&oq=coding+tutorial', PHP_URL_QUERY);
parse_str($link, $output);
$output['oq'] = 'new value';
$query_result = http_build_query($link);
echo $query_result;
This code yields that the http_build_query function wants an array or object...i guess i'm not giving it that in some way? What do I need to do to get this to work?
If you want to rebuild the full URL after modifying the query parameters, you could do this:
$url = 'https://www.google.com/search?source=hp&ei=85GhW6CNHoSqsgXnzoD4Ag&q=coding+tutorial&btnK=Google+Search&oq=coding+tutorial';
$link = parse_url($url, PHP_URL_QUERY);
parse_str($link, $output);
$output['oq'] = 'new value';
echo substr($url, 0, strpos($url, '?') + 1) . http_build_query($output);
Output:
https://www.google.com/search?source=hp&ei=85GhW6CNHoSqsgXnzoD4Ag&q=coding+tutorial&btnK=Google+Search&oq=new+value

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 attribute with file_get_contents PHP

I have a sql query that I store in a variable and I displayed. I get the contents of this with file_get_contents from another file, I would like to recover some of this code (which is html) in order to make link. More precisely retrieve the id.
My api.php
$base = mysql_connect ('localhost','root','');
mysql_select_db('administrations', $base);
if(isset($_GET['cp']))
{
$sql = 'SELECT NOM_organisme, ID_organisme
FROM organismes
WHERE code_postal LIKE "%'.$_GET['cp'].'%"
ORDER BY NOM_organisme;';
$req = mysql_query($sql) or die('SQL Error !<br>'.$sql.'<br />'.mysql_error());
}
while ($data = mysql_fetch_array($req))
{
echo '<p id="'.$data['ID_organisme'].'"'.
$data['NOM_organisme'].'</br>'.
$data['ID_organisme'].'</p></br>';
}
I want to get the id="I WANT THIS".
And my index.php (part of my code that retrieves the contents).
if(isset($_POST['cp']))
{
$api = "http://mywebsite.fr/api.php?cp=".$_POST['cp'];
$var = file_get_contents($api);
echo $var;
}
How can I get the id="" in my index.php ?
please look at php get documentation. you need to link to your script with url parameters and access them in your php code.
http://php.net/manual/en/reserved.variables.get.php
echo ''.$data['NOM_organisme'].'</br>'.$data['ID_organisme'].'</br>';
php
if(isset($_GET['id']))
{
$api = "http://mywebsite.fr/api.php?cp=".$_GET['id'];
$var = file_get_contents($api);
echo $var;
}
if you dont want to use url parameter you can use post values
http://php.net/manual/en/reserved.variables.post.php
I understand what your trying to do, but dont find it logical without knowing the purpose of this tiny code :)
Do you have a link or some sort?
Basicly what i should do is:
$base = mysql_connect ('localhost','root','');
mysql_select_db('administrations', $base);
if(isset($_POST['cp']))
{
$sql = 'SELECT NOM_organisme, ID_organisme FROM organismes WHERE code_postal LIKE "%'.$_GET['cp'].'%" ORDER BY NOM_organisme;';
$req = mysql_query($sql) or die('SQL Error !<br>'.$sql.'<br />'.mysql_error());
while ($data = mysql_fetch_array($req))
{
echo '<p id="'.$data['ID_organisme'].'"'.$data['NOM_organisme'].'</br>'.$data['ID_organisme'].'</p></br>';
}
} else {
echo 'show something else';
}
If I get you correctly, you are
Sending a GET request in index.php using file_get_contents() to your website.
The website (api.php) performs an SQL query and prints the result in HTML.
index.php takes this HTML output and stores it in the variable $var.
You want to retrieve all values contained inside the id attribute of the paragraph.
In this case, you probably want to use regular expressions. preg_match_all seems to be appropriate. It should work for you like this:
$out = array();
preg_match_all("/id=\"([^\"]*?)\"/U", $var, $out);
foreach ($out as $value) {
echo 'I found some id ' . htmlspecialchars($out[$value][2]) . '<br />';
}
And additionally:
A decent HTML parser would be much more appropriate in this case (eg. it would not match id="X" in flow text).
Your PHP code is vulnerable to SQL injections.
You should sanitize plain text to HTML appropriately.
First of all, you should try to display your API reply as a JSON-string, this is much more convenient.
If you still want to use your api.php, you first need to close your opening paragraph! You did forget a '>'!
echo '<p id="'.$data['ID_organisme'].'">'.
$data['NOM_organisme'].'</br>'.
$data['ID_organisme'].'</p></br>';
Then you need to parse your paragraph.
You can do it like that:
if(isset($_POST['cp']))
{
$api = "http://mywebsite.fr/api.php?cp=".$_POST['cp'];
$var = file_get_contents($api);
preg_match("#<p id='(.*)'#", $var, $matches);
id = $matches[1];
echo $id;
}

php script encoding special characters causes error

I'm attempting to run the script referenced here
<?php
$url = 'index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44';
parse_str(parse_url($url, PHP_URL_QUERY), $vars);
echo "Variables:\n";
print_r($vars);
$id = reset(explode(':', $vars['id']));
echo "The id is $id\n";
$id = intval($vars['id']);
echo "Again, the id is $id\n";
Unlike the example shown - which works - on my station, the variable array shows that "&" is encoded to "amp;" causing that script not to work for me.
When I output the variable array from the example, I get variables like [amp;id]
How can that scriptbe modified with the "&" decoded so it will work on my station?
Thanks for your help
simple solution is
$url = html_entity_decode('index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44');

Categories