Categories
General

Handy Tidbits: Create lots of files on linux quickly for testing

dd bs=1000000 count=20475 if=/dev/zero | split -b 4095 -a 7 -d – foo.

foo. (filename), 4095 = filesize (in bytes).

Taken from a comment by klode at
http://www.askdavetaylor.com/how_can_i_quickly_create_millions_of_tiny_files_in_linux.html#eb8sC3UpjoMBX0U1.99

Categories
Electronics General GitHub PHP

Using only PHP to save Google Starred items to Pocket!

So, based on my last post, I wanted to see if I could do everything with PHP. After a bit of google-fu and using the php.net manual, I’ve managed this beauty. Use at your own risk! This works with my Google Starred items, and you still have to obtain the starred.json file from the Google Take Out service (See my last post for more information).

If you have any tips on how to improve this, drop me a comment!

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Instapaper: Export</title>
</head>
<body>
<h1>Unread</h1>
<ol>
<?php

// First off, we start by opening the file required (starred.json),
// Then we set the $galbool paramater (This is used where sites have
// given a "Gallery" URL (To make it more cosmetic, it appends the
// text [Gallery] to the end of the description.

$file_handle = fopen("starred.json", "r");
while (!feof($file_handle)) {
    $galbool = FALSE;
    $line = fgets($file_handle);

// This is our first check. We run through the json file and look for
// lines that contain the text "href". If it does not have that text,
// we are not interested, and set that line to be blank.

    $preg = "(\"href\")";
    $urlcheck = preg_match($preg, $line);
    if ($urlcheck !== 1) {
    $line = "";
    } else {

// A cheeky little bit of coding. Whislt we are in the loop, and
// I know that this is a URL we are intersted in, I'll have a look
// at the last character. If its a ",", I also want to delete that
// line. Looking at the JSON file, if a line contains a URL and
// ends with a ",", it means its not the *ACTUAL* URL we want, so
// we continue our ruthless streak and set that line to blank!
// (This was included ot deal with hackaday.com URL's, which for
// some reason doubled up, and this was a quick and easy way to
// get rid of them!

        $preg = "(,)";
        $clean = preg_match($preg, $line);
        if ($clean !== 0) {
            $line = "";
        }
        }

// Now we trim the whitespace and other non-needed characters, and
// we remove the first bit from the string thats not needed. This
// takes us right to the http:// part of the link, which is what we
// need! We also remove the trailing slash from the link as well.

        trim($line);
        $line = substr($line, 16);
        $line = substr_replace($line, "", -2);
        $string = $line;

        $check = $string[strlen($string)-2];
        if ( $check == "/"){
            $string = rtrim($string);
            $string = rtrim($string, "/");
            $desc = $string;
        }
        $check = $string[strlen($string)-1];
        if ( $check == "/"){
            $string = rtrim($string);
            $string = rtrim($string, "/");
            $desc = $string;
        }

// This is just a quick check to see if the URL passed is a gallery
// URL. If so, we set the $galbool value to true, and then do our
// usual URL cleanup. I have removed the /gallery part from the URL
// This is personal preferance, and I've not had any adverse effects
// from either taking it in, or removing it. It has to be removed
// just now to make figuring out the link text easier though.
// We can add it back in later if required.

        $gallerycheck = str_replace("/gallery", "", $string, $count);
        if ($count == 1){
            $galbool = TRUE;
            $string = rtrim($string);
            $string = rtrim($string, "/gallery");
            $desc = $string;
        }

// And now for the (almost) finale! We take everything after the
// forward slash in the URL, remove that forward slash, then we
// run through and replace every "-" with a space. This makes the
// end HTML page look nice, and it keeps with Instapapers Export
// option. If the $galbool value is true, we create a [Gallery]
// tag.

        $desc = strrchr($string, "/");
        $desc = str_replace("/", "", $desc);
        $desc = str_replace("-", " ", $desc);
        $desc = ucwords($desc);
        if ($string != "" ){
        if ($galbool == TRUE){

// you can add back in the /gallery link here again if you need it!
// Just uncomment the relevant line and comment out the other!
//        -------------------------------------------------------------------------------------------------

//        $formatted = '            <li><a href="' . $string . '/gallery">' . $desc . '[Gallery]</a></li>';

//        ----------------------------------***OR THIS LINE***---------------------------------------------

        $formatted = '            <li><a href="' . $string . '">' . $desc . '[Gallery]</a></li>';

//        -------------------------------------------------------------------------------------------------

        } else {
        $formatted = '            <li><a href="' . $string . '">' . $desc . '</a></li>';
        }
        echo $formatted;
        }
    }

// We now close the file (good housekeeping), and finish up
// the script.

fclose($file_handle);
?>
</ol>
</body>
</html>

 

Categories
Electronics General

Custom Invitations using PHP!

People often don’t realise how versatile PHP and its add-on’s, including Imagik can be. I’ve used the following code in the past, and again recently, and I always receive comments on how nicely created invitations are. Its the personal touch that does it!

Firstly, I created an invitation using the awesome Pixelmator for Mac. You can use Gimp or Photoshop, or whatever takes your fancy, but what your looking for is a nice invitation with room for peoples names, like this:

Pre-PHP processing

(I’ve saved this as a PNG file)

Next up, some pre-processing work is required. I’ll go into this stuff in more detail in future blog posts, but what you want to do is set up a LAMP install (Linux, Apache, MySql and PHP). Make sure you have Imagik installed. You then want to install PHPMyAdmin, and create a database and one table with 2 columns (ID and Name).

ID Name
1 Nick T
2 Mr. A. N. Other

You can then plop the following code into your root directory, customise as needed, and away you go!

<?php
$con=mysqli_connect("localhost","USERNAME","PASSWORD","DATABASENAME");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Database connection has passed, now to select ALL the data from the Table "NAME"
$result = mysqli_query($con,"SELECT * FROM name");
while($row = mysqli_fetch_array($result)) //Grab everything and put it into an array
{ //Start the loop
$image = new Imagick('siteinfo.png'); //The name of the background image
$draw = new ImagickDraw(); //Tell imagick were going to draw on this image
$draw->setGravity (Imagick::GRAVITY_CENTER); //Centre our Text
$draw->setFillColor('black'); //Set the font colour to BLACK
$draw->setFont("/var/www/skia.ttf"); //Load the font we want to use
$draw->setFontSize( 40 ); //Set our font size
$text = $row['name']; //Place the name into a variable
$image->annotateImage($draw, 240, -150, 0, $text); //Write this name into the image at the location specified
$image->setImageFormat('jpg'); //Tell imagick were going to save it as a JPG
$name = $row['id'] . ".jpg"; //Give it the file name of its ROW in the database
$image->writeImages($name, TRUE); //Save it to the root folder (where the script was ran)
} //Lather, Rinse, Repeat!
mysqli_close($con); //Close the MySQL connection
?>

One of the important functions in the above script is the

$image->annotateImage($draw, 240, -150, 0, $text); //Write this name into the image at the location specified

Using the awesome documentation online at PHP.net, you find out that the 3 numbers, in order mean X position, Y position and angle. Angle is set to 0 because I don’t want the text angled. A nice straight line of text. The X position relates to where in the image the text is placed horizontally, and the Y relates to the vertical position. There was no hard and fast way to figure out those numbers, so I played about with them until I was happy. There is more than likely a function already created, or you could write your own that works out the exact location, but for my needs, a little bit of guessing with a small sample yielded pretty good results!

After running that PHP file, you get this at the other end:

Image 1
Image 1

and

Image 2
Image 2

The above took less than 1 second to produce, once the script was ran. I used this to create over 60 invites, and that took around 10 seconds of script execution time! (If I remember, I’ll put in a timer to see how long exactly it took. Bare in mind this was completed on the Ubuntu Laptop – which isn’t exactly a powerhouse!)

I’m fully aware that there was probably a workflow for Automator on the Mac which I could have used – but its nice to keep the PHP skills going for little things like this!

UPDATE: Using the 2 names above, the script was executed in 0.74 seconds – This is on a Dual Core Intel(R) CPU T1400 @ 1.73GHz with 1Gb of RAM.

UPDATE 2: Using 59 names from the database, the script was executed in 6.01 seconds. Not bad!