...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
April 29, 2011

Is this a bit overboard or am I doing the right thing?

Question by Kyle

For logging in:

$username = mysql_real_escape_string(htmlspecialchars(strip_tags(trim($_POST['username'])), ENT_QUOTES));
$password = mysql_real_escape_string(htmlspecialchars(strip_tags(trim($_POST['password'])), ENT_QUOTES));

For inserting data I re-use the same mysql_real_escape_string(htmlspecialchars(strip_tags(trim(...

I feel like this is bad practice because I’m using so many functions… Is this the right way to protect against mysql injection & prevent xss injection? Or is it completely overboard? Everything works fine and nothing is broke–my question really is, am I using things that are obsolete when paired together? Is there only one function that I should use for the job?

Thanks.

Answer by Quassnoi

What if I use <mysecretpassword> as a password?

It will be stripped and anyone will be able to login as me.

I think you should store the username and password as it is and do htmlspecialchars only when displaying them.

strip_tags seems to be unnecessary here at all unless you really dislike usernames like BlaBla aka Yada-Yada <C00lHax0r>

Answer by Starx

Here is what is suggested by most of the answers.

$username = mysql_real_escape_string(trim($_POST['username']));

$password = md5("mysalt".mysql_real_escape_string(trim($_POST['password'])));
Read more

Making dynamic sized boxes

Question by Mohsen

I have a quiz that have four options to choose.
Every question have different options and sometimes an option have a long text that doesn’t fit in my fixed size boxes (say div).
I don’t want to have largest possible box to prevent overflow in my boxes. I want to size my box depended on longest option that I have in current quiz and if every option is short enough use fixed sizes that I had.

this is my HTML markup:

<div id="options">
    <div class="option 1">
        <span class="optiontText"></span>
    </div>
    <div class="option 2">
        <span class="optiontText"></span>
    </div>
    <div class="option 3">
        <span class="optiontText"></span>
    </div>
    <div class="option 4">
        <span class="optiontText"></span>
    </div>
</div>

and this is CSS:

#options{ width:800px;}
.option{width:380px; margin:10px;}

Text of optionTexts came from database and I want a jQuery function that size my boxes depended on size of text

Answer by Starx

It’s better you use The Jquery Equal Height Plugin to balance the height of the options.

Read more

JQuery will work with Fiddler, but not on my server

Question by user730663

Fiddler Link : http://jsfiddle.net/nLxc4/5/

My code :

<html>

<head>
    <script type="text/javascript" src="js/jquery-1.5.1.min.js"></script>
<script type="text/javascript">
function dynamicSearch() {
    var val = $('#search').val();
    if (val == '') val = '.';
    var srch = new RegExp(val, "gi");

    $('.active').each(function(i, el) {
        if ($(this).text().match(srch)) {
            $(this).show();
        } else {
            $(this).hide();
        }
    });
}

$(':checkbox').bind('change', function() {
    var div = this.value.replace('value', '#div');

    if (this.checked) {
        $(div).addClass('active');
        $(div).show();
    } else {
        $(div).removeClass('active');
        $(div).hide();
    }
});

$('#search').bind('keyup', dynamicSearch);
</script>
</head>

<body>

<form>
    <label for="search">Search:</label>
    <input type="text" name="search" id="search"/>

    <input type="checkbox" name="modtype" value="value1" />value1
    <input type="checkbox" name="modtype" value="value2" />value2
    <input type="checkbox" name="modtype" value="value3" />value3
    <input type="checkbox" name="modtype" value="value4" />value4
    <input type="checkbox" name="modtype" value="value5" />value5
    <div class="row" id="div1" style="display:none">Show Div 1</div>
    <div class="row" id="div2" style="display:none">Show Div 2</div>
    <div class="row" id="div3" style="display:none">Show Div 3</div>
    <div class="row" id="div4" style="display:none">Show Div 4</div>
    <div class="row" id="div5" style="display:none">Show Div 5</div>
</form>
</body>

</html>

As you can see, in the fiddler, when you click a check box it displays a particular div. On my home server, nothing happens. Can anyone see why this might be the case? Thanks very much.

Answer by Starx

Jsfiddler, wraps the js code inside $(document).ready() if you choose jQuery as the library. That’s why it is working there and not on your server.

Update the following in your code

$(document).ready(function() {  //This
$(':checkbox').bind('change', function() {
    var div = this.value.replace('value', '#div');

    if (this.checked) {
        $(div).addClass('active');
        $(div).show();
    } else {
        $(div).removeClass('active');
        $(div).hide();
    }
});

$('#search').bind('keyup', dynamicSearch);
}); //And This
Read more

What do you look for when selecting an open source solution for the task at hand?

Question by lobster1234

This could get quite confusing if there is a wider range of tools that fit the need – like logging in Java. In general, what would you, as fellow developers consider the so-called litmus test before making a selection between available open-source tools/libraries?

I can think about developer velocity, code documentation, the release frequency, committers’ reputation to name a few. Wanted to reach out to the community and get some more data points.

I apologize if this question belongs to programmers.stackexchange.com, I found that there are more questions tagged with open-source here than there.

Answer by thorsten müller

An active user base is often a good sign. If there is a forum or a mailing list, have a look, how many people use it, if there are recent posts and what kind of problems people have. When developing web sites with Ruby on Rails I had to choose a lot of OSS tools and an active community and answers to problems by the developers are a good sign. People are obviously still using it and problems are solved.

Answer by Starx

My main reason is the resources that are available on the internet.

  • Open Source solution, have good documentation.
  • Tips and Tricks or Tutorial are easily available.
  • Forums and discussion board are maintained in order to support.
Read more

Hiding and showing divs depending on variable value

Question by user712027

Can anyone please tell me why the code below is not showing the div ticker? it just shows div main ..

Thanks a lot!

<script language="javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script type="text/javascript"> 
    $(document).ready(function(){ 


        $('.ticker').hide();
        $('.main').show();
        $('.other').hide();

    }) 
</script>
<?php

$main = 'ticker';

if ($main=="ticker"){?>
    <script type="text/javascript"> //alert('flag'); //this alert shows ok
        $('.ticker').show();
        $('.main').hide();
        $('.other').hide();
    </script>
    <?php


}

?>
<div class="main">main</div>
<div class="ticker">ticker</div>
<div class="other">other</div>

Answer by Derek

Looks like you’re missing the $(document).ready() from the second script block.

Answer by Starx

Try this

<?php    
$main = 'ticker';    
if ($main=="ticker"){?>
<script type="text/javascript"> //alert('flag'); //this alert shows ok
    $(document).ready(function() {
        $('.ticker').show();
        $('.main').hide();
        $('.other').hide();
    });
</script>
    <?php
}
?>
Read more

PHP Session ID the same but variables are lost

Question by Nick

I have a login page that sets session variables upon successful login. The login page then redirects to an admin page. The admin page is able to read session variables just fine. But when I do a jQuery load() function that loads viewUsers.php in the content div the session variables are gone. The weird part is the session id is the same.

I used var_dump() on both the admin page and the viewUsers page. The admin pages shows all the proper variables from the login page but the viewUsers page which is called with a jQuery load() function var_dump of $_SESSION is blank. var_dump of $_COOKIE[‘PHPSESSID’] has the proper ID though, it doesn’t make any sense to me.

This is how I set the session variables.

$_SESSION['userID'] = $userInfo['ID'];
$_SESSION['userType'] = $userInfo['userType'];
$_SESSION['programID'] = $userInfo['programID'];

This is the jQuery

$("#content").load("viewUsers.php");

All pages have session_start() at the very top. The session variables also didn’t work when I tried window.open and window.location instead of a jQuery load() function.

Some how the session variables are getting lost even though I have the correct session id. If anyone could shed any light on this I would really appreciate it!

As of right now I’m populating hidden fields and using a post function instead of load to get around it. I understand this isn’t the best way, but it’s the only way I could figure out how to do it.

Edit:
Here is the top of the index which read the session variables fine.

 <?php
    session_start();
    //require("session.php");
    if(!isset($_SESSION['userID'])){
        header("location: ../login/index.php");
    }
?>

Here is the entire viewusers

    <?php 
session_start();

//foreach($_POST as $name => $value){
    //$_SESSION[$name] = $value;
//}

//echo " session id " . $_COOKIE['PHPSESSID'];
var_dump($_COOKIE);
var_dump($_SESSION);
?>

<?php require("adminFunctions.php"); ?>


<h2>View Current Users</h2>
<?php require("userlinks.php"); ?>
<table id="userTable" class="tablesorter">
    <?php getUsers($_SESSION['programID'], $_SESSION['userType']) ?>
</table>
<script type="text/javascript">

    $('td[name="userID"]').hide();

    //$("#userTable th").click(function(){
        //color();
        //colorTable();
        //color();
    //});

    function colorTable(){
        $("tr:odd").css("background-color", "#c0c0c0");
        $("tr:even").css("background-color", "#ffffff");
    }

    function color(){
        $("tr:odd").css("background-color", "#ffffff");
        $("tr:even").css("background-color", "#ffffff");
    }

    $(document).ready(function(){
        //colorTable();
        $("#userTable").tablesorter({widgets: ['zebra']});

    });
</script>

Another Edit:
Here is the javascript code to load viewusers
The only reason I’m using post is because I set the session variables as hidden fields in order to pass session variables. On viewusers I use a foreach loop to set the session variables. I understand this isn’t secure.
function maintainUsers(){

$.post("viewUsers.php", $("#sessionform").serialize(),function(data){
        //alert(data);
        $("#content").load("viewUsers.php");
    });
}

Answer by Starx

Normally, this sort of error occurs when you dont use session_start() to read the session data.

Try placing (Although, you said you have, I would suggest rechecking)

session_start();

At the beginning of your viewUsers.php

In case, the above is not the case, thenyour current page (the one from which you execute the .load() function) is resetting the session and tampering with the values. Unless you upload the code or find it out, there is no solution for this case.

Read more
April 28, 2011

Creating a simple but flexible templating engine

Question by Starx

I am trying to build a basic templating engine. Like the template engines already available as open source, I am using search and replace techniques.

However, as the search and replace have to be hardcoded, it is not so much flexible. What I mean to say is, as an example, I am using something like this

$templateMarkup = '<div class="title">{_TITLE_}</div>';
$renderedMarkup = str_replace("{_TITLE_}",$title,$templateMarkup);
echo $renderedMarkup;

As you can see, it is hardcoded. So I have to purposely know all the placeholders to accomplish a successful render.

I am a little bit weak in regular expression. But I know, if I can develop a regex, which can match all the text starting with {_ and ending _} and get the value in between them, I just might be able to create a flexible templating engine.

I need help with the regular expression.

If I am completely going the wrong way to accomplish, please do warn me.


For those who think I am reinventing the wheel. Here is my explanation

Templating engines, that are already available are quite unnecessarily complex. 
My requirements are simple and so I am builidng my own simple engine. 

Answer by Sam

The regular expression you’re looking for is {_(w+)_}, if your template tags are only ever a single word. You’d use it a bit like this:

<?php

$replacements = array(
    "firstname" => "John",
    "lastname" => "Smith"
);

$template_markup = "Hello {_firstname_} {_lastname_}";
if(preg_match_all('/{_(w+)_}/', $template_markup, $matches)) {
    foreach($matches[1] as $m) {
        $template_markup = str_replace("{_".$m."_}", $replacements[$m], $template_markup);
    }
}
echo $template_markup;

?>

You’ll see the preg_match_all has forward slashes surrounding the regular expression, these are delimiters.

Update: If you want to expand the regular expression beyond single words, then be careful when using . to match any character. It’s better to use something like this to specify that you want to include other characters: {_([w-_]+)_}. The [w-_] means it will match either alphanumeric characters, hyphens or underscores.

(Perhaps someone can explain why using . might be a bad idea? I’m not 100% sure).

Answer by Starx

I have combined the solutions provided by both Sam and James to create a new solution.

  • Thanks to Sam for the regex part
  • Thanks to James for the array mode str_replace() part.

Here is the solution:

$replacements = array(
    "firstname" => "John",
    "lastname" => "Smith"
);

function getVal($val) {
    global $replacements;
    return $replacements[$val];
}

$template_markup = "Hello {_firstname_} {_lastname_}";
preg_match_all('/{_(w+)_}/', $template_markup, $matches);
$rendered = str_replace($matches[0], array_map("getVal",array_values($matches[1])), $template_markup);
echo $rendered;
Read more

Background not visible due to positioning

Question by dragonfly

The background color of <ol> list is not displayed properly. This problem started after I floated label left and input right. How to fix this. The expected result is:

enter image description here

Here is my result: http://fiddle.jshell.net/WZ3nM/1/

Similarly I’ve problem with the div .wrapper. The shadow should be way below the content and there should be a white color background beneath <div class=.col-2>.

Answer by Elliott

I modified your code and added a third <li> with the following style:

clear:both;

Your float was taking elements out of the document flow and this the background color didn’t know where to end.

Hope that helps.

Answer by Starx

You need to clear the float, before you close your <ol>

Check it out here.

Read more
April 26, 2011

JQuery load at display page

Question by cosma

I’m newbie on web technologies and particular on jQuery so my question can be stupid.

What I want is to call a particular file (using .get or .post jQuery) when I click on some link and also load that file into browser. Also, the browser address should point to that file. This is what I have tried:

$('#my_link').click(
    function(event){
        event.preventDefault();
        $.get("index.php", function(data){
            $(document).html(data);
        });
    }
);

P.S.
I’m using .get/.post because I want to send some param. to that page (index.php), param. used to fill some fields.

Answer by Starx

I will suggest you, to try .load() method instead. It also provides options for sending params.

Here is an example based on the question.

$('#my_link').click(function() {
   $('#mydiv').load ("index.php", { param1: val1, param2: val2 }, function) {
      alert('loaded');
   });
});

I would suggest to load the contents on a division rather than the document itself.

Read more
April 25, 2011

How can I clear the input text.. when I clicked

Question by psygnosis

How can I clear inputttext..when I clicked the input text with jquery… no change.. I mean

example I have a input text and is value TEXT..

When I clicked the input text value is empty..

Answer by David Thomas

To remove the default text, on clicking the element:

$('input:text').click(
    function(){
        $(this).val('');
    });

I would, though, suggest using focus() instead:

$('input:text').focus(
    function(){
        $(this).val('');
    });

Which responds to keyboard events too (the tab key, for example). Also, you could ue the placeholder attribute in the element:

<input type="text" placeholder="default text" />

Which will clear on focus of the element, and reappear if the element remains empty/user doesn’t input anything.

Answer by Starx

I am supposing you are trying to create a effect, where the textbox contains a label. And when the user click in the textbox, it disappears and lets the user input the text. You do not require Jquery for this.

<input type="text" value="Input Text" onfocus="this.value=''" onblur="(this.value=='')? this.value='Input Text':this.value;" />

Demo

Read more
...

Please fill the form - I will response as fast as I can!