How to call a PHP function (with parentheses)

How to call a function in PHP

A reader of my blog recently emailed me, asking me to check over some PHP code

Nothing works from my php file except just connecting to the database

It’s simple code – I’m not doing anything fancy

So here’s the PHP code supplied:

function getConnection( ) {

$host="host";
$port=3306;
$socket="";
$user="me";
$password="mypassword";
$dbname="downloads";

@ $con = new mysqli($host, $user, $password, $dbname, $port, $socket);

if ( mysqli_connect_errno()) {
echo "Connection function failed";
return false;

} else {
echo "Connection function succeeded";
return $con;
}
}

$res = getConnection;
if (!$res) {
echo "Connection failed. " . mysql_errno($res) . ": " . mysql_error($res). "\n";
}
else {
echo "Connected to database." . "\n";
}

$key = md5(microtime());
if ($result = $res->query("SELECT count(*) FROM downloads WHERE downloadkey = '{$key}' LIMIT 1")){
echo "Select succeeded." . "\n";
}
else
{
echo "Select failed." . "\n";
}

They helpfully supplied output and the error message too:

Connected to database. Fatal error: Call to a member function query() on a non-object in /path-to/filename.php on line 33

Which seems to suggest to the connection is fine, but when it comes to use the connection. The connection object isn’t actually an object.

They are using a function to create the database connection, a good sign.

There are a few lines after the function, they all look okay

But wait, maybe something doesn’t look right about this line:

$res = getConnection;

Notice anything missing?

Does it look better like this?

$res = getConnection();

Yes! Calling a PHP function, even though that function has no parameters, you must include the parentheses!

Otherwise PHP doesn’t know it’s a function and actually assumes getConnection is a string. As demonstrated by this snippet:

$res = getConnection;
var_dump($res);
// Outputs: string(13) "getConnection"

So that was the first problem, the reader assumed the connection was being created.

When in fact the function was never being called.

Even though they have code to check the connection.

However, that code:

if (!$res) {

Was never going to equate to false, as $res was actually a string “getConnection”.

That if statement should be changed to this:

if (!is_object($res)) {

Now we are actually checking whether the $res variable is actually a connection object or not!

Help for avoiding undefined index notices

If you are just starting out with PHP, you may come across this message:

Notice: Undefined index: username in C:\wamp\www\mysite\index.php on line 99

Even if you’ve been coding for years you can still get this message!

You may be confused as to what an “Undefined index” is? Often seen when trying to access global server variables such as $_POST and $_GET when passing data from another page or posting it back to the same page.

So what is it? It really is an index of an array that hasn’t been defined yet.  You are trying to access data in a variable that doesn’t exist!

Depending on the PHP error reporting level you configure, you can even hide these notices, but that’s not recommended, better to deal with them and write good code.

You can normally fix your “Undefined index” errors with the isset function to check whether a variable is set, like this:

// Check if the username is set or not...
If (isset($_POST['username']))
{
$username = $_POST['username'];
}
else
{
$username = "";
}

However a very useful function which can save you many lines of code like the above and undefined index notices, can be found in the comments (all credit to the author) on the same page of the PHP manual.

function isset_or(&$check, $alternate = NULL)
{
return (isset($check)) ? $check : $alternate;
}

//Example usage which will give the same result as the if / else statement above
$username = isset_or($_POST['username'], "");

It’s a very useful function if you are using plain PHP and need to determine the value of variables. It will also make your code cleaner and easier to read than repeated if / else statements like the above.

How to protect your PHP source code as a freelancing web developer

How to protect your PHP source code?  You might be worried about giving away your secret sauce  or having it reverse engineered.

Another good reason for wanting to protect your code is delivering the code to a clients server / hosting before final payment has been made for the development of the code.

I have experienced this first hand! I was very surprised to find a delivery of code for sign off was encrypted, I hadn’t seen that before.  Sure enough when we asked the development company they said they would remove the encryption once the final payment had been made (there already had been a number of part payments through the project).

So definitely a useful tool for small shops and freelancers, make it a part of your contract that the source code will be decrypted when fully paid for.

We also had another client who wanted to distribute PHP code on USB thumb sticks.  Not recommended, but it is possible to run a web server like that, using a SQLite database.  Given the accessibility of a USB thumb stick rather than a Linux server, we encrypted the PHP code to protect it.

Here’s a couple of PHP encoders that we’ve used:

So encode, obfuscate and protect your code, if you feel the need, especially if you aren’t 100% confident of a client paying you.

Have you experienced a similar situation before, please share below in the comments.  If you would like more useful tips like this, please subscribe to be updated on new ones.

What is the minimum amount of time I should charge as a Freelance Web Developer?

Your clients are calling you, emailing you, sending in small requests…

Can you change this? Can you change that?

Sometimes the changes are so small, barely 5 minutes that you feel guilty for charging your “valuable” clients.

Well you shouldn’t feel guilty! You are in business and you are selling your time and your clients are likely consuming your time with small requests if you don’t have a minimum amount of time to charge them.

So yes, yes you should be charging a minimum amount of time for almost all client engagement.  Make your clients aware, ideally up front and in your contract of what that minimum is, so that there aren’t surprises when they receive their invoices.

Always consider the amount of time it takes to read their emails, answer their calls, discuss / consider their request, find the place to make the changes, test the changes in multiple browsers, publish the changes and then respond or get back to the client, as well as tracking the time spent and creating and sending the invoice.  All in all, even though the actually technical change may take a few minutes, by the time you’ve done everything else, it could easily be an hour of your time that has gone by if not more.

If you don’t have a support contract or monthly retainer, I recommend that your minimum amount of time to charge is one hour.  Your client also knows your hourly rate, so they know the minimum charge to expect when they engage you.  This will help make the client think about what they are going to request, before they request it and consume your time.

Often in work places, I’ve found the human interaction takes many orders of magnitude longer discussing a change that is required than the actual change itself.  So track all that additional time and charge your client appropriately.

How to use PHP Sessions?

Need help with a simple PHP session tutorial?

Wondering what you should store in a session?

You are in the right place for a fun example:

If you are learning PHP, sooner or later you will have a need for using sessions.

Sessions allow you to maintain the state of an application between user requests.

They are useful when a user logs in to your site. So that you can recognize on each page that the user is still logged in as they navigate the pages of your site.

Once you understand how sessions work you might be tempted to store lots of data in the session. However sessions should generally be used to identify a user. Other data is saved in the database which is linked to the user / session.

Every PHP page which needs to access the session data will need to call this function first:

session_start();

You can then store and retrieve data in the session:

// To store a number in the session
$_SESSION['number'] = 911;
// To retrieve the store number
echo $_SESSION['number'];

The following in simple example of storing and retrieving sessions. This is a game of “Higher or lower?”, where you try and guess a number between 1 and 100. The code picks a random number and stores in it in the session when the game is started. Then as you attempt to guess, the cumulative number of guess is also stored in the session. When you win and correctly guess the number. It will retrieve the number of attempts from the session and display it.

Link to demo http://trabest.com/higher-or-lower.php
Link to github repo with the code https://github.com/element121/higher-or-lower

Try it out, the best number of guesses so far is 3!

Please leave a comment below and let me know what you think. If you any have questions, feel free to contact me.

How much should I charge hourly as a PHP Freelance Web Developer?

How much should I charge hourly as a PHP Freelance Web Developer?

Working your own hours as a freelancer can be great with regular work coming in.

But you need to make sure you are making ends meet and covering your costs.

You might be considering switching from full-time paid employment to freelance or some part-time freelance on the side.

So how do you figure out much to charge for your time?

It all depends on your skills, the size of the job, the complexity of the job, your location, your overheads, whether it’s a new client or an existing one…

However you should re-think your approach, because in order to answer the question, it’s important to find out…

How much do you need to charge to be able to live (comfortably)?

What’s your time worth to you?

How much do you need to earn annually?  That’s your target! Figure that out and work backwards from there, divide by 52 to get the weekly rate, divide by the number of hours and days you want to work to get your hourly rate.

For example:


Desired annual income: $50,000

Giving a weekly income: $961.54 (50,000 / 52)

How many hours do you want to work in a 5 day week?

5 hours a day over 5 days gives you an hourly rate: $38.46 (961.54 / 5 /  5)

8 hours a day over 4 days give you an hourly rate:  $30.00 (961.54 / 8 / 4)


Use the above example to work out what you need to charge an hour to cover your needs over a year.  Do it now, if you don’t know what your rate should be.

If it comes out at a rate like $38.46 then round up to $40.00 and then double it to $80! As you need to cover your quiet periods as you are unlikely to working full-time all the time.

Figuring out how much you need to charge and how many hours you need to work is the important first step.

You can also charge by project for a fixed price.

Another option is charging by value, selling your value to your clients.

Not only will this provide value to your clients.

You will be able to maximize your own value in $$$

If you are interested in charging by value, I recommend the Double Your Freelancing course by Brennan Dunn. Try it out for free.

Looking to hire a PHP developer, then test them out!

6hxvm0nzyp8-caleb-ralston

If you are looking to hire a PHP developer, then test them before an interview, in the interview, or if you are unsure about hiring a new freelance developer, test them with a small project first, minimize your time and risk and save yourself potential headaches in the future…

You can get cheap shitty programmers anywhere.

PHP is great, has been around for years and is easily accessible and widely used, but that means there are a lot of developers / programmers out there who are “experienced” in PHP and available at amazingly low rates.  So unless you really want bargain basement code, give them a test!

You should of tested them before you hired them.

Some companies that have hired me and have never tested me technically or otherwise, I’m always surprised by that!

One company I applied for made me go through 4 rounds of testing. The companies with the shitty developers don’t test the people they hire.

Amazingly a significant percentage of people will buy a car without test driving it!  It might be different if you are hiring a car from a trusted company like Avis, Budget, etc.  In the same way if you are hiring a person through a recruitment agency or trusted company you will assume they are up to scratch and have been checked over at least.

I test all hires with a few decent programming challenges and i only let them use pen and paper.

If you don’t test them out first, you could easily end up looking to hire someone else to fix their mess of code.  Often that can mean re-writing lots if not all the code, pushing your project back even further along the time line.

Usually because people hiring don’t know code.

If you really don’t know code, do you have another developer already on staff who could easily help you with some relevant technical questions or a quick test? I’ve seen this before where non-technical managers, don’t involve existing staff to hire new technical staff!

Try before you buy and test before you hire!

So test them verbally, online in a video chat, in person, written test, computer test, find a way!

8 things to consider when hiring a Freelance PHP Programmer

11h1ssvcixc-federico-bottos

When hiring a Freelance PHP programmer, you can easily be inundated with choices on sites like Elance / ODesk and Freelancer.  So if you need some help narrowing down the choices consider the following points:

  1. Price, do you really want the cheapest PHP programmer in the world?  What value will that give you? Consider paying more for better quality work that is done right first time around and done in a timely manner.
  2. Experience / Portfolio / Ratings, do they have the right experience you are looking for with a portfolio to match and how are they rated online?
  3. Language, if you are both fluent in the same language, it will make communication so much easier
  4. Time Zone, consider how important it is that someone is available during your working hours, do you need to be able to easily get hold of them, when it’s convenient for you.
  5. Location and currency, makes it easy not having to deal with exchange rates and everyone will understand their tax obligations.
  6. Availability, linked to the time zone and other commitments, will this freelancer be working on your project 100% and will they be able to respond when you need them and will they will be available for support in the future if needed?
  7. Start small, test a new freelancer with a small project, to see how they complete it, if they are good you can always hire them again, this way you minimize your risks for a small investment.
  8. References, do they have references you can check with previous clients? A quick phone call now can reassure you and may save you a lot of potential headaches later.

 

Why you shouldn’t use the CodeIgniter PHP framework… directly

There is a lot of discussion about which is the “Best PHP framework” and there are many good ones to choose from Laravel, Symfony, CodeIgniter, CakePHP, Yii, to name a few off the top of my head.  There are many different answers about which may be “best” depending on your needs and the use case.

Personally I’ve almost always used CodeIgniter, but never directly!  I did try Cake and Yii and read up on the other two I’ve mentioned, but never used them either yet.

And to add fuel to the fire, I think you should consider not using CodeIgniter directly, but instead use on of the “frameworks” built on top of and extending CodeIgniter.

To name but a few:

Personally I’ve used Bonfire a couple of times and GoCart many times.  I’ve found GoCart a great framework (because it’s built on top of CodeIgniter).  It’s actually designed as a lightweight e-commerce platform with a basic lightweight CMS.  However I’ve never really used all the features it comes with, instead it gives me a framework/platform to quickly build web applications on top of.  I can make use of it’s user management system straight away, I don’t need to build my own.  It’s also Bootstrapped, which is all that I need to quickly build clean and functional web apps.

I liken the framework choice to a choice about cars, you can ask what’s the best car for under $25,000 and you might be able to come up with a choice of a three of four, but all have slightly different advantages and options.  Then next years models will come out and there will be new choices, there may even be a new manufacturer with a brand new model…

Sometimes though it’s best stick with the tried and tested frameworks, just as car manufactures stick with their tried and tested “frameworks”.  The framework that makes an Audi A3, also makes a VW Golf as it does a SEAT and a Skoda.

So consider the above if you haven’t already looked into them.  There may well be similar offerings built on top of Laravel and Symfony which I haven’t investigated yet.

Whilst writing this, it’s made me think maybe I really should check out CodeIgniter on it’s own.  What frameworks do you use? Let me know in the comments below…

How to protect your PHP source code with encryption?

Worried about giving away your PHP source code?

Want to protect your code when delivering it to a clients hosting when it’s not paid for yet?

I know as this has happened to me. I found a delivery of PHP code for sign off encrypted, I hadn’t seen that before. When we asked the company they said they would remove the encryption upon final payment.

Encryption is definitely a useful tool for PHP developers. Make it a deliverable of your contract that the source code will be decrypted when paid for.

We also had another client who wanted to distribute PHP code on USB thumb sticks.  Not recommended, but it is possible to run it like that, using a SQLite database.  Given the accessibility of a USB thumb stick rather than a Linux server, we encrypted the PHP code.

Here’s a couple of PHP encoders that we’ve used:

So encode, obfuscate and protect your code, if you feel the need to!

Please leave a comment below or sign-up for email updates on new blog post.