Ask Us Your PHP Website Development Questions


Click here to Register for Ask the Cult Masters

I’ve been coding for about a decade-and-a-half and I still have questions that only those who are more advanced than me (yes there are people who are more advanced than me) can answer. As it is right now, I like to search for answers on my own but it wasn’t always like this.

When I was still a young coder, I asked questions – a LOT of QUESTIONS. The same is true for Cult Masters Benj and John which is why we thought it’d be a good idea to do a once a month open-forum webinar wherein your can ask us your php website development questions and we’ll do our best to answer.

We called it “Ask the Cult Masters”

Participation is simple, you tweet whatever php website development question you have using the hashtag #phptraining. We will then monitor your questions from this day until broadcast date and we will answer them live.

Of course, in order for you to hear what we have to say, you’ll have to register for the webinar which is, well, FREE.

Register now at http://coderscult.com/webinars/ask-1

27 Things You Must NOT Forget in Creating a Fast Loading Website

How to Lose Weight in the Browser and Create a Fast Loading Web Site

I don’t like waiting more than 5 seconds for a webpage to load and yes I’m being kind. Many would actually bail out if the page doesn’t load in 2-3 seconds. For years web designers and developers alike have been told to do what can be done to speed up page load times.

A fast server is not always enough. Most of the time, the choking point is the browser as it takes too long to load all the elements of a web page. In fact, streamlined web pages on an average server can easily outperform bulky web pages on a fast server. As you will see in the list below, a huge majority of the optimizations are for the browser.

So how does one do it? BrowserDiet.com nails it just right with a 27-point list which I am summarizing below.

HTML

  1. Avoid Inline Code
  2. Styles Up Top, Scripts Down Bottom
  3. Minify Your Html
  4. Try Out Async And Defer

CSS

  1. Minify Your Stylesheets
  2. Combining Multiple CSS Files
  3. Don’t Use the Universal Selector
  4. Prefer <link> Over @import
  5. Think About (and Rethink) Your Key Selector

Javascript

  1. Load 3rd Party Content Asynchronously
  2. Cache Array Lengths
  3. Avoid document.write
  4. Minimize Repaints and Reflows
  5. Minify Your Script
  6. Combine Multiple JS Files Into One

jQuery

  1. Always Use the Latest Version of Jquery
  2. Selectors
  3. Take Advantage of Method Chaining
  4. Use for Instead of Each
  5. Don’t Use Jquery…

Images

  1. Use CSS Sprites
  2. Don’t Scale Images in Markup
  3. Optimize Your Images

Server

  1. Enable Smart Caching
  2. Gzip

Bonus

  1. Diagnosis Tools: Your Best Friend

Read the detailed list at BrowserDiet.com

PHP cURL Tutorial and Example

Do you want to learn how to use cURL in PHP? Well, if so then this tutorial is for you. But before anything else, what is cURL?

cURL is a command line tool for transferring files with URL syntax. The strong point of cURL is the number of data transfer protocols it supports. It is distributed under the MIT License which makes cURL free software. It supports FTP, FTPS, HTTP, HTTPS, TFTP, SCP, SFTP, Telnet, DICT, FILE and LDAP. – based on Wikipedia’s definition

PHP cURL allows you to read websites, make automated logins, upload files and many more. I’m personally using it to automate updating of my many websites.

Now that you know what cURL is, I think it’s time to look at some code.

<?php
$ch = curl_init ("http://www.yahoo.com");
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$yahoo = curl_exec ($ch);
?>

The simple example above simply gets the contents of www.yahoo.com and saves it in the variable $yahoo. Here’s a line-by-line explanation:

$ch = curl_init (“http://www.yahoo.com”);

Initialize curl with the URL of yahoo

curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);

Tell php curl that we want the data returned to us instead of being displayed

$yahoo = curl_exec ($ch);

Execute curl and put the output in $yahoo.

But, that’s too simple! That can be done in simpler ways with PHP’s file functions such as file() and file_get_contents()! True but that’s where the comparison ends.

The power of PHP cURL lies within the curl_setopt() function. This function instructs cURL of what exactly we want to do. Let’s say, what if a webpage that you want to access checks for the HTTP_REFERER header? Or perhaps, what if you need to access a webpage that works correctly only if cookies are enabled?

Here’s another example… This time we specify the HTTP_REFERER…

<?php
$ch = curl_init ("http://www.somedomain.com/page2.php");
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_REFERER, "http://www.somedomain.com/page1.php");
$page = curl_exec ($ch);
?>

In this example, the CURLOPT_REFERER line tells cURL to set the HTTP_REFERER header to http://www.somedomain.com/page1.php.

PHP cURL can do more. It can send POST data, it can log on to a website and automate tasks as if it was a real person and much more. That’s it for now and I hope this PHP cURL Tutorial helped you.

PHP cURL Cookies Example

Want to learn how to use PHP cURL with Cookies? Well, it’s pretty simple so let’s go see the code but first let’s make a scenario…

Say we have a page called ‘cookiepage.php’ in a particular website that checks for the cookie set by the homepage and will only return the proper output if the cookie exists. How do you do it? Here’s how…

<?php

/* STEP 1. let’s create a cookie file */

$ckfile = tempnam ("/tmp", "CURLCOOKIE");

/* STEP 2. visit the homepage to set the cookie properly */

$ch = curl_init ("http://somedomain.com/");
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);

/* STEP 3. visit cookiepage.php */

$ch = curl_init ("http://somedomain.com/cookiepage.php");
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);

/* here you can do whatever you want with $output */

?>

Just in case you weren’t able to catch what we did in the above example, here’s a short explanation.

  • STEP 1 creates a temporary cookie file using the tempnam() function.
  • STEP 2 loads the homepage and saves the cookie in our temporary cookie file. The key here is this line:curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
  • STEP 3 loads cookiepage.php with the saved cookie with this line:curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);

Sleek and simple ei? Hope this PHP cURL Cookie example helped you out!

How to Post Data with cURL in PHP

Do you need to post data to a website using PHP? It’s actually pretty easy to do. Here’s the code.

<?php
$urltopost = "http://somewebsite.com/script.php";
$datatopost = array (
"firstname" => "Mike",
"lastname" => "Lopez",
"email" => "[email protected]",
);

$ch = curl_init ($urltopost);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$returndata = curl_exec ($ch);
?>

And what happened? Here’s my quick explanation.

$urltopost

The url where you want to post your data to

$datatopost

The post data as an associative array. The keys are the post variables

$ch = curl_init ($urltopost);

Initializes cURL

curl_setopt ($ch, CURLOPT_POST, true);

Tells cURL that we want to send post data

curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);

Tells cURL what are post data is

curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);

Tells cURL to return the output of the post

$returndata = curl_exec ($ch);

Executes the cURL and saves theoutput in $returndata

That’s it.

Coding Starts in Your Head

I personally believe that coding in general, website development included, requires one to have a proper mindset. I’m pretty sure that all great coders have some commonalities that define their success.

Watch this:

Point is we can teach you everything that we can teach you but without the proper mindset you’ll only be a mediocre coder at most.

Also check out LearnPHP.co’s recent interview with yours truly on the matter.

Setting up Your PHP Web Development Environment

So you want to learn to develop websites in PHP. That’s all cool but where do you begin?

You search the web and find out that you have to setup a web server on your computer as well as a MySQL server. It’s all confusing – I know, I too was confused at first.

Good news is that the good guys and gals over at apachefriends.org created XAMPP. It pretty much does all the installation work for you so you can focus on what you want – creating websites.

They have versions for Windows, Mac, Linux and even Solaris. And oh, it’s totally free!

Download it here:

The download page includes setup instructions as well. If you think you can create websites with PHP then I’m sure you can follow the installation instructions too.

What Editor Should You Use

Now that you have Apache/PHP and MySQL running through XAMPP, the next thing for you to do is install an editor. Any plain text editor such as Notepad will do. However, there are better editors out there that provide syntax highlighting and debugging functions. One of my favorites is Eclipse PDT (PHP Development Tools) NetBeans. It’s free and it runs on Java which means it is cross-platform.

Download it at netbeans.org

One nice feature I like with NetBeans is that it has a list of all the functions supported by PHP making it easier for me to write thousands of lines of code. Also, since it’s an IDE, it also keeps track of your variables, functions, and classes.

Quick but important note, it’s also best to keep a copy of the PHP manual accessible. If you’re always online, then the manual is just a click away. Typing php.net/str_replace on your browser will take you to the documentation of the PHP’s str_replace function. You may also want to download a copy of the PHP manual if you’re not connected to the internet all the time.

There you go. If you’ve successfully installed XAMPP and NetBeans then you already have the basic needs in getting started with PHP.

Javascript Sleep Function

I’ll make this short and quick. I’ve been searching the web for a Javascript sleep function that works and came across this. It was presented as a class but what I needed was just a function so I rewrote the code a bit. Here’s the end result of my Javascript sleep function which I named, well, jsleep.

function jsleep(s){
	s=s*1000;
	var a=true;
	var n=new Date();
	var w;
	var sMS=n.getTime();
	while(a){
		w=new Date();
		wMS=w.getTime();
		if(wMS-sMS>s) a=false;
	}
}
// how to use
alert('in the beginning there was a pause...');
jsleep(3);
alert('3 seconds after... the pause was gone.');

I’ve tested it in Google Chrome, Firefox 3 and Internet Explorer 7. Works like a charm.