Bouncy Numbers PHP

Bouncy Numbers on projecteuler.net

Under 7 seconds with ASUS G53J (xampp) PHP.

How does it work?
We start at 0, and check each number for “bounciness” until we get an even 99% (brute force method).

Although the script could be shortened, I found this one to be the quickest PHP script yet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
$num = 0;
$count = 0;
$percentage = 0;

//$num = 21780;
//$count = 19602;

$ts = microtime(1);

while($percentage != 0.99)
{
    $incline = $decline = false;
    $str = (string)$num;
    $len = strlen($num);
   
    for($i = 0; $i < $len; $i++)
    {
        if(isset($str[$i + 1])){

            if($str[$i] > $str[$i+1])
            {
                $incline = true;
                if($decline)
                    break;
            }
            else if($str[$i] < $str[$i+1])
            {
                $decline = true;
                if($incline)
                    break;
            }
           
        }
    }
   
    if($incline && $decline)
      $count++;
   
   $num++;  
   $percentage = $count / $num;
}

echo $num.' - '.(microtime(1) - $ts);

Drupal – Add all users to simplenews newsletter

The script below will add all users to your simplenews newsletter and subscribe them to the top most newsletter (if you have more that one newsletter, you can just loop through it)

This has only been tested in Drupal 5.x.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
   
    $user = "DB_USERNAME";
    $pass = "DB_PASSWORD";
    $db = "DB_NAME";

    $dbh = new PDO('mysql:host=localhost;dbname='.$db, $user, $pass);
   
   
        $sth = $dbh->prepare("
            SELECT users.name AS subscribed_mail, users.mail AS registered_users, users.uid, simplenews_subscriptions.snid, users.created
            FROM users
            LEFT JOIN simplenews_subscriptions ON users.mail = simplenews_subscriptions.mail
            UNION ALL
            SELECT users.name, simplenews_subscriptions.mail, users.uid, simplenews_subscriptions.snid, users.created
            FROM users
            RIGHT JOIN simplenews_subscriptions ON users.mail = simplenews_subscriptions.mail
        "
);
        $sth->execute();
        $row =$sth->fetchAll(PDO::FETCH_ASSOC);
       
        ?><table border="1">
            <tr>
                <th>Ref #</td>
                <th>UID</th>
                <th>Username</th>
                <th>Mail</th>
                <th>SNID</th>
                <th>Created (GMT)</th>
            </tr>
        <?php
            $notAdded = 0;
            $totalUsers = 0;
            foreach($row as $key=>$var){
                   
                    if($totalUsers % 2 == 0){
                        ?><tr style="background-color:#DDD"><?php
                    }else{
                        ?><tr><?php
                    }
                    ?>
                   
                        <td><?php echo $totalUsers+1; ?></td>
                        <td><?=$var['uid'];?></td>
                        <td><?=$var['subscribed_mail'];?></td>
                        <td><?=$var['registered_users'];?></td>
                        <td><?=$var['snid'];?></td>
                        <td><?php
                            if(!empty($var['created'])){
                                echo date("Y-m-d H:i:s", $var['created']);
                            };
                        ?></td>
                    </tr>
                    <?php
                   
                    $totalUsers++;
               
                //IF SNID IS EMPTY, IT ISN'T ADDED
                if(empty($var['snid']) && !empty($var['uid']) && !empty($var['registered_users'])){
                    $notAdded++;
                   
                    //ADD IT INTO SUBSCRIPTIONS
                    $sth = $dbh->prepare("INSERT INTO simplenews_subscriptions (mail) VALUES (?)");
                    $sth->execute(array($var['registered_users']));
                   
                   
                };
               
               
            }
        ?>
        </table><?php
       
        echo 'Number that needs to be added : '.$notAdded.'<br/>';
        echo 'Total users : '.$totalUsers.'<br/>';
       
        if($notAdded > 0){
            echo 'Added missing rows<br/>';
            $sth = $dbh->prepare("SELECT snid FROM simplenews_subscriptions");
            $sth->execute();
            $row = $sth->fetchAll(PDO::FETCH_ASSOC);
            //print_r($row);
            $news = $dbh->prepare("SELECT tid FROM simplenews_snid_tid GROUP BY tid");
            $news->execute();
            $news = $news->fetchAll(PDO::FETCH_ASSOC);
           
            if(!empty($news)){
                foreach($row as $key=>$var){
                    $sth = $dbh->prepare("INSERT INTO simplenews_snid_tid (snid,tid) VALUES (?,?)");
                    $sth->execute(array($var['snid'],$news[0]['tid']));
                }
            }
        }
   
?>

PHP Email Class

With the number of different emails a website may send, I find it easy to stay consistent in keeping one email format.

I decided to build a small PHP Email Class to send HTML e-mails.
Here is the class, below is the way it works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
    error_reporting(0);
    class email{
        var $subject = '';
        var $from = 'test@example.com';   //THIS IS THE EMAIL PEOPLE WILL REPLY TO
        var $to = '';
        var $message = '';
        var $logo = 'true';
        var $title = '';
   
        function __construct(){
            $this->headers = "From: " . strip_tags($this->from) . "\r\n";
            $this->headers .= "Reply-To: ". strip_tags($this->from) . "\r\n";
            //$this->headers .= "CC: test@example.com\r\n";     //IF YOU WANT TO MAKE A CARBON COPY
            $this->headers .= "MIME-Version: 1.0\r\n";
            $this->headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
        }
       
        function subject($subject){
            $this->subject = $subject;
        }
       
        function title($title){
            $this->title = '<h3>'.$title.'</h3>';
        }
       
        function logo(){
                    //HTML code will go here for the logo of the e-mail, this could include a link (Remember it has to absolute)
                    //EXAMPLE
                    return '<img src="http://mysite.com/images/logo.png"/>';
        }
       
        function to($to){
            //THIS NEEDS TO BE EITHER ONE VALUE OR AN ARRAY
            //user@example.com, anotheruser@example.com    Array('test@test.com','test@test.com');
            //User <user@example.com>    Array(0 => Array('user','test@test.com'));
            //User <user@example.com>, Another User <anotheruser@example.com>   Array(0
            $this->to = $to;
        }
       
        function from($from){
            if(isset($from)){
                $this->from = $from;
            }
        }
       
        function message($msg){
            $this->message = '';
            if($this->logo == 'true'){
                $this->message .= $this->logo();
            }
            $this->message .= $this->title;
             $this->message .= $msg;
        }
       
        function send(){
            if($this->to == '' || ($this->message == '' && $this->subject == '') ){
                //NO NAME
                return false;
            }
           
            if(is_array($this->to)){
                //MULTIPLE
                foreach($this->to as $key => $var){
                    if(isset($var[1])){
                        //NAMES
                        mail($var[0].'<'.$var[1].'>', $this->subject, $this->message, $this->headers);
                    }else{
                        //JUST EMAILS
                        mail($var[0], $this->subject, $this->message, $this->headers);
                    }
                }
            }else{
                //ONE EMAIL
                mail($this->to, $this->subject, $this->message, $this->headers);
            }
        }
       
        function __destroy(){
            $this->subject = null;
            $this->from = null;
            $this->to = null;
            $this->message = null;
        }
    }
?>

So how easy is it to get working???

1
2
3
4
5
6
7
8
require_once 'email.class.php';
$email = new email();
$email->to('user@example.com');
$email->subject('Welcome to my site');
$email->title('Hi there!');
$email->message('Just wanted to welcome you to my site');
$email->send();
$email->__destroy();

That’s how easy it is to send an HTML e-mail with that class.
Some notes

  • Will accept no subject or no message but not both
  • The above is expecting a logo, to remove the logo fully just use $email->logo = ‘false’;
  • There is a comment in the code on how to send to multiple people, example below
1
2
3
4
5
6
7
8
9
10
11
   $email = Array(
        0 => 'me@me.com',
        1 => 'test@test.com'
    );


    //OR
    $email = Array(
        0 => Array('Jack','jack@hill.com'),
        1 => Array('Jill','jill@hill.com')
    );

PHP garbage collecting

Recently I was working on a PHP object that kept going over the allowed memory limit. The easy way around that would be to bump PHP’s memory limit. Unfortunately I planned on running the script every 5 seconds. I find bumping PHP’s memory limit okay in certain circumstances but I decided that I was just going to do it properly.

PHP’s garbage collecting can be a little slow. Using unset() does unset the variable but it still exists in memory until garbage collecting has occurred (which may not be fast enough). This is no good for what I wanted. What is written below seems to work well. By assigning a null value to the variable, we clear any data off of it.

1
2
$var = null;
unset($var);

Basic, I know. But it works awesome!

PHP Thumb Generator 2011

First things first, I want to try and ensure every post on this blog is something interesting or creative.

This post is about a small script I threw together to create thumbnails of images.  Although this is not necessarily new or “creative”, I feel it deserves to be posted as it’s small and condensed.  Other scripts on Google are heavily outdated and a lot do not work.  The ones that do work contain workarounds that are not needed due to CSS3, or things you would never use (because we’re all Web 2.0 and all).

The script created does the following things

  • Can create thumbnail by width or height (it finds the correct dimension), or choose a custom width and height
  • Quality (1-100)
  • Output as a different format
  • Save the file as a new file (or overwrite)

It’s pretty basic, but it is essentially all you need.  I’ve uploaded it and it can be downloaded here.  Since WordPress is against files ending with certain extensions (namely zip files), remove the .txt extension from the file and it should work properly.

EDIT :

I’ve updated the script thanks to user pradip pointing out a problem. The script can be viewed here and downloaded here