Posts Tagged ‘PHP’
RewriteMap directive in .htaccess file problem?
As written in Apache’s manual (Apache HTTP Server Version 2.2 Documentation):
RewriteMap Directive
(…)
Context: server config, virtual host
(…)
this directive can be set only as described, not in .htaccess file.
But really.. there’s no problem. Solution for PHP.
To replace links like:
http://www.com/index.php?fa=Shop.List&directoryId=334&subcat=f5a7&view=full
to
http://www.com/List,cable,tube,photo
A map file (should be hidden from browsers for the best) must contain some entrys ( values can be extracted from DataBase too ) i.e.:
File: rewriteMap.inc
List Shop.List
cable 349
tube f5a7
photo full
Then create an example rule:
RewriteRule ^([A-Za-z0-9_\-]+)\.htm$ /index.php?urlsel=$1 [NC,L]
[NC,L] (if needed) means no casesensitive and Last rule.
Condition ^([A-Za-z0-9_\-]+)\.htm$ specifies files with letters, numbers and - and _ and included .htm suffix.
This rule takes us INTERNALLY to:
http://www.com/index.php?urlsel=$1
where $_GET['urlsel'] is = “List,cable,tube,photo”
Now it can be processed and served.
Yet it can better.
Why not create shortest links as possible.
Instead of multiple parameter combinations, rewriteMap.inc can hold links already prepared for single locations or ready to use parameters for each single link.
Example file: rewriteMap.inc
guitar modelC3 param1 param2 param3 id1
guitar modelA3 param1 param2 param3 id2
drum modelSH param1 praram2 param3 id3
URL entered:
http://www.com/guitar-modelC3.htm
Rule invisible redirects us to:
http://www.com/index.php?urlsel=$1 ( user still sees http://www.com/guitar-modelC3.htm)
Inside of index.php $_GET['urlsel'] is = “guitar-modelC3″.
File index.php reads a rewriteMap.inc – or gets data from DB.
What’s good that even if You don’t secure this $_GET – nothing happens, cause there will be NO INDEX found, but depending of solution You may want to secure it (I do and You can read some at my previous article Secure PHP variables $_GET, $_POST – wrapper function).
Now data from rewriteMap.inc or database can be retrieved and put into control variables in script.
Data from rewriteMap.inc can be converted to an associative array indexed with keys as follows:
array[] of array[]
array[ guitar-modelC3 ] => array ([0] param1[1] param2 [2] param3 [3] id)
to simplify access.
Of course file rewriteMap.inc should be created dynamically by Your www/CMS engine, by hand only with small web services or in special cases.
With this solution and a hughe URL links count, You’ll have to consider some efficiency optimizations. But i’m sure You know that if you reading this.
Using data base engine to store rewriteMap data depends of created data base model.
And that’s it.
This is only workaround idea to .htaccess problem. Optimization, alternatives and security aspects are beside of this blog entry.
It works for me but I do not take responsibility of any entry on this blog. Use it all at Your own risk.
( I use comma instead of / to avoid special treatment for CSS, JS and other client side included files – we don’t need that at this time )
( About mod_rewrite and URL rewriting You can read a great article here: URL rewriting )
LABEL in PHP ’switch – case’ statement (almost GOTO)
Yeah i know, every good programmer loves ‘goto’ statement ;) I did not used it jet, but it works well i think, and was just written by me for some pal.
Code below uses the WHILE loop with a SWITCH statement to generate jumps between needed CASE: conditions. But You have to watch for the $condition or set emergency counter ($ctr) to avoid endless loop.
$code = 304; // start with some example code
$fork_question = false; // some IF to fork
$condition = false; // break if $condition is set or just secure the loop
$ctr = 0; // exit help counter or needed loops count (5 is set for example)
while( !$condition || $ctr == 5 ) {
switch ( $code ) {
case 1:
echo "in case 1<br />";
break;
case 304:
{
echo "in case 304<br />";
if ($fork_question)
{
echo "never here<br />";
}
else
{
echo "Try to jump to 'Label' 404 code<br />";
$code = 404; // set the new code - our LABEL jump
break 1;
}
}
case 390:
echo "in case 390<br />";
break;
case 404:
echo "in case 404<br />";
$condition = true; // !
break;
default:
{
echo "DEFAULT<br />";
break;
}
}
$ctr++;
echo "Loop: ".$ctr."<br />";
}
echo "end<br />";
exit;
Please use it free as always.
Cut string to given length or word count easy with _str_cut()
Another simple function of my library (extended at 09-09-2008).
Use it when You need to cut some text/string to given length in chars or specified word count and wish to add some suffix at the end like » read more or …
From:
$_str = “Here’s a sampling of features that might make you want to use WordPress.com. (Besides it being run by some swell folks!) We’re not fancy-pants marketers“
$_str = _str_cut( $_str, 30, “ » read more”);
To:
Here’s a sampling of features » read more
/**
* (C)2008 savride.wordpress.com
* @return String cut to needed length and with suffix if need one
* for example "..." as default or "<a href=" or what you just enter
* @param $_str Object given string
* @param $_len Object new length to set
* @param $_more Object[optional] suffix string instead of "..." fe. <a href="http://set_some.link.com">Link name set</a>
* @param $_cnt_words - cut to given words NUM - UPDATE
*/
function _str_cut( $_str, $_len, $_more = " ...", $_cnt_words = false, $_separator = " ")
{
$_str = strip_tags( $_str );
// return by WORD COUNT - update
if( $_cnt_words )
{
$_new_str = "";
if( $_cnt_words == 1)
return strtok( $_str, $_separator );
$_new_str .= $_separator.strtok( $_str, $_separator );
while( $_cnt_words > 0 )
{
$_new_str .= $_separator.strtok( $_separator );
$_cnt_words--;
}
return trim($_new_str, $_separator);
}
// return by WORD COUNT - update
$_start_len = strlen( $_str);
$_new_len = $_len - strlen( strip_tags($_more));
if ( $_start_len >= $_new_len)
{
$_str = substr( $_str, 0, $_new_len);
$_str = preg_replace( '/\s+[^\s]+?$/', "", $_str);
$_str .= " ".$_more;
}
return( $_str);
}
Feel free to use it.
Secure PHP variables $_GET, $_POST – wrapper function
If You’re tired of maintaining endless $_POST, $_GET or other multiple variables passed to Your PHP scripts, want to gain more control over them or just try to secure things from abusive users, bots etc. it’s conveniently to use some shortcut.
How to group them at one place? It’s easy, and it’s a time saver to simplify complicated.
Try this wrapper function. It’s especially not optimized fe. to switch or shortened in any way, both for tutorial purposes and that it comes straight out of my PHP project. The project is always ‘work in progress’ so some code has to stay unoptimized for further evaluation.
Some people use such code for so called front controller and other:
page = $_GET['page'];
swith($page) {
case 'home':
include_once('index.php');
break;
case: {...}
Try to avoid it.
You can have multiple places in your script where some variable has to be used and checked. Why do always the same and worst – insecure.
Do it better way:
/**
* Savride's environment variables filtering ($_GET, $_POST, etc.) (c) 2008
* wrapper function
*
* @return > a filtered value or redirect if filtered out as abuse
* @param $_option Object > get variable by index, example: 'pagename' (useful when var does'nt exist)
* @param $_old_option Object > use this as default if no value is set
* @param $_filter Object[optional] regexp for advanced filtering or simple /string/ to deny
*/
function _sopt( $_option, $_old_option = false, $_filter = false)
{
$_value = false;
if( isset( $_GET[$_option] )) {
$_get_t = $_GET[$_option];
if( $_get_t !== false)
$_value = $_get_t;
}
if( isset( $_POST[$_option] )) {
$_post_t = $_POST[$_option];
if( $_post_t !== false)
$_value = $_post_t;
}
if( $_filter) {
if ((( strpos($_filter, "#") !== false) && ( strpos($_filter, "#") == 0))
||
(( strpos($_filter, "/") !== false) && ( strpos($_filter, "/") == 0))) {
if ( !preg_match( $_filter, $_value)) {
$_value = false;
//echo "Error _sopt - unwanted chars";
}
}
else
if( strpos( $_value, $_filter) !== false) {
//echo "$_value | $_filter";
Header( "HTTP/1.1 403 Forbidden" );
exit;
}
}
if( !$_value )
{
if ( isset( $_old_option) && ( $_old_option != "") )
$_value = $_old_option;
else
$_value = false;
}
//echo $_value;
return( $_value );
}
Example usage:
// simplest (no multiple conditionals at this place in code)
$_var = _sopt('page');
// check for abusive http URLs injections
if(( _sopt( 'page', "", "http://" ) == false ) || ( _sopt( 'page', "", "http%3A%2F%2F" ) == false ))
(...)
if( _sopt( 'PHPSESSID', "", "http://" )
||
_sopt( 'PHPSESSID', "", "http%3A%2F%2F" ))
{...};
// check some sent FORM / LINK variable
if( _sopt( 'fbt_message_send', "") )
(...)
// variable check filtered with regexp
if( _sopt( 'subpage', "", "/^[a-zA-Z0-9]+$/" ))
(...)
And so on. Use this idea freely. I hope it’ll work for You.
This piece of code can be extended with a wider variable scope, not just $_GET… etc. also can be used with any variable check operation/validation.
Depends of functionality/speed overhead You can afford in Your project.
Caching for current script page variables can be added (eliminates $_GLOBALS access), also an additional parameter escaping functions.
The thing is: use single wrapper function, do not let variables spread all over your scripts.
Don’t let it be Yours one and only security line, as i said, it’s just a part of an environment validation but very useful and important.
Don’t put it in heavy for/while etc. loops.