How To Generate a Random Password in PHP

Here’s a quick little snippet to generate a random password in php:

function createRandomPassword($length = 7) {
    $chars = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789!@#$%^&*(){}[]";
 
    $pass = '' ;
 
    while(strlen($pass) <= $length) 
    {
        $pass .= $chars[mt_rand(0, strlen($chars))];
    }
    return $pass;
}

How to create a silent [password] prompt in PHP

I’m creating a script that needs to ask for the MySQL root password and want to do a classic password prompt that doesn’t output the characters. I found this handy script that takes care of it.

The basic premise of the script is to detect windows. If found, use vbscript to create a popup InputBox. Otherwise, good ol’ linux allows you to suppress output:

/usr/bin/env bash -c 'read -s -p "Enter Password: " mypassword && echo $mypassword'

Here’s the whole script:

function prompt_silent($prompt = "Enter Password: ") {
  if (preg_match('/^win/i', PHP_OS)) {
    $vbscript = sys_get_temp_dir() . 'prompt_password.vbs';
    file_put_contents(
      $vbscript, 'wscript.echo(InputBox("'
      . addslashes($prompt)
      . '", "", "password here"))');
    $command = "cscript //nologo " . escapeshellarg($vbscript);
    $password = rtrim(shell_exec($command));
    unlink($vbscript);
    return $password;
  } else {
    $command = "/usr/bin/env bash -c 'echo OK'";
    if (rtrim(shell_exec($command)) !== 'OK') {
      trigger_error("Can't invoke bash");
      return;
    }
    $command = "/usr/bin/env bash -c 'read -s -p \""
      . addslashes($prompt)
      . "\" mypassword && echo \$mypassword'";
    $password = rtrim(shell_exec($command));
    echo "\n";
    return $password;
  }
}

Cookies with jQuery

Being able to set and read cookies asynchronously can be a great feature in many aspects of a web app. If you are looking for such a feature you probably already have jQuery attached to your app. All you need now is the jQuery Cookie plugin. You can pick that up at Here.

Once you have that attached in your files, you can easily start setting and reading cookies.

Set Cookie

$.cookie("cookie_name", "your_value");

Adding Options

$.cookie('cookie_name', 'your_value', { expires: 10, path: '/basepath/for/cookies', domain: 'yourdomain.com', secure: true });

The line above lets you set multiple parameters to the cookie. The above cookie would expire in 10 days and the path will set the area of your site the cookie will work.

If you were to do the same action in strictly javascript you would have to run more detailed code like:

document.cookie = "cookie_name=your_value; expires=16/07/2010 00:00:00; path=/basepath/for/cookies; domain=yourdomain.com";

jQuery is slightly easier to use in this regard but is even better when retrieving the cookie values.

Read Cookie

$.cookie("cookie_name");

Removing a cookie is also easy but they way you do it may not be the first guess a programmer would try without consulting documentation.

Remove Cookie

$.cookie("cookie_name", null);

Conditional Stylesheets in FBML

FBML doesn’t allow the IE conditional stylesheet comments in Facebook Fan Pages.  In order get similar functionality, we need to leverage the significantly more powerful user-agent tags. This allows you to post user-agent conditional code to your fan page for any browser type.

#submit-container { margin-top: 15px; }
#agree-container { position: relative; top: 10px; }
#submit-button { padding: 9px 20px; border: 1px solid green; color: black; }

What isn’t clear in the FBML documentation at this point is how accurate the user-agent application is. If I’m spoofing my user-agent, does the effectiveness of this tag diminish? Most people don’t spoof their user agent, but there are people who do so. Presumably if the user agent is the only test, they wouldn’t be able to view your fan page.

How To: Open CakePHP .CTP files with Dreamweaver

Here’s a useful link to configuring CakePHP to open CTP files for editing as though they are PHP files.

http://www.jamesfairhurst.co.uk/posts/view/opening_cakephp_files_in_dreamweaver/

PHP Generate UUID

Here’s one way to generate a UUID (GUID) in PHP

function uuid() 
{   
    // The field names refer to RFC 4122 section 4.1.2
 
    return sprintf('%04x%04x-%04x-%03x4-%04x-%04x%04x%04x',
        mt_rand(0, 65535), mt_rand(0, 65535), // 32 bits for "time_low"
        mt_rand(0, 65535), // 16 bits for "time_mid"
        mt_rand(0, 4095),  // 12 bits before the 0100 of (version) 4 for "time_hi_and_version"
        bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '01', 6, 2)),
            // 8 bits, the last two of which (positions 6 and 7) are 01, for "clk_seq_hi_res"
            // (hence, the 2nd hex digit after the 3rd hyphen can only be 1, 5, 9 or d)
            // 8 bits for "clk_seq_low"
        mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535) // 48 bits for "node" 
    ); 
}

How To Convert Seconds to Minutes in ActionScript 3

Recently, I’ve been developing a game in ActionScript 3 (which I’ll share later). I needed to have a second timer count down, which is easy enough with the Timer class. The hard part for me was formatting it so it made sense to the player. Here’s what I came up with for converting a second count to minutes (formatted string):

public function convertSecondsToMinutes(seconds:Number):String
{
     var secondsString:String = new String;
 
     if (this.time%60 < 10) // checks to see if it needs a leading zero
     {
          secondsString = "0" + this.time%60;
     }
     else
     {
           secondsString = "" + this.time%60;
           // the double quotes are needed to cast this as a string
     }
     var minutes:String=Math.floor(this.time/60) + &#039;:&#039; + secondsString;
 
     return minutes;
}

HttpPostedFile Maximum File Upload Size

I just ran into a file upload issue where file uploads were reaching the default maximum file upload size of 4MB. It was pretty straight forward to increase the HttpPostedFile maximum upload size, and I set it to 10MB for this site using the following in the web.config file:

<configuration>
 <system.web>
  <httpRuntime maxRequestLength="10240" executionTimeout="90" />
 </system.web>
</configuration>

I’m not a huge fan of ASP.NET. The tools are really handy and in general customizable enough for what I need, but the fact that they seem to be massively overhauled (yet miraculously still not on the cutting edge) with every release yields an efficiency problem. I simply cannot learn a massive new library every couple years, it just doesn’t make sense.

Plus, I love to know HOW things work, instead of just THAT things work.

My Browser Crisis

Firefox has always been Omega in my book. I’ve spent most of my life on a Firefox Missionary for all the IE users who didn’t know better. But recently I feel dirty. Deep down I am questioning my alignment. I start looking at my task manager and see Firefox spitting in my face with all the memory its taking. My Firefox was taking over 500M of memory and that was unacceptable to me. Why should the most common computer program, a browser, be running so inefficiently after this many years of tuning. I fought back with tweaks in the browser config, limiting it’s consumption. And like a fight with an ex-girlfriend, it said “Fine, if that’s the way you want it”. Browsing is painfully slow now. I’m hurt and feel betrayed.

Then the voice in my head asks “What else is out there?”. I’ve been hearing more and more good things about Chrome and recently heard the Web Developer plugin is available on that platform now as well. I would love to see some fast Javscript rendering too. And then I thought I would have never thought before: “What about IE?”.

I am conflicted to say the least. I got myself a copy of Chrome. My computer is running it like its a DOS Program. And if Chrome displays the same as Firefox why shouldn’t I set it as default. Well for now it’s because I am a loyalist to Mozilla but at this rate, change may be on the way.

Getting excited for Wordpress 3.0

I’m going to just come out right away and say I am not a big fan of Wordpress MU. There seems to always be plugin compatibility issues and getting multiple real top level domains to work on one system is troublesome to say the least.

But when I heard in the upcoming Wordpress 3.0 release MU will be merged with that of a single blog install, I got goosebumps to the point where my arm said “Thank you Matt Mullenweg” in braille. I am pumped to know all plugins will be for one platform now and even better all questions and support will be found in 1 forum! I hated having a problem in MU since the MU community is so much smaller but hopefully that will bind with wordpress.org. From the sounds of it we may still have to custom map domains which is a bummer but it may turn out to be easier to do.

Other features announced include better menu system and you will be able to choose a username right from the install. Goodbye “admin”!