Wednesday, November 4, 2009

Top 5 most common PHP blunders

PHP is a very flexible language. Flexible enough that someone with no programming experience at all can create useful programs, meanwhile appeasing the needs of the formally trained OOP programmers.

Coders from either of these two groups have certainly written code that generated an error. Sometimes I just wish that either the errors were more helpful, or simply spat out a number, so you could look it up in the "this number means this error" table.

I can see it now.. "Parse error #63" and of course referencing my list of error codes that doubles as a black light poster I see error #63 reads "you left the stupid semi-colon off the end of the line again !" Some things just never change.

Anyway, here are in my opinion the most common errors PHP coders encounter, and hopefully some hints on what might be the cause.

  • #5

    Warning: Cannot modify header information - headers already sent by (output started at ...

    If you have a PHP script that tries to use the header function, or set cookies, you might have encountered this error. It's one of the few where the error message is actually helpful. The most common cause is an extra space or line either at the top or bottom of the PHP script, outside the <?php & ?> tags. Reading the error, it actually tells what file, and where the problem was caused.



  • #4

    Parse error: syntax error, unexpected T_STRING in ...

    Probably one of the most common errors, and also the least helpful. The most likely cause is the line above the one indicated in the error message is missing the semi-colon at the end.




  • #3

    Parse error: syntax error, unexpected $end in ...

    This error can be a nightmare to correct and almost always has to do with a missing closing curly bracket } You can avoid these types of problems by formatting your code as you go, lining up the opening and closing curly brackets like this...

    if ($loggedin == 1) {
    echo 'Hello '. $username;
    } 
    else 
    {
    echo 'Hello guest';
    }
    

    You will ALWAYS have the same number of opening and closing curly brackets. Another possible cause is mismatched double and single quotes in an echo or print statment, eg; echo "Oh no another error!';




  • #2

    Parse error: syntax error, unexpected 'X', expecting ',' or ';'

    Another not entirely helpful error, but usually easily fixed. Check for attempts to print/echo strings that are not surrounded by single or double quotes, like ...
    echo Oh no another error!; This error might also be the result of a missing semi-colon at the end of the preceding line.




  • #1

    Invalid argument supplied for XYZ ....

    Certainly a candidate for least helpful, this error arises when your try to do something to an array or object that doesn't exist. The actual cause can vary from simple typoes to a failure to create and populate the array/object.



Friday, October 9, 2009

Some helpful mod rewrite rules to improve SEO.

If you are new to creating websites, or just want add some new tricks to your existing skill set, getting a grasp on mod rewrite is a pretty good way to improve your website, both in terms of usiblity (for people) and improving search engine rankings (for bots).

Getting started, the .htaccess file


htacess is feature of Apache web server. If set up correctly, it gives the website owner a way to pass configuration changes and tweaks to the Apache web server, affecting how their website behaves.

Apache is typically installed with modules, one of those modules is called mod rewrite, and with it, you can essentially tell Apache what to do, and how to respond to nearly any type of website request.

Check your website for any .htacess files you might have. Keep in mind, Apache directives inside a .htaccess file affect all directories beneath it, so if you have existing .htaccess files, you can usually just add to them.

So either edit or create a .htaccess file with any text editor such as notepad.


Handy .htaccess entries


Customized error pages
Let's face it sometimes things just don't go as planned, but your website can recover from it gracefully with custom error pages.

So, writing a single error page in HTML, including links to the site sitemap.xml, and other sections of the site, a search form if applicable, as well as a javascript redirect to the site's main page. So if a person encounters an error, they will
be steered in the right direction. You can use a single .html file to respond to numerous error types.

Using an error page named 404.html to respond to 404 (not found) and 500 (internal) errors, add this to your .htaccess file

ErrorDocument 500 http://www.superdupersite.com/404.html
ErrorDocument 404 http://www.superdupersite.com/404.html


Blocking website access by IP address.

Deny from 127.0.0.0


Firing up mod rewrite . .


In order to make sense of mod rewrite directives, you need to tell Apache to access the mod_rewrite module.

Adding a line that reads . . .

RewriteEngine on
does exactly that.

Next, need to tell mod rewrite which directory to act upon, if this .htaccess file resides in your main web directory, you probably want . .

RewriteBase /


If the .htaccess file is in some sub directory of your website, you probably want ..

RewriteBase directoryname/


Handy mod rewrite rules


After enabling and setting the base directory, you can start adding mod rewrite rules. One I always include is what I call the the non WWW to WWW rule, basically force the browser or search engine spider to use www in the URLs of the site. If they browse to any pages without WWW, they are 301 redirected.


RewriteCond %{HTTP_HOST} ^superdupersite\.com(.*)
RewriteRule (.*) http://www.superdupersite.com/$1 [R=301,L]


Prettier URLS


If you are using PHP, or really any other web development language, you can take parameters from ugly URLs and make them pretty.

The example below will serve index.php?author=Smith when /author-Smith.html is requested.

RewriteRule ^author-(.*)\.html$ index.php?author=$1 [R=301,L]


Likewise this rule serves index.php?book=Diary when /book-Diary.html is requested.

RewriteRule ^book-(.*)$ index.php?book=$1 [R=301,L]


Passing multiple paremters



Finally you could get book and author in one request like this..

index.php?author=Smith&book=Diary when /author-Smith-book-Diary.html


RewriteRule ^author-(.*)-book-(.*)$ index.php?author=$1&book=$2 [R=301,L]

The $1 represents characters in the first parentheiss (.*) the $2 represents the 2nd one and so on.

Regular expressions


If you have created something like the above mod rewrite rules, congratuations, you have used regular expressions since they were used. ^book=(.*)$

Regular expressions can get tricky but the vasics are ..

^ [caret] Means the beginning of a line, so ^G would match any line with a capital g as their first character.

$ [dollar] Means the end of a line , so G$ would match any line ending with a capitol g.

. [period] Means any single character, including space,

* [asterisk] Mean continually match on previous rule.. more on this later

Ranges . You can specify a range of characters to match on with square bracket []
Match any single digit number ..
[0-9]

Match any single lowercase letter
[a-z]

Match any single uppercase letter
[A-Z]

Match any letter, regardless of case
[A-Za-z]

Match any alphanumeric character
[A-Za-z0-9]

Remember the period and asterisk earlier? Combing examples above, you could do..

Any 2 digit number
[0-9].

Any number, regardless of lenghth
[0-9]*

And same for letters

Any 2 letters
[A-Za-z].

Any letter combination, regardless of lenghth.
[A-Za-z]*

Using just the period and asterisk means ALL characters, so
.* would match an entire line.

A.*Z would match all characters between capital a and z

Remember when a regular expression rule is wrapped with parenthesis, like this .. ^book=(.*)$ it becomes available to the destination URL as $1, $2 etc.

There are far more complex ways to use mod rewrite, as well as .htaccess but hopefully this has gotten you off to a good start.

Wednesday, September 30, 2009

Proxies PHP and XML OH MY

I like PHP. I like XML, but like anything, it sometimes just flat out pisses me off. Such was the case when a host I had been gleefully fetching an RSS feed from decided they needed to move their website to a host that provides DDOS detection and protection.

The happy little code snippet below, that had been chugging along for almost a year, and continued to work on other hosts suddenly broke...

$rssfeedurl = http://www.somdomain.com/somerss.xml

if (!$xmlDoc = new DOMDocument()){
echo 'Could not initiate feed '.$rssfeedurl ;
}

if (!@$xmlDoc->load($rssfeedurl)){
echo 'Could not fetch or translate '.$rssfeedurl.' into XML';
} else {
// PARSE AWAY ! ! ! !
//get elements from ""
$channel = $xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = @$channel->getElementsByTagName('title') ->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link') ->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description') ->item(0)->childNodes->item(0)->nodeValue;
}


After beating my head against my already battered desk for far too long, I asked the owners of the domain, what up?

They in turn conveyed my question to their new hosting company who promptly responded with "The HTTP request header is invalid" and hinted that their external proxy couldn't forward such a request to the targeted server..

So, I tried using stream_context_create() and libxml_set_streams_context() to create valid HTTP request headers, and it seemed to work....


$opts = array(
'http' => array(
'user_agent' => 'xml fetcher 1.0',
)
);

$context = stream_context_create($opts);
libxml_set_streams_context($context);
if (!@$xmlDoc->load($rssfeedurl)){
echo 'Could not fetch or translate '.$rssfeedurl.' into XML';
} else {
// PARSE AWAY ! ! ! !


I finally gave up on using it though because I was still getting intermittent failures, likely because creating a fully valid HTTP request header is trickier than I thought... So I switched to CURL, and Eureka ! CURLOPT_HTTPPROXYTUNNEL to the rescue!

Why didn't I try this before? If you have done a Google search on "PHP CURL proxy" you will find tons of info on posting through a local or intermediary proxy. But I could find almost nothing on dealing with the nuances of a remote proxy directly in front of the target server, and besides $xmlDoc->load($rssfeedurl) is just so damn elegant...

After some trial and error, I came up with this.

$cookie="./.cookiefile";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $rssfeedurl);
curl_setopt($ch, CURLOPT_HTTP_VERSION, 1.0); // 1.1 likely works as well, but 1.0 seems fine
curl_setopt($ch, CURLOPT_HEADER, 0); // Dont want response headers
curl_setopt($ch, CURLOPT_REFERER, 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']);
curl_setopt($ch, CURLOPT_USERAGENT, 'Dew-Code XML Grabber 1.0');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); // to handle redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // assign response to a variable
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie); // .cookiefile is just an empty file, just in case
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); // ditto
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // seconds to wait for response
curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // in case of redirect, convey referrer
curl_setopt($ch, CURLOPT_MAXREDIRS, 5); // how many times to allow redirect
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); // absolute must when a proxy is involved
$rssblob = curl_exec($ch); // make it go!!

if (curl_errno($ch)) {
echo curl_error($ch); // handy for debuging
} else {
curl_close($ch); // Save the binviroment! clean up after yourself
}

if (!@$xmlDoc->loadXML($rssblob)){
echo 'Could not fetch or translate '.$rssfeedurl.' into XML';
} else {
// PARSE AWAY ! ! ! !


I hope you find it useful..

Tuesday, September 15, 2009

Tiny little trickling income streams

I know a lot of website owners that spend their time and money making their site as good as it can be. For them it's not about making a buck, it's about giving back, which is of course a good thing.. but, there is certainly nothing wrong
with supplementing your income so that at the end of the month you are at least covering the costs of hosting your website, and if you come out ahead, well that's even better.

So here I will cover some of the ways you can get your website earning a bit of income. Depending on how much traffic your site gets, you aren't likely to be retiring early from the money you make, but you should be able to at least cover your monthly web hosting costs.

Google Adsense :
Adsense is probably the most widespread and popular way to monetize a website. After signing up you can create banner ads as well as text link blocks to spread around your site. Further you can customize the colors and even fonts they use. Which colors work best on your website is a hot topic for debate, so I suggest creating 2 custom pallets that blend well with your site's colors, then set all your banner ads to cycle through up to four random pallets, selecting your 2, and either 2 stock pallets or your own that contrast your site's color scheme.

Google will cycle through the color pallets available, and eventually start favoring the one that results in the highest click through rate.

You can also limit banner ads to images only, text only, or both. I suggest both, again, Google will start favoring the format that provides you the best potential earning.

You can have up to 3 banner ads, and up to 3 text link units on each page, but more isn't always better. And of course where your adsesne code is placed on your web pages can have quite an effect on their performance. Often a square banner ad wrapped by your site's content, like the one shown on this page will outperform the typical banner in the header and footer. Likewise, text link units often perform well when directly below your site's main content.

Either way, make a habit of doing a monthly tweak, change one thing, placement, format, color etc. and let it run for a month before deciding whether you have increased or decreased your site's revenue.


Chitika :

Chitika's Premium Ad units is one of the few website ad services that can be used in conjunction with Google Adsense.

After adding the Premium Ad code to your website, only visitors that were referred to your site through a major search engine will see the ad. So your regular viewers, who get to your site through a bookmark, or other link won't see the Chitika ads.

Like Adsense, placement and color choices can affect your revenue, so yet again, make a monthly tweak, and review the performance.



Text-Link-Ads :

Once your site has been around for a while and has a decent and steady stream of traffic you can sell static links to other sites at rates you determine. TextLinkAds will estimate what they think a link on your site should sell for and once you have sold a link placement, they split the income from it 50/50 which may not sound like such a great deal, but when you consider they handle everything, leaving you to continue work on your website, it works our pretty well.



There are of course numerous other ways to monetize a website and I've only touched on a few here which I have had experience with. I'm curious what visitors might have to say about these, or other methods of site monetization , so let the comments fly!

Wednesday, August 12, 2009

Best freelance site

I've been a freelancer for a few years now, using various websites to help me to find work, and after using them for a year or more, I've come to a firm decision one is just better than the others.

Granted, I haven't tried every freelance site out there, after checking out several, I found I could get ample work by checking out these 4 every day.

Also, I should point out, Freelancing isn't just for ubergeek programmers. If you can type, you can freelance, since there are always jobs for article writers, product reviews, really anyone can freelance.

So, the top 4 I've used...

LimeExchange :
Pros Pretty interface, frequently added projects with a variety of platforms and programming languages.
Cons A lot, and I mean A LOT of form filling out in order to be able to bid on projects. Granted once you are done filling out the profile, you wont have to do it again, but just to be able to bid on a $10 project, it is extreme overkill.

GetAFreelancer:
Pros Large selection of projects
Cons Unless you spend money to upgrade your account, you are limited to 10 types of projects you can bid on. Example, if you haven't checked off "logo design" in your profile, you can go to the trouble creating a mockup, write up your proposal, and click the Bid now button only to find you've wasted your time, since they'll never see your mockup or proposal.

RentACoder
Pros Large selection of projects on diverse platforms and languages.
Cons Somewhat unintuitive interface, but by far the biggest con is it promotes racism.. Project creators can set their project so that only persons from certain countries can bid on them. Sure, your language ability should be a consideration when choosing a programmer, but excluding persons from bidding just because of what country they come from is just flat out wrong.

Scriptlance
Pros Large selection of freelance projects on diverse platforms and languages. Escrow system to ensure the project creator does indeed have the funds to pay you. Free withdrawal to your Paypal account once you've made over $30. Allows you to create separate programmer's account and a buyer's account so you can outsource portions of larger projects you've won.

Cons 5% or $5 of your earnings paid to Scriptlance per bid won (although other sites mentioned above charge the same or more) . No easy way to transfer funds from your programmer account, to buyer account, or vice versa, although their tech support can do this for you pretty quickly after you contact them.

And in order of best to worst, here they are.
  1. Scriptlance
  2. RentAcoder
  3. GetAFreelancer
  4. LimeExchange

And there you have it. If you are considering becoming a freelancer, or just wanna make a few quick bucks, I highly recommend ScriptLance.

ps, yes those are affiliate links, and after you create your account(s) you can make your own and earn even more.

Tuesday, August 11, 2009

The magical mythical world of SEO

Anybody with a website has no doubt heard the term SEO, Search Engine Optimization. In fact it is a billion dollar industry. Everyone seems to think there is some magic bullet that will miraculously rocket their web site to the top of the SERPs , that's short for Search Engine Result Pages by the way.

Well the truth is, there simply isn't such a thing and anyone that tells you otherwise is either trying to deceive you, or is simply not very bright. I often do SEO work for clients, but the bulk of my work is mostly undoing the damage that occurs when overzealous webmasters cross the line and are penalized for attempting to manipulate search engines. They are usually oblivious to the fact that they have shot themselves in the foot, so much of my time is spent explaining what I'm explaining here.

In short, SEO is not about knowing what to do, it's about knowing what not to do. Tactics like creating mirror sites to funnel page rank to your primary site are quickly discovered for what they are, attempts to manipulate search engines. If you are lucky those mirror sites will simply be disregarded. If you are not so lucky, your primary site will be penalized, or possibly completely removed from the search engine's index.

Keyword density is another one of the many apples "search engine experts" hold in front of web site owners to entice them out of their money. Suggesting there is some magic number that will take their site to the top... that number is of course 2.83881% .. Joking, there is no such thing.

Instead, here is what I suggest. Open up note pad. Enter your sites title, your meta keyword and description tags, and finally the copied text from your main index.

Now read it as if you've never read it before. Read it out loud. If it reads like poorly translated Japanese, then you have a problem and should rewrite it. If your dog or cat's head tilts in that "what the hell are you saying" way, you should rewrite it. While doing so keep the following in mind.
  1. Your website is for people not search engine bots.
  2. Googlebot will not laugh at your jokes or buy your products.
  3. If you discuss a topic in depth, your keywords and their variations will occur naturally.
There, thats simple right? Now read your new copy 5 times. Better ? Good!

That is not to say you should not be aware of your keyword density, just don't obsess over it. To make sure you haven't gone overboard (which is prone to get your site penalized) check out this tool http://www.keyworddensity.com

Entering your top competitors URL, your own and your primary keyword phrase, you can see if you have gone overboard. Your goal here is not to one up the competition, just to ensure you are in the ball park, within a few percent of the competition. Again there is no magic number, but there is a number that will get your site penalized, so a bit lower than your competition is probably a good idea.

Once your on site work is done, it is time to get relevant and quality back links to your site.. something I dread because it is time consuming and does not provide immediately noticeable results.

Again the same rules apply. Your website is for people. So provide them with content and resources they can actually benefit from, whether it's a funny video or an article on potty training gerbils, write for people, not search engines and you'll do well.

Websites with Flash intros, things that make you go BLEH!

As is hopefully apparent by now, I'm a freelance coder, eeking out an existence coding websites, writing niche applications, usually in PHP. Occasionally I'll run across a project where I am creating a web sites from the ground up, instead of extending/tweaking an existing site.

When I get such a project, I find I am quite apprehensive to the response I get when I request a complete feature list.. there is much pacing, biting of nails and overall nervousness as I refresh the contents of my inbox, and damn, there it is.. They want a Flash intro... BLEH !!!

Now of course everyone is entitled to an opinion. If you think Flash intros are cool and actually watch them when you see one, instead of immediately clicking the "skip" link, then hey, more power to you, but you are in the minority. The majority of people click the skip link within nano seconds, and if they can't easily find it, they will hit the back button rather than wait for your flashy intro to complete. Likely giving you the exact opposite to the reaction you were hoping for..

From a technical, SEO and good ol' experience perspective, a Flash intro, even one with a prominently displayed skip link really hinders your site's ability to be suggested as a search result and often actually deters visitors from returning once they have discovered your site.

Presumably you want as many people as possible to sign up for the mailing list, buy your products & services and partake in the activities your site promotes. That means getting web traffic, which in turn means providing copious amounts of relevant text on the most important page of your site to search engines, so that they can determine what the site is about and categorize it, then suggest it where applicable.

On a new site especially, with few or no links pointing to it, it will be some time before search engines start suggesting your site in search results. You need to make the site's content as easily
accessible to both humans and search engine spiders, and frankly, Flash intros hinder both, not to mention they make the majority of your visitors go BLEH and/or go away.

Sunday, August 9, 2009

I'm a grumpy old man.

I'm really not sure when it started, but just yesterday I was thoroughly convinced. I now inhabit the body of a grumpy old man. I've always thought myself to be a pretty optimistic. open minded and accepting person. That's all gone now.

I know I was over the edge when I heard about a Chinese bride wearing a wedding gown that measured 1.25 miles long, apparently in an attempt to get into Guinness book of world records.

My initial reactions follow, although to my credit, some were only mental, not actually verbalized. I've indicated my verbal remakes with *

OMFG What a waste of resources!!! What a selfish egotistical couple !
*MY GOD THAT MAKES HER BUTT LOOK HUMONGOUS.* That thing could clothe a couple dozen African villages.

Those Chinese, population is so dense everyone feels like a Lego block. They'll do anything to feel like an individual, poor people. I wonder what the husband does? Maybe he makes fireworks for a living? OMFG what a waste of resources. All that work and material for a second of eye candy on 4th July for the good ol' US of A.
What a selfish country! With their Hummers and RVs blowing off fireworks at the drop of a hat, consuming 80% of the world resources.. Argh I got a headache !

*AT LEAST SHE LOOK GOOD IN WHITE*

And there you have it. I've accepted my plight. Dusted off the old rocker and fashioned a cane from a broken tree branch. Tomorrow I'll be shopping at Goodwill for polyester pants that come up past my belly button and a goofy hat.

You damn youngsters! Get off my lawn !!!.. Oh wait, I live in an apartment, I don't have a lawn.

Friday, August 7, 2009

Don't with the DOS dweebs!

You may have heard, a few sites were reportedly the target of a distributed denial of service attack. This sort of thing happens every day. The only thing that sets this recent situation apart are the victims. 3 of some of the most visited sites on the net.

Google, Facebook and Twitter were all bombarded with data requests, likely from a bot net orchestrated by one or more acne faced dweebs who's sole source of ego reassurance is digitally intimidating people.

To them I say KNOCK IT OFF! Put your knowledge to better use, or at least go play GTA or something. The DDOS on these sites served no purpose at all. You gained nothing from the act other than a fleeting and false sense of digital superiority. You are still a dweeb and as long as you anonymously menace people, you always will be. So go find that bully that bruised your self esteem so badly and tell him what you think. Stand up to him, vent your frustrations at him.. Not absolute strangers that have nothing to do with your problem.

There, I feel better now.

Sunday, August 2, 2009

To all SEO professionals. INCOMING ! ! ! !

Maybe you've been using Google for more than a search engine for these past several years. If you are a website owner, or an SEO consultant, it's pretty likely you also use Google to measure a website's prominence, to act as a benchmark on the pecking order against the competition.

Well, the rules and standards that determine that pecking order will be changing... Actually it is always changing, but for the first time in several years, a change is coming that could have more than a subtle effect on the mighty Google SERPs (search engine result pages). Whether it will affect your website(s) or not is yet to be seen.

Google has been working on something they call Caffeine, and unlike Microsoft's caterpillar to butterfly transformation that resulted in Bing, Caffeine won't likely result in an obvious change to the Google interface we all know and love, instead, the changes are under the hood, so to speak.

In short, it's faster. In some of my tests up to %50 faster.. WHOA!!! %50 faster? Yes %50 faster, which raises the question, how did they make such a dramatic performance increase without simplifying the pecking order rules. Has the mighty Google algorithm been whittled down to bare essentials? Since I'm not a Google engineer, I can't say, but on the other hand, if I were a Google engineer, and told you, I'd have to kill you.

So what does this mean to you? Well, it may have absolutely no impact on your website's position in SERPs, but some may be affected, and I'm guessing, that change would be more than the occasional small 1-2 spot variation we all see from time to time. So, I can only suggest, we all duck and cover. That is to say, avoid any drastic SEO related tweaks until you know how your website is affected.

You can get a sneak peek, but please be aware, Caffeine is still under the knife, and could be further adjusted, so I suggest simply monitoring, not reacting, until Caffeine has been finalized.

Wednesday, July 22, 2009

When PHP stands for Possibly Hopless Progam

So, here I am, almost broke. Drank my last pot of coffee, down to 6 cigarettes and I get this seemingly simple gig to fix some XML fetch parse present script. Woot I can do that for like $20 USD .. ( I found if I don't specify USD I'm likely to be paid in pesos, rubles or some other currency, exchange rates rarely work to my favor)

Anyways.. It looked like a pretty well written script, using PHP's DOMDocument support, which I've used on some of my own scripts. The crux of the script was...


$rssfeedurl = 'http://someXMLurl';

if (!$xmlDoc = new DOMDocument()){
echo 'Could not initiate feed '.$rssfeedurl ; exit();
}

if (!$xmlDoc->load($rssfeedurl)){
echo 'Could not fetch feed '.$rssfeedurl ; exit();
} else {
$channel = $xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = @$channel->getElementsByTagName('title') ->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link') ->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description') ->item(0)->childNodes->item(0)->nodeValue;

//etc etc . . . .
}

Of course the script ran for months just fine, then suddenly stopped for no apparent reason. Turns out it was getting a 403 forbidden response.. but the IP was not blocked by the host serving the XML.. actually they couldn't figure it out either.

I tested every conceivable cause I could think of. Shelling into the server, I could wget the XML just fine.. So I wrote a quick PHP script, using curl to fetch the feed, thinking it's gotta be the user agent they are blocking...

I tried all sort of different user agent names, even some real nasty ones that any network would ban on sight. All were allowed to fetch the feed.

Then I accidentally fired the script off with no user agent set. WHOOP THERE IT IS.. 403 forbidden.. BINGO. They reject requests with no user agent set.. but how the hell do you set an agent name for DOMDocument::load ?

Luckily I found the answer. The trick is adding a few lines before you initialize DOMDocument


$opts = array(
'http' => array(
'user_agent' => 'xml fetcher 1.0',
)
);

$context = stream_context_create($opts);
libxml_set_streams_context($context);



if (!$xmlDoc = new DOMDocument()){
echo 'Could not initiate feed '.$rssfeedurl ;
}




So.. now I got $20 USD YAY! A pound of coffee, maybe some top ramen and a pack of smokes!! NEXT !

PS. if you wre actually curious what PHP stand for, it's PHP: Hypertext Preprocessor so. in essence the first P stand for nothing, it is just there to create a cooler sounding 3 letter acronym, and beside HP was taken.

Thursday, July 9, 2009

My 401k is now 404

Well, so much for retiring any time soon. Granted, in another 10 years or so, my 401k will almost certainly regain what it has lost in recent years, but any hopes of an early retirement have been dashed on the jagged rocks below.


I still think having a 401k is a good idea, and strongly suggest anyone with a full time job start one, and divert as much as your income to it as you can. If you start one at age 18, and put as little as 2% into it, you can pretty much assure a comfortable retirement.


There are a couple of strings attached, like early withdrawal penalties, so take my advice, don’t treat a 401k as a savings account. Use a regular bank for that. Only a percentage of “disposable” income should be put into a 401k


For those like me, that started their 401s later in life, you’ll need to invest a larger percentage, as close to the non-taxable max as you can, which is typically %15, but can vary based on your income.


The real beauty of a 401k is the income you put into it is not taxed, and you only pay taxes on your income after the 401 deposit has been subtracted. It’s like you are being paid to save money.


Add to that, the money you’ve invested in your 401k, is exactly that, an investment which can gain or lose money depending on the stock market. Whether you cash out at a profit or a loss is just a matter of timing.

Wednesday, July 8, 2009

When will a penny be worth something?

For a long time now, I’ve been a vocal advocate for the abolishment of the penny, but the US mint continues making them, despite the fact that they cost more to make than they are worth. Perhaps they have considered something I haven’t?


Coins throughout history have been made of precious and semi-precious metals, because there is actual value in gold, silver, nickel and copper. Take the silver dollar, or the $20 gold piece for example. Just like the penny, they were made of metals that actually had value, namely gold and silver. but not any more.



Today’s penny only contains roughly 2% copper, the rest is a zinc based alloy, but even still, the alloy in a present day penny is worth more than the penny itself. Add to that the costs of labor and machinery it takes to make a penny, you wind up with each penny costing around 1.3 cents to make.



Back in the day, gold and silver coins were quickly discontinued when the metals used to make them cost more than the coin was worth, so why not the penny ? What does the government know that I don’t? Are they hoping the value of the dollar will drop so low that manufacturers and retailers will lower their costs? Do they plan to start lowering federal and state mandated minimum wages?