tail -f /robot/mind > blog

awesome-robot

tail -f /robot/mind > blog


PHP Script to get user's location

Thursday, January 19th, 2012

 

This is a quick little function that uses cURL to scrape a third party website to get information about a users's location. I've noticed that the response may not always be very accurate, so I wouldn't recommend this for anything where the location actually matters. 

function location_information($ip_address) {

    #create an array of fields we will be searching for. This array is used later

    $fields = array ("Country","State/Province","City","Zip or postal code","Latitude","Longitude","Timezone","Local time","Hostname");

 

    #url of the site we'll be scraping

    $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip_address);

 

    #initialize curl

    $ch = curl_init();

 

    #set array of curl options

    $curl_opt = array(

        CURLOPT_FOLLOWLOCATION  => 1,

      CURLOPT_HEADER          => 0,

        CURLOPT_RETURNTRANSFER  => 1,

        CURLOPT_USERAGENT       => $_SERVER['HTTP_USER_AGENT'], #send the user's useragent, just in case they start blocking requests from servers

        CURLOPT_URL             => $url,

        CURLOPT_TIMEOUT         => 1,

        CURLOPT_REFERER         => 'http://' . $_SERVER['HTTP_HOST'],

    );

    #set the options

    curl_setopt_array($ch, $curl_opt);

    #run curl, get content back in a string

    $content = curl_exec($ch);

    if (!is_null($curl_info)) {

        $curl_info = curl_getinfo($ch);

    }

 

    #close curl

    curl_close($ch);

 

    #loop through array of fields we're looking for, pull out corresponding values

    foreach($fields as $field) {

iif ( preg_match("{<li>$field : ([^<]*)</li>}i", $content, $regs) ) {

$location[$field] = $regs[1]; }    
}

}

    #return array of location information

    return $location;

}

 

Usage is as follows:

print_r(location_information($_SERVER['REMOTE_ADDR']));


MySQL Fuzzy Dates

Monday, November 28th, 2011

So I was in a discussion in a how-to forum I like to frequent to both learn new stuff and help others when it was proposed that MySQL couldn't do "fuzzy dates." I felt I had to prove them wrong, as any good internet debater inevitably ends up doing. Fuzzy dates are when you see blog posts or forum posts and they say stuff like "Posted 5 days ago" or "Last updated 3 years ago."  So, how can it be done?  Here you go:

SELECT 

    CASE 

        WHEN DATEDIFF(NOW(),`posted_date`) <1  THEN  'today')

        WHEN DATEDIFF(NOW(),`posted_date`) =1  THEN  '1 day')

        WHEN DATEDIFF(NOW(),`posted_date`)<=31 THEN  CONCAT(DATEDIFF(NOW(),`posted_date`),' days')

        WHEN DATEDIFF(NOW(),`posted_date`) BETWEEN 31 AND 60 THEN '1 month')

        WHEN DATEDIFF(NOW(),`posted_date`) BETWEEN 61 AND 365 THEN  CONCAT(ROUND(DATEDIFF(NOW(),`posted_date`)/31),' months')

        WHEN DATEDIFF(NOW(),`posted_date`) BETWEEN 365 AND 730 THEN '1 year')

        WHEN DATEDIFF(NOW(),`posted_date`)>730 THEN  CONCAT(ROUND(DATEDIFF(NOW(),`posted_date`)/356),' years')

    END `fuzzy_date`,

    `article_id`,

    `anything_else`

FROM 

    `articles_table`  ORDER BY `posted_date` DESC LIMIT 25

Basically what we're doing is subtracting the "posted date" of the article from today's date. For that, we're using MySQL's built in "NOW()" function.  We're manually clumping the various date ranges in to make them more audience friendly.  If you know of a better way to do this, by all means, post here and let me know.  Also, if you've found this helpful and have found a way to modify it to fit your application, let us know!

 


Form Filler Chrome Plugin

Monday, August 15th, 2011

So, I've created a Chrome plugin, and I'm pretty excited. 

As you know, I am a web developer and make forms pretty much every day. I was testing a form recently that had dozens upon dozens of fields that had to be filled out then submitted.  So I decided to look for an extension that would populate these forms for me and none of them did what I needed. They were all either overly complicated or didn't work at all. So I made one myself.

Here's the link:

https://chrome.google.com/webstore/detail/lgkfngpnlpjjjodgkmcmecnjdianeome?hl=en-US

This is an extremely easy-to-use, quick, stripped down form filler to use for testing forms.  It will auto populate forms with one of three types of sample data, element name, serialized number, gibberish string.  It also has a "clear" button.

Other features are that it will try to detect fields looking for email addresses and populate a sample email address, and it will try to detect phone and fax numbers, and populate those accordingly.

I encourage you to check it out, and leave me good feedback on that site if you like it. And if you have any issues or bugs or even questions.

 


Tutorial: Crash Course in PHP - Make your first web app in 1 hour or less

Tuesday, January 25th, 2011

This is an extremely basic tutorial for php and mysql.  This is the most basic application I could think of that still explains enough to get you started along your path of programming in php and mysql. It's not pretty, it's not innovative, and it's not even really all that interesting, but it's the best way to get your feet wet.

 

Before you begin:

For this tutorial, we're going to assume that you're hosting your site on a webhost like GoDaddy or Hostica.  Make sure you have the following:

  • FTP Host, Username and Password
  • Database Username and Password
  • Access to your phpMyAdmin for your site
  • An IDE. I recommend Komodo Edit
What exactly will we be doing in this tutorial?
Today we're going to create a guestbook. But, "that's so 1996" you say?  Yes, it is. But guestbooks are easy and give us enough features to play with without getting too confusing.  Essentially, we're going to make a page with a form that gets submitted to a database and another page that formats and displays those submissions. 
Some of the things you will learn are:
  • Using php to create HTML
  • Accessing (querying) data in a database
  • Storing data in a database
  • Manipulating dates
  • Loops in php
  • If statements
Creating the Table
First, obviously, we will have to create a table in our database for this you will want to log into your phpMyAdmin for your site. This information should be available from your webhost.
For this tutorial, we will only need 1 table, (see, I told you it was easy) but many apps use multiple tables.  In this table we will be storing all information associated with the guestbook.
  • Comment ID
  • Name
  • Email Address
  • Date/Time
  • Comment
phpMyAdmin makes the creation of the table easy. You may have to actually create the database in the control panel of your web host. This varies from host-to-host. If you cannot figure it out, file a ticket with your host, and they should be able to help you.
  1. Go to your database on the left by clicking on the the name. In the right panel, you will need to find a box that looks like this:
    Tutorial new table
    Enter the name of the table, we'll call it "guestbook" and for the number of fields, enter 5. (they will be the 5 from the list above). Click OK to continue.
  2. Now you will see a screen that looks like the following. Go ahead and fill out the information as seen below:
     Tutorial add fieldsMake note of the following information on the fields:
    1. comment_id is the unique id for this row. The data type is integer with a length of 11. This is usually what you'll want to do any time you're storing a number. Also note that under "extra" we set it to "auto_increment." This will mean that the field automatically adds a number to the previous row. (That makes our job easy, since we don't even have to think about figuring out what goes here).  The last thing you should note is that the "primary key" radio button is clicked. It should always be clicked on auto increment rows.
    2. name and email_address are two plain text fields that will be entered by the user of your guestbook. The 255 is how many characters max can go here.
    3. timestamp is a datetime field meaning mysql knows that whatever goes in this field will be a date and time.
    4. comment  is saved as "text" meaning it's much larger than varchar, and does not have a limit.
  3. Now click save.  That's it. Our table is made! 
Creating the php files
This is where you will need your FTP information. Make sure your IDE is all set up. For this tutorial, I will be using Komodo Edit.
If you need help setting up Komodo Edit, click here. If not, click to connect to your remote server on the left hand panel. The icon looks like a gear. If you cannot see your file system in the panel on the left hand side, or you have an error, you will need to properly configure your remote server.  If you're seeing your file system, you can continue.
  • Right click on your root directory and click "New Folder."  Call it guestbook and click "ok."
  • Now go into this folder, right click and then click "New File." Call it index.php.
  • Right click again, New File, and now call it submit.php
What did we just do here?
We just created the files that will do all of the work for our guestbook. Index is a special name for a file. Any file called "index" such as index.htm, index.php, or index.html will be the main document in that folder, and will show up by default.  Meaning that right now you should be able to go to http://yoursite.com/guestbook and it will link directly to the index.php file you just created!
So, lets go ahead and test to make sure all of that is working right.  If you go to that file right now, it should be blank. So try it, if you have no errors, lets go on.  In Komodo Edit, double click on index.php and it should open up in the left panel. Enter the following text:
<?php
echo "hello world!";
?>
Now go to the page: http://yoursite.com/guestbook. It should say "hello world!" in your browser.  This is it! your first php app!  If this didn't work, you may want to check your url, spelling, etc.  If you're seeing the brackets and the word "echo" in your browser, this means php is not enabled on your server. You will have to talk to your webhost to get this situated.
 
Creating the form
Now, delete that, since it was just a test and we don't need it and copy and paste this into your index.php. 
<form action="submit.php" method="post">
    Your Name<br>
    <input type="text" name="name"><br>
    Your Email Address<br>
    <input type="text" name="email_address"><br>
    Comment<br>
    <textarea name="comment"></textarea><br>
    <input type="submit">
</form>
This is just a rough, simple form.  It is bare-bones for instructional purposes. Remember, you can modify this any way you wish. In fact, after this tutorial, I recommend playing around with it, breaking it, fixing it, applying CSS, etc.  It's all a learning process.
 
Sending the data
So the way form data works with php is that using a form, you can pass data to another form using "GET" and "POST."  Rather than try to explain how all this crazy stuff works, I'll just show you:
Open up submit.php and paste the following.
<?php
echo "<pre>";
print_r($_POST);
?>
What I did there was use a fantastic simple little function built into php called print_r. Basically what it does is take everything in an array and display it.  It's great for displaying everything while troubleshooting.
Now go to your site http://yoursite.com/guestbook/, fill out the form and submit it.  What you're looking at is all of the values that were passed from the form on index.php to submit.php.
But what if you actually want to do stuff with the data, instead of just throwing it all up on the screen?  This is easy, too.  To access individual parts of the data, knowing that it's just an array, you can echo it, or save it, or whatever very easily.  To see how this works, replace everything in your submit.php file with this:
<?php
echo  $_POST[ ' name ' ];
?>
and then to make it even more useful, try it like this:
<?php
echo  "Your name is" . $_POST['name'];
?>
And now you know how to send data from one page to another!

 
Saving the data
Now that we know how to send the data from the form on one page to another page, we can now use that page to save everything in the database.  
To save something in the database, what we're going to do is send a command to the mySQL database, telling it to do something. Right now, we're going to pass it a bunch of values and say "put it in the guestbook table."  Our command is going to look like this: (Sample data)
INSERT INTO `guestbook` (`name`,`email_address`,`timestamp`,`comment`) VALUES ('some name','some email',NOW(),'some comment');
One thing you may want to take notice of, is "NOW()."  This is a built in mysql function that returns the current date and time. We're using it here to automatically choose the right date and time when the item is inserted.

Now that we know what command we want to send to the database, how do we send it?  Well, first you connect to the proper server, tell it which database to use, then send the command. To connect to the server and database, you will have to provide your credentials. Your username and password lets the database know that you're allowed be accessing it.  Your php code will look like this:  (the "//" means that it's a comment. Php will not try to run that code)
<?php
//connect to the database
mysql_connect("host_name", "user_name", "password") or die ('Could not connect to mySQL');
//choose the database
mysql_select_db("your_database") or die ('Could not connect to database');
?> 
Now we're connected to the database. You may want to browse to http://yoursite.com/guestbook/submit.php before continuing, to make sure you have your host, username, password, and database names correct. If these are not correct, double check all spelling and if it still doesn't work, you may want to contact your host, and they will be able to give you this information. 

After we have connected to the database, we need to send the sql command to the database.  Since this is a dynamic application, we'll have to change up that command, and format it using the variables that were passed to the page from the form, so that it inserts the users's data.  Your PHP code should look like this:
mysql_query("INSERT INTO `guestbook` (`name`,`email_address`,`timestamp`,`comment`) VALUES ('{$_POST['name']}','{$_POST['email_address']}',NOW(),'{$_POST['comment']}')") or die(mysql_error());
That's it!  Just stick that snippet of code right under the connecting commands and you're good to go.  Now you can test your app.  Go to the form, fill it out and submit it. Then go look at your table in phpMyAdmin. The data you inserted into the form should be showing up in your table.  If you're unsure where to check, there's a tab at the top called "Browse."  Click that.
Displaying the data
So now we're going to display the data.  For this, we can just put it at the bottom of your index.php file.  
First, just like the other page, we're going to have to tell your php script how to connect to the database. Put the following snippet (it's the same as the last step):
<?php
//connect to the database
mysql_connect("host_name", "user_name", "password") or die ('Could not connect to mySQL');
//choose the database
mysql_select_db("your_database") or die ('Could not connect to database');
?> 
Now we need to actually get the data from the database. For this we'll use another query, this time to "ask" the database for some information.  So before the last ?> add the following
$result = mysql_query("SELECT * FROM `guestbook` ORDER BY `timestamp` DESC") or die(mysql_error() . "

FOR:

". $query);

This is an example of a SELECT statement. This is about as simple of a statement you'll ever see.  Essentially what it does is tell the database we want to retrieve data (SELECT), where we want to retrive it from (FROM `guestbook`) how we want to display it (ORDER BY `timestamp`) and put it in reverse order, with the most recent ones first (DESC).
Now that we have the query, and we're saving the results in an array ($result), we need to loop through that array and display everything on the page:
while($row = mysql_fetch_array($result))
{
    ?>
    <p>
        <b><a href='mailto: <?= $row['email'] ?>'><?= $row['name'] ?></a></b> at <?= date('m-d-y h:i:s a', $row['timestamp']) ?><br>
        <?= $row['comment'] ?>
    </p>
    <?php
}
Now, there's a lot going on there, so I'll break it down.  What we're doing is displaying each comment, but above each comment, we're displaying the name as a link to an email, and we're putting the date and they posted. We're using php's built in date formatter to format the date so that it's easily read.  You can learn more about that here.

So that's it!  You have your first php script. Go ahead and view your index.php file, your test posts should be showing up!  Feel free to message me here if you have any questions whatsoever. I love to help! 


The Complete Odd Arnie

Sunday, November 28th, 2010

Don't tell the RIAA that I'm pirating music!!!  Anyway, by popular request, here's the entire Odd Arnie collection. 

Stating the Oddvious

[SND] Win or Lose
[SND] Butterface
[SND] M. Ono
[SND] Crying Shame
[SND] It's not that bad
[SND] One voice
[SND] Stand
[SND] I'm not the problem
[SND] Dancing in the streets
[SND] Tallest man
[SND] Night I regret
[SND] Odd Arnie

 

The Penis deMilo Sessions

[SND] Not That Bad
[SND] Not the Problem
[SND] Mono

 

Demo 

[SND] Tallest Man
[SND] The Long Goodbye
[SND] Homeless Joe
[SND] Substandard Society
[SND] Night I Regret
[SND] Mr Smarty Pants
[SND] Stand

 

 





follow brettlivaudais at http://twitter.com