Simply Breath Teching…

Resources for PHP Programmers and Small Business Operators

Firefox Losing Session Variables on Redirect

So I’ve been attempting to deal with an issue on a CMS I made for quite sometime. When People logged into the CMS they would be redirected to the Homepage from the Login page. They would get a first glimpse of the homepage then once they clicked a link they would be redirected back to the login page as the SESSION variables would disappear.

The problem was firefox feels that http://www.mysite.com is a totally separate site to http://mysite.com so it resets the SESSION variables.

I changed my links which i had prepended the domain to for some unknown reason (I’m sure there was a logical reason when i wrote it), so I changed it to /pageNames.html and all was well in the world again.

While researching this bug I found some other solutions

  • Call session_write_close() before using a header redirect in PHP
  • The worst possible solution would be to pass the SESSION Id (SID) in the url (not recommended) but nevertheless if worse comes to worse it is a solution.

Hope this helps someone. Until next bug.. keep up the good work.

Bookmark and Share

Function for dealing with quotes in input fields in HTML/PHP

Anyone who has coded html has come across this issue, you have an input field in your form but oh no! someone has entered a single or double quote into the value and they are now trying to edit it, and all you see in the input box is John\ instead of John\’s. It is one of those reoccuring issues which I face from time to time, but not anymore.

Every now and then i stumble across a new issue which my current method doesn’t solve. Talk about frustration, going through old code just to make sure you aren’t using that incorrect method. Heres something I whipped up tonight which I thought I should post asap.

function form_encode($string)
{
/*make sure you remove the spaces in the first variable of the str_replace function, Word press doesn't seem to like to print out the htmlentity of the ampersand which is understandable*/
return str_replace("& amp ;", "&", (htmlentities(stripslashes($string), ENT_QUOTES)));
}
I’m pleased with this solution, i’m hoping it’s not too computational intensive as it uses str_replace only once.

This function is especially effective when the data is being pulled from a database, but i found i needed a solution that can not only use data from a database and encode it properly but also if you are reusing $_POST variables, my forms if they fail reuse the same values, and i was getting alot of “John\ ” errors but using the stripslashes then the htmlentities fixed it up really nice.

The reason for the str_replace is the htmlentities function will change the ampersand at the start of some special characters into the htmlentity & amp ; which is what the function is supposed to do.. funny that. But a simple str_replace returns any double encoded htmlentites back into their original format, which means perfect display for us and easier forms from now on.

This has been tested on Firefox for Mac, Safara (Mac), will test on PC later. Thought I’d get this up asap for everyone. Will be interested to see if anyone finds it though.

Bookmark and Share

FireFox Caches Images When It Shouldn’t

I’ve recently come across a small annoyance in the firefox browser. I was creating a website that allows you to modify images so they can be printed. I had a caching issue when users would press back then change a setting and go forward again. A refresh would fix the issue. So FireFox was using the cache when I didn’t want to.

As usual first attempt was use some php code to specifiy the caching paramaters.

header(‘expires: Mon, 26 Jul 1997 05:00:00 GMT’);
header(‘cache-control: no-store, no-cache, must-revalidate’);
header(‘cache-control: post-check=0, pre-check=0′, FALSE);
header(‘pragma: no-cache’);

But to no avail, although IE responds extremely well Firefox didn’t. But i found that if the filename is the same as something in cache FireFox looks at the binary code and determines if anything has changed if it has it will reload the same image changing the cache.

This leads me to the solution, if you are writing PHP code then simply add this line to the end of the source attribute
<img src="image.jpg?t=<?php echo uniqid();?>" />

You can also achieve a similar process using javascript by utilising Math.rand() .

This tells firefox that the image is different when in reality it isn’t.

Remember Image Caching is a good thing except in instances such as this. Don’t restrict caching too much or you will find your bandwidth usage could jump quite a bit.

Bookmark and Share

FireFox and IE Ignore Hosts File

Thought i’d share this with everyone, I recently ran into some trouble on my machine where my browsers began ignoring my Hosts file. After much annoying testing and what not I eventually found that the reason they were ignoring my hosts file was because it was going through a proxy.

I’ve never set a proxy up on my computer, but recently I installed Google Web Accelerator. Bingo they set up a proxy to speed up the sites you view.

So uninstall that if you have it and Bob’s your uncle. A normal Add/Remove Programs on XP does the trick.

If it doesn’t help check if you are using a proxy to connect, if not check your spelling in your hosts file.

Bookmark and Share

Debugging Solutions – A Framework

Recently i’ve been running into numerous bugs occurring in my code, it mostly stems from the fact I am working with another companies poorly written code, planning on helping them out I decided to accept the job without a proper look at their current code, and database structure. Note To Self – Don’t ever accept a job that you don’t see first or create yourself.

Anyway, bugs galore is something that I’ve had to deal with. So I assumed other people would probably be in the same dilemma at some point in the programming lives where they had run out of ways to debug. So I am attempting to write a debuggers framework, particularly for dealing with code from other people. Although this list will apply to any code, your own, others, or a mixture.

Step 1 – Find the bug. This is normally the easiest step :P . Many times someone else will do this for you. Take note of the location of the bug, any error messages it emits, and the variables in the URL. If an error is generated then you have struck a gold mine, this is normally due to a syntax error somewhere in the code, take note of any line numbers that it has given you and continue.

Step 2 – Open up the code and peruse the file. If the file you are working on calls on a number of other pages, or functions from other files open those up as well. As you are perusing look out for the obvious errors, if you have an error code or a line number in which the error has occured check that this line and the line before and after it are syntactically correct.

Step 3 – Still no Luck? Check the logic. Logic errors account for most of my errors especially when dealing with date data types, the way my brain thought about the scenario was backwards or somethign unexpected came through. Check that they are correct do some simple scenarios in your head. If this doesn’t solve the problem, change any changes make to the original.

Step 4 – Google. Need I say more, not really but a couple of tips won’t go astray.

  • Search Terms – Type in the box what you would say if you were asking a fellow programmer. My website is generating broken images when I do such and such. Still no luck be less specific – Images are broken when my page loads.
  • Google Groups. Sometimes a quick search of google groups can give immediate results. Sometimes not.

Step 5 – Take a break – take a 10 – 20 minute break, if you have been working on the bug for more then an hour. Play a game of solitaire or minesweeper to relieve some stress, go get a cup of tea/coffee. Whatever it takes to get your mind off the problem. Dwelling on something is normally the worst scenario to be in.

Step 6 – Feel better? Not for long… If you are at this point and it still needs to be fixed urgently then its time for some commenting of someone elses code, not the best scenario but a very good one.

  • Write your own output function for debugging – See my post on – Spitting – Soothes the Soul and Eases the mind.
  • Use html comments to output some code in the background, this is especially important when you are fixing bugs on a live site. People are unaware anything has changed, but you can continue to debug freely. Well not as free as you would like but fairly unrestricted. If you have a Sandbox type area then use that and only upload changes when you have fixed it.
  • If you aren’t on a live server. You got it made – Die Statements to infinite and beyond. If you are debugging javascript Alert statements are your friend. Before each die statement place a print_r($_GLOBALS) or whichever custom function you made see Spitting Link two points up ^

Step 7 – This is never a good step to be at. Now is about the 2 – 5 hour mark. You are more then likely grumpy, irritated, snappying and any and every living thing and even some inanimate objects. But there is light at the end of the tunnel. Step 8 is go to sleep. But first you should find an appropriate forum that posts similar problems to what you are having. Try to find one that is still active. Put a few posts up on a number of forums then go to Step 8.

Step 8 – Sleep on it. You might toss and turn for 30 minutes while you attempt to break your brains vice like grip on the problem, but now is your subconscious’s time to shine. Ever noticed that your thoughts are clearer in the morning, or you have a solution to the problem you’d been having about how you would begin a project. Daybreak comes, you stir from your slumber, roll out of bed (insert personal wake up routine here), *Ding* Lightbulb, thats an idea! Run frantically to the computer or to a pen and paper and jot down any partial, possible, probable, plausible, portable, pottable, porsche (too many p words) solution that you think up. Driving to work and think up one, use your phone, most phones these days will have some sort of voice recording (not advising using your phone while driving – many phones with recorders have a quick use button.), or pull over and write it down. Forgetting it would be terrible at this point.

Step 9 – Try some of your ideas (if any).

Step 10 – Check your forum posts, any hits, and views, most of all any Replies???? If there are go check them out. If not start again from Step 2.

I know the feeling of desperation when it comes to debugging, mood swings, cussing (worse then a sailor, and if you are navy computer programmer, dear baron that would be some colourful language), all the side effects of a nagging coding issue.

Usually many people will solve their problems by Step 3 – 4. Simply stepping through the code in a calm manner can often prove to be the best approach. Try not to get too rialled up, it’s only code. :>

Bookmark and Share

Forms submitting twice in Firefox

Recently I uncovered an extremely annoying and difficult to find bug in a website I’ve been modifying a client. There are two things I dislike, the first being debugging code where there exists some obscure error, the second and the one I dislike the most is debugging someone else’s code where there exists some obscure error.

Poorly written, poorly commented (something I also do but should improve), poorly formatted, and all round poorly done, is is the state of the code I was faced with. The predicament you might ask or yell! I was adding an item to a shopping cart, but in FireFox it was being added twice, where as in IE 7 only once, so begins the bane of my existance (for the day).

Now first things first, check the SQL… “nup that’s perfect”, ok send me an email every time something gets added to the database. Received 2 emails. ….*Pulls some hair out*. Digging into my repertoire, I began utilising all my knowledge of debugging, in between extracting more chunks of hair from any place I could find, (at this stage there isn’t much left but on the bright side I have a nice Brazilian, and I could be in the Olympics in swimming.)

Then comes Google, the saviour of many, the enemy of few (except yahoo, ninemsn, hotbot, altavista, etc). Enter Search Terms : Form Submitting Twice in FireFox. Results – a Plethora of semi useful information.

From the rubble a solution was found – from Sparhawk – to sum up his post, any element in your html that contains an empty src attribute will, in FireFox, invoke a call to the same page. In IE it invokes a call to the current working directory.

Elements that generally have a src attribute are external cs, javascript scripts, and by far the most common, images. I’m yet to find the empty src attribute (as I didn’t write the code, the main file of the website is >250kb, about 8 pages are included every page load, and I found a better solution – keep reading) but sometimes the removal of it is not needed, simply this, if you are getting duplicate entries into the database, change the form type to a POST instead of a GET. Simply the image loads the same page but with no variables, most form submit page checks that the submit button variable exists, if not it won’t continue to run. If you are getting duplicate entries and are still unsure about whether the entry is being added by your sql command, append the date (something that shows what second it is) to a title, many of my duplicate entries were at elast 2 – 4 seconds apart.

For optimal performance it would be better to remove the empty src if it can be found. I hope this helps someone as i spent easily 3 – 5 hours trying to get it to work, when all I needed to do was replace the POS in POST with GE. The slowest typist could achieve this in far less time then I took to debug. :(

Nuff Said. Comment if it helped you.

Bookmark and Share

4 Tips for Working from Home Successfully

Started your own home business? Telecommuting for the first time? Here are a few tips to help you maximize your time and more importantly your efficiency.

Tip 1

Work area – Your work area is your first port of call when attempting to change your work habits for the better. This area needs to be clean and organized, make sure you have a desk with drawers or somewhere you can put things that aren’t being used so they are out of the way. Many people who work at a computer need simply a pen and paper, for making notes about phone calls, or jotting down reminders if you don’t put them all on the computer. A clean work space helps stop your mind from becoming cluttered.

The location of the work area is just as important as the state of it. If possible make sure your desk isn’t in front of a window, as the backlight from the window can become very distracting causing you to lose focus on the current task more often. Try to have the desk so you can turn to your left or right and see the window, the natural light helps keep you awake and alert.
Tip 2

Distractions – This is the biggest timewaster in any office environment. It is also one of the hardest to eradicate and these tips won’t solve all your problems. Think about what distracts you in your current work area, here’s a list of a few you might come up with.

  • TV
  • Radio
  • Music
  • Phone Calls
  • Emails
  • Visitors
  • Shiny Metal Objects

Each of these distractions can be eliminated or controlled, with exception of the last one if you run a scrap metal yard.

It’s obvious how to eliminate TV, Music, Visitors from your workplace, but controlling emails and phone calls are another matter. Many businesses rely on phone calls and emails for generating income or maintaining contact with current or future clients.

A few guidelines for gaining control:

  • Give yourself set times to check emails. Stopping your current task responding to an email and returning to that task is very detrimental. If you are at the computer all day disable the automatic alerts and sounds that signify you have received an email. As the old saying goes out of sight out of mind.
  • Answer calls at certain periods of the day, you may need to have a number of times during the day depending on the volume of calls you receive. Let any calls that fall outside these selected periods go straight to your phone message service. Make calls and respond to calls during the times you have selected during the day.
  • Try to set these periods towards the end of the day as people work better for the first 3 – 5 hours of the day. Tap into this fact; schedule the tasks that require more brainpower during the earlier parts of the day. I for example am a website developer so I try to schedule my new programming projects at the start of the day, and do my maintenance and client relations towards the end of the day to help keep myself focused.

Tip 3

Work Faster – Sounds like something your boss might say (if you have one that is). Everyone can work faster they just need to find what motivates them.

If you are a goal orientated person:

  • Set yourself a goal for the day, week and month etc
  • Define the priority of these goals and work to your plan through out the day – Plan your work and work your plan
  • Cross off the goals as you achieve them
  • Make a point system so once you achieve a certain amount of points you get to give yourself a treat, get a masseuse for an hour, talk a walk along the beach, go get an ice cream, take a day off (you might want to give all these treats a certain number of points and you can redeem them for a reward, so you don’t take a day off after you achieve each goal :P )

If you are a task orientated person:

  • Define the tasks required for that day or week much the same as goals and give each task a time limit e.g. 45 minutes.
  • Get a stopwatch and when you begin a task start it, record the time on your list of tasks.
  • Revise this list and determine which tasks are taking you longer amounts of time to complete, schedule these tasks earlier in the day when your brain is in high gear.
  • Google’s Task Tracker on Google Desktop is a great FREE product. You simply double click a task and it starts the timer. You can make the tracker stay open all day so you can see how you are progressing.

If your job requires you to be inspired:

  • Devote a wall in your office area or if possible an entire room to be your inspiration area.
  • Put up pictures of your friends and family surround them with photos of the things you like, the beach, the forest, cars, Barbie dolls whatever it is that inspires you.
  • Start the day by walking into this room or staring at the wall. When you feel yourself laxing through the day go look at the wall again. Add to the wall, take away from the wall whenever you need.

Tip 4

Distinguish between work time and life time – Many people who run a small home based business or who start to telecommute begin to find they struggle to determine where their work ends and their life beings. Set yourself specific hours of work. In Australia the norm is 9am – 5pm. Stick to these hours, if you work later one day give yourself an early mark the next day. If you begin to put many of the other tips I’ve provided into action you will find you get more done in those same hours that you can begin to leave work early. Or even have an extra day off a week. If you get to this point, attempt to push yourself by adding another set of tasks into your daily routine. Or use that time to learn a new skill that you can use for your business. A rolling stone gathers no moss.

This is just a small set of tips to help you excel. It is not an exhaustive list but it covers many of the core parts that will help you become an effective worker, giving you more time to yourself and your work life will be more rewarding. I have found these to work really well for me, i just hope they work for you.

Bookmark and Share

PHP Redirect Code – with javascript

Ever needed a redirect function that would know when to use javascript of php. Well the wait is over *crowd goes wild*…. sorry here it is

To use the function simply call it like so:
<?php
$variables = array('firstvar' => $firstVar,
'secondvar' => "hello world");
REDIRECT("newPage.php?currentVar=123", $variables);
?>

and here it is again if you missed it

and voila!

If you liked it let me know please.

I think there is still an issue with if the variable already exists in the target, i just haven’t had the time to work on it.
Maybe i need to follow my tips in my other post – 4 Tips for working from home successfully

Bookmark and Share

$_FILES Array and its Confusing Structure

Have you ever noticed that the $_FILES array has an extremely odd structure that isn’t the usual type of array. The script i wrote helps to put it in an order so you can simply step through each one without having to write any sort of confusing loop.

It’s implementation can be seen below:

// a file field with the name image[] was passed
//if it were a non array input it would simply be if (!empty($files['image']))...
$files = change_file_array($_FILES);
if (!empty($files))
{
foreach ($files['image'] as $key => $f)
{
if ($f['error'] == 0 && $f['size'] > 0)
{
//do somethign with file here
}
}
}

I’m still getting used to wordpresses editor sorry about the indenting.

Click here download the script.

Bookmark and Share