play with PHP GET - php

can anyone help me to play with GET urls for example I have a link like this:
?id=5&lang=1
So my question is how can I make this one:
?id=5,1
I don't want to show the &lang, only I want is that the &lang to replace with , "comma" can anyone help me?

You can use mod_rewrite to rewrite ?id=5,1 to ?id=5&lang=1 internally.
Otherwise, the value of id will be 5,1. Your application would then need to know that id contains more than the id. It could then parse out the language from the id. However, this will become confusing when you introduce more parameters.

Assuming you have already built the URL in the way you have specified, you can break the id field based on the comma and extract the real id and lang field
$urlPieces = explode(",", $_GET['id']);
$id = $urlPieces[0];
$lang = $urlPieces[1];

You are able to do this, but it's not very clean, in terms of the proper $_GET variable values. The solution automatically type casts the values to integers:
sscanf($_GET['id'], '%d,%d', $id, $lang);
// $id = int(5)
// $lang = int(1)

Two solutions:
Firstly, you could simply reformat the parameters when they arrive in your PHP program. With ?id=5,1, you'll get a PHP $_GET array with id '5,1'. This you can simply split using the explode() function to get the two values you want.
The second solution is to use the Apache mod_rewrite feature, to modify the URL arguments before they arrive at PHP. For this, you'll need to understand regular expressions (regex), as mod_rewrite uses this for it's work. You should google 'mod_rewrite' and 'regex' to find out more.
However mod_rewrite is typically used to get rid of GET arguments entirely. For example the URLs of the questions on this site do not have any get arguments, but the server translates the arguments between the slashes into GET arguments. This is considered better practice than simply than changing how the arguments look, as it is more user-friendly and SEO friendly.
Hope that helps.

$id = $id . ',' . $lang;
<a href="?<?php echo $id; ?>">

Related

Find and concatenate result in a pattern

I have a long PHP file and I want to copy all the variable names only and build an insert sql query. Is there a way where I can search for a pattern using regular expression and concatenate the find result till I collected all the variable and spit it out in a statement?
I am using TextMate and am familiar with regular expression search. Regex search result give $0,$1 and so forth argument. Do not know if this possible though. Solution in any editor will do not just text mate.
I have just too many variable (+100) don't feel like copy every single one. Here my sample file
$ID = $_POST['id'];
$TXN_TYPE = $_POST['txn_type'];
$CHARSET = $_POST['charset']
$CUSTOM = $_POST['custom'];
You could try something with get_defined_vars(). However this function also lists GLOBAL vars. You can use this snippet to remove them if you don't want them and display only the vars you defined
$variables = array_diff(get_defined_vars(), array(array()));
However this snippet generates Notices and I haven't found a way to solve them yet.
If you've only got $_POST variables you can loop through the $_POST array itself
You create the SQL programmatically while looping through the array.
My own solution is, do the inverse. It is not probably possible.
Leave only the variable names Remove all the rest. Use
[space].+ regex to remove everything that is after the variable name.
clean the file so that only variable names are left. then do a couple more find and replace to bring the variable name in the form you want.
If you're looking to match only the variable names (not the $_POST array indices), then the regular expression is pretty much provided in the PHP documentation:
\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
This will, of course, include $_POST, but that should be easy enough to remove. If not, you could do it with negative lookahead (if TextMate supports it):
\$(?!_POST($|[^a-zA-Z0-9_\x7f-\xff]))[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

How do I break apart a URL to its component parts in PHP?

Regular expressions have never been one of my strong points, and this one has me stumped. As part of a project, I want to develop an SEO link class in PHP. Handling the mod_rewrite through Apache is fairly straightforward for me, and that works great.
However, I'd like to create a function which is able to generate the SEO link based on a dynamic URL I pass in as the first (and only) parameter to the function.
For example, this would be the function call in PHP:
Blog Post Title
The function CreateLink would then analyse the string passed in, and output something like this:
blog/blog-post-title
The URL stub of the blog post is stored in the Database already. I think the best way to achieve this is to analyse the dynamic URL string passed in, and generate an associative array to be analysed. My question is, what would the Regular Expression be to take the URL and produce the following associative array in PHP?
link_pieces['page_type'] = 'blog/post';
link_pieces['post'] = 123;
link_pieces['category'] = 5;
Where page_type is the base directory and request page without extension, and the other array values are the request vars?
You can just use parse_url and parse_str, no need for regexes.
Use parse_url to break the URL into parts:
This function parses a URL and returns an associative array containing any of the various components of the URL that are present.
Then use parse_str to break down the querystring part of the URL.

APACHE mod_rewrite change variable name in query string

I'm trying to change a variable name in a query string, so it's usable by my PHP code.
The query gets posts from an external system, so I can't control that they are posting a variable name with a space in it. And that makes it impossible for me to use the PHP $_GET function.
I need to change variable%20name to ?new1
And I need to change variable2 to new2
There are many variables passed in the query, but only these two need to be changed. The rest can stay the same or even disappear.
So ?variable%20name=abc&variable2=xyz
Needs to end up as ?new1=abc&new2=xyz
Also, they may not be in this order and there may be more variables
So ?variable%20name=abc&blah=123&blah2=456&variable2=xyz
Could end up as ?new1=abc&new2=xyz
OR as ?new1=abc&blah=123&blah2=456&new2=xyz
Either way would be fine!
Please give me the mod_rewrite rule that will fix this.
Thank you in advance!
Parsing the query string with mod_rewrite is a bit of a pain, has to be done with RewriteCond and using %n replacements in a subsequent RewriteRule, probably easier to manually break up the original query string in PHP.
The full query string can be found (within PHP) in $_SERVER['QUERY_STRING'].
You can split it up using preg_split() or explode(), first on &, then on =, to get key/value pairs.
Using custom%20cbid=123&blahblahblah&name=example as an example.
$params = array();
foreach (explode("&", $_SERVER['QUERY_STRING']) as $cKeyValue) {
list ($cKey, $cValue) = explode('=', $cKeyValue, 2);
$params[urldecode($cKey)] = urldecode($cValue);
}
// Would result in:
$params = array('custom cbid' => 123,
'blahblahblah' => NULL,
'name' => example);

Take all $_GET and add to end of url?

I have a bunch of methods of sorting date=desc,etc,etc and they are posted via a $_GET I want to take all the $_GET variables ($_GET['anythingatall']) and transform them from $_GET['variable]=blah to &variable=blah
Is there a simple way to do this?
You are interested in $_SERVER['QUERY_STRING'], I think. This will contain everything passed in $_GET but in the format you desire.
This might work for you
$string = http_build_query($_GET, null, '&')
Alex's solution should work too, and admittedly cleaner. If you wanted to create a query string from any other array using http_build_query should work fine.
If all you're wanting to do is pass on the existing query string (which is available in $_GET), you can use $_SERVER['QUERY_STRING'], which will be exactly what you're looking for, a query string representation of the $_GET array (assuming you didn't change it)
See the PHP documentation on the $_SERVER superglobal.
you may want to take a look at http://us.php.net/manual/en/function.http-build-query.php

Multiple Variables into 1 in a URL

I am looking to have a list of arguments passed across in an a URL.
$url['key1']=1;
$url['key2']=2;
$url['key3']=3;
$url['key4']=4;
$url['key5']=5;
$url['key6']=6;
$url['key7']=7;
Please Note I am trying to pass this in the URL in 1 GET variable. I know this would be better done by ?key1=1&key2=2&key3=3...etc but for reasons that are too complicated to try and explain they can't be in this format.
Any suggestions how I can convert this array into something that can be passed as 1 get var in a URL string?
Thanks in advance.
You can use json_encode() or serialize()
$myUrl = 'http://www.example.com/?myKey=' . urlencode(json_encode($url));
or
$myUrl = 'http://www.example.com/?myKey=' . urlencode(serialize($url));
Using json_encode will usually give you a shorter string, but very old PHP version might not have the json_decode function available to decode it again.
The final way would be to create your own custom encoding... it could be as simple a pipe-separated values: key1|1|key2|2|key3|3
This would give you the best option for a short URL, but is the most work.
Try http_build_query:
$url['key1']=1;
$url['key2']=2;
$url['key3']=3;
$url['key4']=4;
$url['key5']=5;
$url['key6']=6;
$url['key7']=7;
echo http_build_query($url);
//echos key1=1&key2=2&key3=3&key...
What it does is converting an array into a query string using the keys and automatically takes care of url-encoding.
EDIT:
Just read your additional requirement that it should be just one variable. So nevermind this answer.
If your problem was the proper encoding though you might want to give this another try.
Hope that helps.
The recommendation to use serialize() is fine. If space is an issue, then use a combination of bzcompress() and serialize().
However, there's a security considering that hasn't been brought up, and that's that the end user (who can see and edit this url) could manipulate the data within it. You may think it's difficult, but most of the PHP-attacking worms in the wild do this to some degree or another.
If letting the user directly manipulate any of the keys or values (or replacing it with an integer, or an object, or anything else), then you should protect your script (and your users) from this attack.
A simple solution is to simply use a shared secret. It can be anything; just so long as it's unique and truly secret (perhaps you should randomly generate it at install-time). Let's say you have in your config file something like this:
define('SECRET', 'unoqetbioqtnioqrntbioqt');
Then, you can digitally sign the serialized data created with: $s=serialize($m) using $k=sha1($s.SECRET) and make the url value $k.$s
Then, before you unserialize() do this:
$v=substr($input,0,40);
$s=substr($input,40);
if ($v != sha1($s.SECRET)) { die("invalid input"); }
$m=unserialize($s);
This way, you know that $m is the same as the original value that you serialized.
If you like, you can use the following drop-in replacements:
define('SECRET','buh9tnb1094tib014'); // make sure you pick something else
function secureserialize($o) {
$s=serialize($o);
return sha1($s.SECRET).$s;
}
function secureunserialize($i) {
$v=substr($i,0,40);$s=substr($i,40);
if ($v!=sha1($s.SECRET)){die("invalid input");}
return unserialize($s);
}
You could serialize them as key-value pairs when constructing the URL, putting the resultant serialized value in a single $_GET variable (e.g. data=sfsdfasdf98sdfasdf), then unserialize the $_GET["data"] variable. You'll need to use urlencode to make sure the resultant serialized values are URL-safe. Make sure you watch out for maximum URL lengths - 2083 characters in IE.
However, unless you really can't use key-value pairs in URLs (per your question), key1=foo&key2=bar... is definitely the way to go.
If you don't mind dropping the key names, you can use
http://example.com?url[]=1&url[]=2&url[]=3
EDIT Keeping the key names:
http://example.com?values[]=1&values[]=2&values[]=3&keys[]=1&keys[]=2&keys[]=3
Then in your PHP script:
$url = array_combine($_GET['keys'], $_GET['values']);
Could you solve your problem by saving the data as a HTML cookie? That way you don't have to modify the URL at all.
If you know the values in advance, you can set them from the server side when you send the user the page with your target link on it.
If you won't know the values until the user fills out a form it can still be done using JavascriptL When the user clicks the form submit you can set multiple cookies by making multiple javascript calls like:
document.cookie = 'key1=test; expires=Mon, 7 Sept 2009 23:47:11 UTC; path=/'
The security model might give you some trouble if you are trying to pass this data from one domain to another though.

Categories