Wwwebber's Blog

Php Script-Process, Display and Watermark all images in a Directory

Posted in free php scripts, image effects by wwwebber on December 13, 2009

I needed a bit of break from some large projects I’ve been working on so I made up a little script that will process, display and watermark all images in a directory. The script makes use of 2 classes. One class is a ImageViewer . This takes an image and watermerks it with whatever text you want.(font size and text is hard coded..so doesn’t work well for really small images…sorry just don’t have the time for that level of finesse at the moment)

The other class processes(DisplayImageDir) a directory by –it gets a list of all images in a given directory (anything with .jpg, .jpeg, .png, or .bmp)

The script will output a double columned display of all of the images in the directory with the watermark added!

You can download the scirpt

Here’s are some demo pages
http://www.mathwarehouse.com/code/php-scripts/imagewriter/
Images of Linear Equations

This script could definitely be improved and generalized. I simply wanted to make it easier for search engines and users of my site to be able to find, and if possibly download the many, many images I have over at Math Warehouse. However, I did want to ensure that there was a copyright watermark on each file.

The script works right out of the box, is open source and hopefully will be useful for someone.

This script ran on a Godaddy shared hosting account–about as budget as it gets so if you’re host doesn’t support the features for the script…it might be time for you to upgrade your account!

Also, note that I named one of the files .php5 to ensure that it was processed by php 5–this was necessary on teh GoDaddy server…you might need to rename the file as well as teh associated variable which is located in DisplayImageDir.class.php

Comments Off on Php Script-Process, Display and Watermark all images in a Directory

Ajax Based Paginator– Spare your server some resources

Posted in ajax by wwwebber on August 17, 2009

The traditional php pager
->each time you load a new page
A) Determine the number of entries per page (it’s up to you just decide! let’s call it number_per_page ) )
B) poll the entire table with SELECT count(*) …. to determine total number of records (let’s call this total_records)
B) calculate the total number of pages ( total_records /number_per_page ) let’s call this total_pages
C) figure out your current page (something like $_GET[‘page’] * number_per_page )
C) do a second query  pull only the needed rows using MySql’s LIMIT

With this approach, you always

  • query the DB twice each page and do not remember  total_records 
  • never remember previously fetched queries (ok…there are server side caching solutions to consider)
  • With an Ajax based pager, you can take advantage of the fact that you’ll not be reloading the entire page–
    this will allow us to do things

  •  1) only the poll the entire table once to calculate total_records–during the first time we connect and just store this number in a javascript variable
    (Yes, I know there  are ways to do this server side with sesions etc–but that’d certainly be more server intensive than storing
    the var on the  user’s machine in a javascript variable–I always like to foist off as much cpu on to  the user as possible!) Imagine the difference here with thousands of users online simultaneously  and cutting out a single query for each one .
      As an aside, I’ve read the select count(*) is instantaneous so carries little overhead-
    -but what if you’re select count(*) is a 6 table MyIsam join–even if that join is optimized with indices, it won’t be instantaneous and will cause some locking) It’d still be nice not to have to run the join every time you page)
  •  2) Also, we, with AJAX, we will be able to cache previously visited pages into an hash array so if a user goes from the first page to the second
    but then back to the first page…we can just use our cache (basically memcache ajax style). Again, there are server side equivalents…like memcache!…but let’s keep giving our users as much of the burden to bear as possible!
  • I. The AJax Pager

    Demo can be seen here on my site math games.com  — look on the right for the ‘recent high scores’

    the concept is pretty much the same as the server side one
    variables required
    var total_records //self explanatory
    var numberPerPage //self explanatory
    var nextStartAt   //representing the number the next query will start at…ie the MySql will be LIMIT nextStartAt,numberPerPage
    1) The pager  : 2 functions
     load_first_page() -> this loads the first page and reads the ‘total_records’ variable that is sent back from the database. I simnply but ‘total_records’ into a hiddent input field.
     This function here is pretty much the only difference from the traditional server side method.

    2) getNextPage(whichWay) -> just send your ajax based requests and load them into the html ( I use  .innerHTML). Psedo code
      if(whichWay ==’back’)
       nextStartAt -=  numberPerPage ; 
      else
       nextStartAt += numberPerPage ; 

     var url =’somesite . com?somequeryString=1&start=nextStartAt&numberRecords=numberPerPage’ 

     getAjaxBasedURL(Url) -> now,use JQuery or whatever you like to handle your Ajax request and response

     

    II. Creating the Cache
    We’re just going to create a a hashmap–ie an associative array whose hashes represent the
    unique query of each ajax call
      my hashmap code looks like

    var cache = new Array();

    function getAjaxBasedURL(Url){
      
      
     var key = mode + ” + nextStart + ” + numPerPage  +” +countryNumber ;

      // key must be ‘unique’ so your hash table has no collisions.  

     if( cache[key] != null){  //if in cache just load the cache
      loadDataIntoPage(cache[key]);
     }
     else
      // write code that fetches, then displays your new url’s data onto the current page
      // after your store on current page
      //store it into cache[key]
    }

    /////////

    The only other functionality that must be implemented is the following. You must tell PHP to calculate the total records during the first page’s request, and then of course send back the result of this query to store in javascript.

     

    Comments Off on Ajax Based Paginator– Spare your server some resources

    How To Delete from Multiple Tables in Mysql

    Posted in MySql by wwwebber on August 11, 2009

    $query1 = ‘DELETE FROM table1 where id=1’;

    $query2 = ‘DELETE FROM table2 where id=1’;

    Many MySql newbies don’t know that you can join delete just like select and updates. Here’s how you’d issue a single query in a join

    $betterQuery = ‘DELETE t1.*, t2.* FROM table1 t1 INNER JOIN table2 t2 ON t1.id= t2.id  WHERE  t1.id=1’;

    Same effect but you’re only query the datbase once rather than twice.

    Comments Off on How To Delete from Multiple Tables in Mysql

    Data-lists.com is a Scam

    Posted in Uncategorized by wwwebber on August 10, 2009

    I am writing this to so that others do not make the same mistake that I did. A brief summary

    1) I bought a database from data-lists(dot)com

    2) the site falsely advertisizes a 100% money back guarentee

    3) the data that I bought was unusable. They gave me a inconsistently formatted csv… For that reason, the data couldn’t be parsed into mysql.

    4) I explained my problems to the data-lists.com scammers . They did not respond to my emails and they did not refund my money.

    G0 here for a good US public schools database

    Comments Off on Data-lists.com is a Scam

    Clean up unwanted characters in a Mysql Database

    Posted in Uncategorized by wwwebber on July 25, 2009

    I recently had to cleanse a large MySql Database–over 130,000 records and many of the records had one or both of the following problems

    1) quotes were not escaped so you’d see a varchar with unescaped single quotes scattered throughout the string–that’s a problem since a single quote indicates the end of the varchar to MySql!

    2) The PHP side of the app did not work well ( in fact at all) with periods or commas…and of course we had a lot of them throughout the DB

    So here’s the SQL that might help you

    the SQL to remove all periods from someTable’s column called someColumn

    UPDATE  `someTable` SET  `someColumn`= replace( `someColumn` , ‘.’, ” )

    A little trickier looking was escaping all of the single quotes thorughout the db. Here’s how you add a single escape slash before the single quotes:

    UPDATE  `someTable` SET  `SsomeColumn`= replace( `someColumn` , ‘\”, ‘\\\” )

    I know that last bolded part probably looks wierd–just remember that you have to escape the escape character as well as the quote!

    Comments Off on Clean up unwanted characters in a Mysql Database

    Migrating an access file to mysql

    Posted in Uncategorized by wwwebber on July 17, 2009

    UPDATE TO THIS POST: avoid using data-lists.com– I bought two databases from them. One was fine  but the other was terrible, and I’m fighting them to live up to their website’s claim that you can get a refund. Again avoid these guys. If you need a good public or private school database, here’s a reliable one digitalpoint . Moreover, this guys list is available in various formats including a MySql dump.

    Ok, this post will help you if

    1) your data is an Access file (who the hell uses Access databases anyway?)

    2) You need that data in a MySql databases

    3) you have mysql  and phpadmin up and running on your computer (you probably also have apache up and running)

    The background : After doing a lot of comparison shopping for a few different databases ( I needed one for all public and private schools in the US), the best deal–by a long shot-was this site: http://www.data-lists.com/ — their data was way more complete–1000’s more unique records than  the others I saw and the price was even a bit better than most of the others that I saw out there. There was only 1 major draw back (at least at first it seemed like a draw back) the data only comes in 1 format: a Microsoft Access file–crap. I thought I was in for a major pain in the butt–and before I started researching how to try to parse an Access file into something I could import into mysql I discovered an awesome mysql to Access conversion  tool that is, amazingly enough, free and does a lot of the work for you–it’ll  import your Access db into your MySql db… All you need is mysql up and running on your computer and this baby’ll convert the entire thing for you!.

    To be able to do this my way (the easy way), just follow these steps

    1) make sure that you log into mysql and start it up, make sure that you have phpmyadmin booted up also

    2) download and install bullzip’s convertor tool , then run the tool. It’s pretty straightforward.

    3) you will be asked for a bit of mysql info–port number etc..

    4) At the prompt you want to do a ‘direct transfer’ which will just take the data and put into a database on your mysql server

    5) then you’re good. It’s in your server. Below is a screen shot of the converter tool in action!

    myqsql-convertor

    Comments Off on Migrating an access file to mysql

    Actionscript 3: loading external bitmapdata and sounds

    Posted in Uncategorized by wwwebber on July 12, 2009

    loading_flashI recently made a math game involving equivalent fractions –it was a lot of fun, my favorite kind of programming. It makes use of about 10 sound files including 4 sound tracks and about 40 rasterized images…needless to say the final file size was too big and the game loaded too slow..initially, the game was  almost 800 kb!  well, i  have almost got it below 500 kilobytes by loading all of the images externally as well as most of the sounds. It’s amazing what a difference the loadiong processcan  make for the end user. If you do it right, the user can just the directions about how to play the game while most or all of the graphics and sounds are being loaded in the background.

    Still, my biggest problem about preloading is the fact that flash does not support loading wav files at run time! This is amazingly annoying especially when you consider the fact mp3 files are a  pain in the but to deal with–if  you have to loop them–since mp3’s have header and leader space . If you need to loop mp3’s seemleassly just read this article compliments of 8bitrocket.com

    Comments Off on Actionscript 3: loading external bitmapdata and sounds

    Hashmap based on values of a key based array

    Posted in free php scripts, hashmap, job search script, sorting arrays by wwwebber on May 26, 2009
    I recently had to create a function that would take the values in a key based array and create a hashmap based off of the values. Basically, I had to switch the keys and values. (Remember there are no duplicate keys and I was going to need multiple objects associated with 1 key..this was all part of my free php job search script ) . Anyway, the goal was to take an array like this
    $before = array(
    “White Plains” => “NY”,
    “New York City” => “NY”,
    “Philadelphia”    =>”PA”,
    “Tampa”            =>”FL”,
    “Miami”            =>”FL”
    );
    </code>
    and turn it into

    $before = array(
    ‘NY’ => White Plains,New York City,
    ‘PA’ => Philadelphia,
    ‘FL’ => Tampa,Miami
    );

    function createHashMap(&$mc){
    $hashMap = array();

    while ($name = current($mc)) {
    $key = key($mc);
    //echo “key: $key , current:  “. $name . ‘ <br />’;
    if(isset($name,$hashMap)){
    //            $newKey = substr($key,0,strlen($key)-1) //remove last
    $hashMap[“‘”. $name .”‘”] .= $key .’,’ ;
    }
    else{
    $hashMap[“‘”. $name .”‘”] = “‘”. trim($key) .”‘”  ;
    }
    next($mc);
    }

    //print em out
    foreach($hashMap as $key => $value)
    echo $key . ‘ => ‘ . $value . ‘<br />’;
    }

    createHashMap($before);

    Comments Off on Hashmap based on values of a key based array

    Php Job Script : Free Job Aggregator

    Posted in free php scripts by wwwebber on May 24, 2009

    One of my clients wanted to me to create a php job script–not a job portal but rather a script that would allow people to search for all of the jobs that you find on indeed.com

    So I made up this script . It is largely open source (1 file is encrpyted…to make sure that the footer links remain intact:) )  Otherwise it is highly customizable and is SEO friendly as the entire script employs mod_rewrite.

    How can I earn money with Script?
    You can register for your own account at indeed.com and use your own ‘publisher id’ to get some cash for each click that a user makes. Also, from personal experience, I have noticed that cpc for Google Ad’s on my job search pages are decent–though would vary by industry.

    Where Can I See a Demo? demo of the default install for the USA and for  India

      Some Sites Using the Script

    What are the Server Requirements: Read them here.

    Where can I download it ? Here

    How can I remove the footer?

    • paypal $50  to  send it here  and I will send you an un-encrypted version. From there, you can do whatever you would like including removing the footer. However, you will need to find the relevant lines of code in the JobRoll.class file and remove them.

    How can I get the entire script unecrypted?

    • paypal $50  to  send it here
        Note: there is only 1 file that is enctyped (jobroll.class.php). The script’s style is easily manipulated with cascading style sheets. If you want to do some deep customizations then, yes, it might be worth the the money  to get the unenctyped jobroll.class.php –however, please make sure you are very comfortable with PHP before trying trying this.

    What Countries are Supported? USA  and India

    Download the script at Hot Scripts: Job Search Script

     

    Also, one of the benefits of the script is that it creates literally hundreds of SEO friendly web pages based off of every combination of city state and county. You can see an example of the site map (that can be customized by just changing a variable in the script here:

    PHP Sorting Parallel Arrays

    Posted in php arrays, private tutors by wwwebber on April 18, 2009

    This weekend I put the finishing touches on a zip code search program for Hubalub private tutors. The goal was for parents to be able to find all tutors within a given radius of a given zip code. Well, after brushing up on some of the fun non-Euclidean geometry necessary to calculate distance on a sphere (check out the Haversine formula at wikepedia), I found myself dealing with the following dilemna. I had about 8 parallel arrays representing the username, cityname and other personal details of the members who were within the radius of a given zip code.

    Below is simplified snapshot of the arrays in question.
    $userNames =array();
    $userAvatars = array();
    $distances = array();
    Naturally, I wanted to display the tutors by distance in descending order so that you’d see the closest tutor first. No problem right, just use one of PHP’s handy sorting functions like ksort() or krsort(), but if you ksort() an array, you’ve lost the whole ‘parallelism’ of the arrays! After toying with different possible solutions, the easiest one seemed to be to create a hashmap in which the distances served as keys and then concatenated all the user details into 1 long comma separated string (which could be exploded later). This allowed me to ksort() the array based on the key which was the distance! And Bam! user data is now in descending order based on distance. The only thing to be careful of is that if two distances were the same (ie duplicate keys) you’d end up with an array of buckets that you’d to loop over.

    Comments Off on PHP Sorting Parallel Arrays