Is there any way to get all GET vars with javascript? - php

First off, I do not want what is in the URL query. I want what PHP see's in the$_GET array.
This is because the URL query will not show all the params if mod_rewrite has been used to make pretty URLs
So is there a way to get the query string that would match exactly what is in the php $_GET array?
--
I came up with a way myself using PHP and JavaScript like so:
function query_string()
{
<?php
function assoc_array_to_string ($arr)
{
$a = array();
foreach($arr as $key => $value)
{
$str = $key.'='.$value;
$a[] = $str;
}
return implode("&",$a);
}
?>
return '<?=urlencode(assoc_array_to_string($_GET))?>';
}
...but I need to do this with just javascript if possible because I can't put PHP code in a .js file.

Won't JavaScript "only see" the query string? How would client-side script know about any rewrite rules?
The only way I can think of is to use PHP -- echo it into a variable in an inline script in your main page rather than the JS file.

In your page <head>:
<script type="text/javascript">
var phpQueryParams = <?php print json_encode($_GET); ?>
</script>
Assuming at least PHP 5.2, otherwise use an external package

The query string is found in window.location.search, but that's the raw query string. So if you run something like this:
(function () {
QueryStr = {}
QueryStr.raw = window.location.search.substr(1);
var pairStrs = QueryStr.raw.split('&');
QueryStr.val = {}
for(var i=0,z=pairStrs.length; i < z; i++) {
var pair = pairStrs[i].split('=');
QueryStr.val[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
})();
You'd have something very much like $_GET in QueryStr.val.
Of course, you mention that you've mixed things up a bit using mod_rewrite, which is cool, but since we don't know your rewrite scheme, we can't help specifically with that.
However... you know your rewrite scheme, and you could probably modify the code I gave above to operate on some other part of window.location. My bet is that you'd want to split window.location.pathname on the / character instead of &.

Related

Alternative for eval() -PHP

i am trying to implement URL mapping in PHP. I have a json file which stores the url and functions which is to execute when that link is requested. I was using eval() but then i came across this
Kepp the following Quote in mind:
If eval() is the answer, you're almost certainly asking the wrong
question. -- Rasmus Lerdorf, BDFL of PHP
now i am thinking is their any other(better) way to do it.
My json file looks like this.
{
"bw/":"main()",
"bw/login":"login()"
}
and my loadPage function look like this.
function loadPage($url){ //$url = 'bw/'
$str = file_get_contents('urls.json');
$this->link = json_decode($str, true);
$url = ltrim($url,"/");
$key = $this->link[$url];
eval("$key;");
}
EDIT:
i defined $this->link in my code
A slight tweak to your JSON to allow you to call the function dynamically would make it easier, just remove the brackets so it would look like...
{
"bw/":"main",
"bw/login":"login"
}
and then call it using...
function loadPage($url){ //$url = 'bw/'
$url = ltrim($url,"/");
$key = $this->link[$url];
$key();
}
A little better way is changing eval() to:
if (function_exists($key)) {
return $key();
}
return default();
and you might create a function "default" to show an error 404 or default page when function doesn't exists.

Rewrite parameters in query string to be compatible to php array

PHP accept array parameters in the query string using the [ ] format
http://my.url/bar.php?foo[]=1&foo[]=2&foo[]=3&foo[]=4
I need to allow the format without square brackets
http://my.url/bar.php?foo=1&foo=2&foo=3&foo=4
I don't want to change my application so I thought about rewrite the second URL to the first one. Is this possible in NGINX?
I think the solution is achievable with a quite simple lua script.
You could:
loop get_uri_args()
accumulate multiple values for the same key in a new key[] variable
put the new args in place using set_uri_args()
Something like the following (not tested, ajust to your real case):
// "foo=val1&bar=baz%foo=val2"
location = /test {
content_by_lua_block {
local args = ngx.req.get_uri_args()
local qs = {}
for key, val in pairs(args) do
if type(val) == "table" then
table.insert(qs, key.."[]" .. table.concat(val, key.."[]"))
else
table.insert(qs, val)
end
end
// qs = { foo[] = {"val1", "val2"}, bar = "baz" }
ngx.req.set_uri_args(qs)
}
// "foo[]=val1&foo[]=val2&bar=baz"
}
Note: this has to be extended if you whant to take into account "multidimensional" arrays too.

passing array from php to javascript

Hello
I'm trying to pass several arrays from php to javascript. For some of them it works, for others not. I get an array of filenames and an array which contains the content of several text files.
<?php
$album="./images/text_".$benutzerLang."_album1/";
$fileArray=lsRandom("./images/album1");
$listTextArray=initTexts($album,$fileArray);
$falseArray=lsRandom("./images/album2");
print $listTextArray[0];
?>
<script language="javascript" type="text/javascript">
var filesArray=new Array(5);
var falseArray=new Array(5);
var textListArray=new Array(5);
<?php
$i=0;
foreach($fileArray as $element){
print 'filesArray['.$i.']="'.$element.'";';
$i++;
}
$i=0;
foreach($falseArray as $element){
print 'falseArray['.$i.']="'.$element.'";';
$i++;
}
$i=0;
foreach($listTextArray as $element){
print 'textListArray['.$i.']="'.$element.'";';
$i++;
}
?>
function createText(){//...
</script>
<?php
function lsRandom($foldername){
$files = array();
$returnFiles=array();
$indexes=array();
$currentPath=getcwd();
chdir($foldername);
// Get the all files and folders in the given directory.
$files = glob("*", GLOB_BRACE + GLOB_MARK);
$indexes=(array_rand($files,5));
shuffle($indexes);
foreach($indexes as $in){
$returnFiles[$in]=$files[$in];
}
chdir($currentPath);
return $returnFiles;
}
function getFileText($fileName,$path){
$filePath=''.$path.''.$fileName.'';
//$file=fopen($filePath,'r');
//$text=fread($file,filesize($filePath));
$text=file_get_contents($filePath,false);
return $text;
}
function initTexts($album, $images){
$textArray1=array();
$i=0;
foreach($images as $im){
$nameArray=explode(".",$im);
$textName=''.$nameArray[0].'.txt';
$textArray1[$i]=getFileText($textName, $album);
$i++;
}
return $textArray1;
}
?>
The problem is the $listTextArray. In the 8th row I can print the whole array $listTextArray which contains the content of some small textfiles and it works. But further down in the 'foreach - loop'. It doesn't work anymore. As soon as I use the variable $listTextArray in the second php block the rest of my php code doesn't get executed anymore. I don't know why it can not access $listTextArray at that part. Because its no problem with the other arrays $fileArray and $falseArray.
Some general advice:
It's difficult to troubleshoot this kind of problem without the error message. If no error is being printed where you can see it, look for files named php.log, error.log, or httpd.log or ask your server admin(s).
Try using print_r() on your arrays to see if there's any difference in how they're structured. For example, just after setting the arrays in PHP:
print_r($fileArray);
print_r($listTextArray);
print_r($falseArray);
Rather than constructing the JS arrays via loops, try using the built-in json_encode() function instead. This both simplifies your PHP code and may cause more useful error messages when there are problems:
var filesArray=<?php json_encode($fileArray) ?>;
var falseArray=<?php json_encode($falseArray) ?>;
var textListArray=<?php json_encode($listTextArray) ?>;
you initiate
var textListArray=new Array(5);
but try to use
listTextArray
Use the same name and everything will be alright
The problem is already solved for you. Use json_encode instead.
print('filesArray = '.json_encode($filesArray));
Note that json_encode demands that your data is utf8 encoded. But you should do that already anyway.

Suggestive Search From JS Array, Possible?

Ok so what i want to be able to do is to perform a suggestive style search using the contents of an array instead of a doing a mySQL database query on every keyup.
So imagine a javascript object or array that is full of people's names:
var array = (jack,tom,john,sarah,barry,...etc);
I want to then query the contents of this array based on what the user has typed into the input box so far. So if they have typed 'j',both jack and john will be pulled out of the array.
I know this is possible via php mysql and ajax calls, but for reason of optimization I would like to be able to query the js array instead.
Hope someone can help me with this!
W.
as the name suggests, this finds elements of an array starting with the given string s.
Array.prototype.findElementsStartingWith = function(s) {
var r = [];
for(var i = 0; i < this.length; i++)
if(this[i].toString().indexOf(s) === 0)
r.push(this[i]);
return r;
}
// example
a = ["foo", "bar", "fooba", "quu", "foooba"];
console.log(a.findElementsStartingWith("fo"))
the rest is basically the same as in ajax-based scripts.
http://wwwo.google.com?q=autosuggest+using+javascript
AJAX calls fetch the contents from another serverside script files. You already have your data in the JS. Read a AJAX tutorial doing this. Then, just remove the parts where AJAX calls are made and replace it with your array's contents, and you're good to go.
I ended up using the following function to build my AJAX free instant search bar:
Example JS object being searched:
var $members = {
"123":{firstname:"wilson", lastname:"page", email:"wilpage#blueyonder.co.uk"},
"124":{firstname:"jamie", lastname:"wright", email:"jamie#blueyonder.co.uk"}
}
Example of function to search JS object:
$membersTab.find('.searchWrap input').keyup(function(){
var $term = $(this).val(),
$faces = $membersTab.find('.member'),
$matches = [];
if($term.length > 0){
$faces.hide();
$.each($members,function(uID,details){
$.each(details,function(detail,value){
if(value.indexOf($term) === 0){//if string matches term and starts at the first character
$faces.filter('[uID='+uID+']').show();
}
});
});
}else{
$faces.show();
}
});
It shows and hides users in a list if they partially match the entered search term.
Hope this helps someone out as I was clueless as to how to do this at first!
W.

Persistent HTTP GET variables in PHP

Let's say I have some code like this
if(isset($_GET['foo']))
//do something
if(isset($_GET['bar']))
//do something else
If a user is at example.com/?foo=abc and clicks on a link to set bar=xyz, I want to easily take them to example.com/?foo=abc&bar=xyz, rather than example.com/?bar=xyz.
I can think of a few very messy ways to do this, but I'm sure there's something cleaner that I don't know about and haven't been able to track down via Google.
Here's one way....
//get passed params
//(you might do some sanitizing at this point)
$params=$_GET;
//morph the params with new values
$params['bar']='xyz';
//build new query string
$query='';
$sep='?';
foreach($params as $name=>$value)
{
$query.=$sep.$name.'='.urlencode($value);
$sep='&';
}
If you are updating the query string you need ot make sure you don't do something like
$qs="a=1&b=2";
$href="$qs&b=4";
$href contains "a=1&b=2&b=4"
What you really want to do is overwrite the current key if you need to .
You can use a function like this. (disclaimer: Off the top of my head, maybe slightly bugged)
function getUpdateQS($key,$value)
{
foreach ($_GET as $k => $v)
{
if ($k != $key)
{
$qs .= "$k=".urlencode($v)."&"
}
else
{
$qs .= "$key=".urlencode($value)."&";
}
}
return $qs
}
View report
Just set the link that changes bar to xyz to also have foo=abc if foo is already set.
$link = ($_GET['foo'] == 'abc') ? 'foo=abc&bar=xyz' : 'bar=xyz';
?>
Click Me
You would have to render out the links with the proper URL querystring to make that happen. This is a design decision that you would need to make on your end depending on how your system is setup.
I have some sites that have this issue, and what I do is setup a querystring global variable that sets the current page data the top of the page request.
Then when I am rendering the page, if I need to make use of the current query string I do something like:
echo '<a href="myurl.php' . querystring . '&bar=foo';
It's not the cleanest, but it all depends on how your system works.
Save some code and use the built-in http_build_query. I use this wrapper in one of my projects:
function to_query_string($array) {
if(is_scalar($array)) $query = trim($array, '? \t\n\r\0\x0B'); // I could split on "&" and "=" do some urlencode-ing here
else $query = http_build_query($array);
return '?'.$query;
}
Also, though it isn't often used, you can have $_GET on the left-hand side of an assignment:
$_GET['overriden_or_new'] = 'new_value';
echo 'Yeah!';
Other than that, just do what Paul Dixon said.

Categories