Feb 022014
 

Below is a simple CLi coin flip I created to help me decide on what to do for lunch.. Don’t forget to change the mode of the file:

$ chmod +x flipcoin

Usage:

$ ./flipcoin # Flips 3 times by default
$ ./flipcoin 1234 # Flips 1234 times
#!/usr/bin/php
<?php
/*
Determine the number of flips.
This assumes you won't be putting in values <=0 
*/
$lim = (array_key_exists(1,$argv)) ? $argv[1] : 3;
 
/*
Set counters, $heads, $tails and $c(ount)
*/
$heads=$tails=$c=0;
for($i=0;$i<$lim;$i++) {
        $c++;
        $int = rand(1,1000);
/*
If $int modulo 2 leaves a remainder, call heads;
else call tails
*/
        if ( $int % 2 ) { echo '!'; $heads++; }
        else { echo '.'; $tails++; }
        if( ($c % 50) == 0 ) { echo "\n"; }
}
/*
Echo the winner, if there was one
*/
echo "\nAfter {$lim} flips: {$heads} Heads(!) and {$tails} Tails(.)\n"
.( ($heads > $tails) ? 'Heads' : ( ($tails == $heads) ? 'Nobody' : 'Tails' ) )
." wins.\n";
 
/* Check for ties, and break them with one last flip  */
if($tails == $heads) {
$int = rand(1,1000);
echo "\n".'Single Tie Breaker Flip:  ';
if ( $int % 2 ) { echo 'Heads Wins.'; }
else { echo 'Tails Wins'; }
echo "\n";
}
exit(0);
?>

It’s nothing crazy, but it is fun to watch 100,000,000 coins being flipped..

After 100000000 flips: 50005803 Heads(!) and 49994197 Tails(.)
Heads wins.

Enjoy!

Sep 092011
 

Adding compression to your PHP scripts is as easy as:

<?php
// start at the beginning of your output.
ob_start();
 
/*
//////////////////////////////////////////////////
output will be here, whatever it is.
/////////////////////////////////////////////////
*/
 
// and after your output.
ob_flush();
ob_end_clean();
?>

No, really. It is that easy.

May 272011
 

I was bored the other day so I made a very simple article spinner…

Takes a sentence like this:
The {quick|fast} {brown|black} {fox|dog|cat} jumps {over|above|around} the {lazy|sleepy} {horse|cow|donkey}.

And turns it into something like:
The fast brown cat jumps above the sleepy donkey.

$content = "The {quick|fast} {brown|black} {fox|dog|cat} jumps 
{over|above|around} the {lazy|sleepy} {horse|cow|donkey}.";
function spinaround($content)
{
    preg_match_all('/{(.*)}/sU',$content,$matches);
    foreach ($matches[0] as $k=>$v)
    {
        $string = $matches[1][$k];
        $new = explode('|',$string);
        $new = $new[array_rand($new)];
        $content = str_replace($v,$new,$content);
    }
return $content;
}
echo spinaround($content);

I know what you’re thinking; “But most article spinners can do two levels of spinning!!” Yeah, well, using regex to do so is a bit of a pain, however using square brackets [ ] this is entirely possible, as follows:

Takes this:
The {quick|fast} {brown|black} {fox|[fat|skinny] dog|cat} jumps {over|above [and beyond|and below]|around} the {[overly|somewhat] lazy|sleepy}
{horse|cow|donkey}.

Turns it into:
The fast brown fox jumps above and beyond the overly lazy horse.

$content = "The {quick|fast} {brown|black} {fox|[fat|skinny] dog|cat} jumps 
{over|above [and beyond|and below]|around} the {[overly|somewhat] lazy|sleepy}
{horse|cow|donkey}.";
function spinaround($content)
{
    preg_match_all('/{(.*)}/sU',$content,$matches);
    foreach ($matches[0] as $k=>$v)
    {
        $string = $matches[1][$k];
        if ( preg_match_all('/\[(.*)\]/sU',$string,$stringmatches) )
        {
            foreach ($stringmatches[0] as $l=>$w)
            {
            $new = explode('|',$stringmatches[1][$l]);
            $new = $new[array_rand($new)];
            $string = str_replace($w,$new,$string);
            }
        }
        $new = explode('|',$string);
        $new = $new[array_rand($new)];
        $content = str_replace($v,$new,$content);
    }
return $content;
}
 
echo spinaround($content);

Now I know the standard ‘spinables’ use { } for both sets of spinning, but oh well.

Enjoy.

Apr 162011
 

You may have heard of prepared statements, but don’t quite understand the differences. In this post I’m going to try and help you with that. Well, with your standard query, you would get your information, escape it for safety, build your query and execute.

<?php
/* instantiate our class, and select our database automatically */
$sql = mysqli('localhost','user','password','database');
 
/*
let's assume we've just received a form submission.
so we'll receive the information, and we'll escape it
*/
$name  = $sql->real_escape_string($_POST['name']);
$age   = $sql->real_escape_string($_POST['age']);
$email = $sql->real_escape_string($_POST['email']);
 
/* build the query, we'll use an insert this time */
$query = "INSERT INTO `tablename` VALUES ('$name','$age','$email');";
 
/* execute the query, nice and simple */
$sql->query($query) or die($query.'<br />'.$sql->error);
?>

So, what is an advantage to doing this? An advantages is you can view the full query prior to running it, simply by echoing it out. How does this help? It lets you make sure that your query is building properly before you start executing it.
What is a disadvantage? Well, you have to escape each string for security purposes, that takes a little more time than some people may like to spend.

And how about prepared statements?

<?php
/* instantiate our class, and select our database automatically */
$sql = mysqli('localhost','user','password','database');
 
/*
let's assume we've just received a form submission.
so we'll receive the information, and we'll escape it
this step is not necessary, but why not.
*/
$name  = $_POST['name'];
$age   = $_POST['age'];
$email = $_POST['email'];
 
/* build the query, we'll use an insert this time */
$query = $sql->prepare("INSERT INTO `tablename` VALUES ('?','?','?');");
 
/*
bind your parameters to your query
in our case, string integer string
*/
$query->bind_param("sis",$name,$age,$email);
/* execute the query, nice and simple */
$query->execute();
?>

The beauty of these prepared statements is there are fewer steps, and you need not escape the parameters because the bind_param() will do that for you.

So prepared statements are best suited for queries that take user input, such as an INSERT or UPDATE query, or a DELETE or SELECT with a WHERE clause.

Hope that helps.

Apr 012011
 

So you may have been looking through a PHP script you downloaded and seen a bit of logic that you didn’t even know was possible. What you probably saw was Ternary Logic, it had a question mark and a colon (?:) in use, making it more confusing for you. Well not any more, here comes the clarifier. The easiest way to do this is take a long hand if/else and then create a ternary logic statement to match it. So let’s try that.

<?php
/* we'll set a $gender variable, typically you will already
 have your variable set elsewhere */
$gender = 'male';
 
/* so we'll create a basic if/else */
if ( $gender == 'male' ) {
    $title = 'Mr';
} else {
    $title = 'Mrs';
}
echo $title;
/* that makes sense right? */
/* we can shorten that easily, using ternary logic */
$title = ($gender == 'male' ? 'Mr' : 'Mrs');
echo $title;
/* Also instead of putting our result into a variable, we can just
as easily put it in-line with our code, if we want to */
echo  "Hello " .($gender == 'male' ? 'Mr' : 'Mrs'). ". Smith, how are you?";
/* in our case this will output: "Hello Mr. smith, how are you?" */
 
?>

So as you can see the ternary logic form, if you were to read it as english, would read something like “$title gets the value of ‘Mr’ if $gender is equal to male, and ‘Mrs’ if $gender is not male.”

“Ok, that’s fine, but what if I want to return a true or false value?” Well that’s even easier! Let’s try it:

<?php
/* explicitly tell PHP to return a true or false */
$result = (1+1==2 ? true : false);
 
/* or imply that you want a true or false like so: */
$result = (1+1==2);
echo ($result ? '$result is true' : '$result is false');
 
?>

The above second example $result will set $result to have the return value of the expression (1+1==2) which, as far as I know is true.

And there we go, a very basic example of ternary logic, practice makes you better, so practice lots. I hope you found this helpful.