Remember HEADERS when sending mail from a site.

Generally speaking, the e-mail will go to junk because of incomplete and missing headers. Many spam filters pick these “lack of headers” as a commonality between all those e-mails for all those enlargement pills and pirated software we’ve all been after.

Your mail code is slightly incorrect though, generally speaking the usage for mail is:

mail(”To”,”Subject”,”Message”,”Headers”)

Which could explain why it went to junk the first time. Therefore you would have something like this established:

$headers = “MIME-Version: 1.0\r\n”;
$headers .= “Content-type: text/html; charset=iso-8859-1\r\n”; // Important to change if you ever add attachments
$headers .= “From: “.$email_address.”\r\n”;
$headers .= “Reply-To: “.$email_address.”\r\n”;
$headers .= “X-Mailer: PHP/”.phpversion().”\r\n”;

I’m sure you can work out the rest. Word of warning though, your e-mail address may be blacklisted as “junk” if you didn’t set the “from” value. There are many more headers that you may want to look up RFC2821 or some explanation on various headers.

Tutorials to read and learn

Coding Style – http://www.phpro.org/tutorials/PHP-Coding-Style.html

MVC – http://www.phpro.org/tutorials/Model-View-Controller-MVC.html

OOP – http://www.phpro.org/tutorials/Object-Oriented-Programming-with-PHP.html

Some PHP Tutorials

http://www.killerphp.com/tutorials/object-oriented-php/php-objects-page-1.php

http://phpvideotutorials.com/

http://www.php-mysql-tutorial.com/

http://www.phpro.org/tutorials/

http://www.idea22.com/video/list/

http://www.sitepoint.com/article/object-oriented-php

http://www.sitepoint.com/article/php-paging-result-sets

Australia Post Codes with Longitude and Latitude + PHP functions to calculate distance between them

http://www.corra.com.au/support/downloads/

# Australian Postcodes CSV File – Zip (292kb)
# Australian Postcodes MySQL Dump File – Gz (286kb)
# Australian Postcodes PHP Functions – Zip (2kb)
# Australian Postcodes PHP Functions – Plain Text (3kb)
# Australian Postcodes MySQL Function – Plain Text (1kb)

Create a PHP POP3 email reader

http://www.phpit.net/article/read-email-php-pop3/

Building a simple MVC with PHP5

http://www.phpit.net/article/simple-mvc-php5/

Creating PDF files on the fly with PHP

Two great articles

http://www.astahost.com/info.php/how-create-pdf-php_t4972.html

http://www.devarticles.com/c/a/PHP/Use-PHP-to-Create-Dynamic-pdf-Files/

Creating Graphs and Charts in PHP with PHP/SWF!

http://www.maani.us/charts/index.php?menu=Introduction

PHP With MYSQL Essential Training Notes

After completing the Lynda.com recent PHP and MySQL training series, these are the notes that I’ve taken. Hopefully they can serve as a useful reference for you like they have me!

The difference between single and double quotes

Its better to use double quotes.

  • You can add variables into double quotes and it will output the variable value.
  • You can surround a variable in curly braces and it will still output the variable value

Single quotes will output the variable name.

String Functions

$string = “The quick brown fox jumped over the lazy dog”

.=

Concatenates a string

str_repeat($string,2);

Repeats a string twice

strpos($string,”brown”);

Finds the position of the string

There is two types of numbers:

  • Integers (whole numbers)
  • Floating point numbers (decimals)

Manipulating Numbers

Increment: $var++

Decrement: $var–

Random number: rand()

Random number with min/max: rand(1,10)

Float point Numbers

Floating point numbers are Decimal numbers! Ie. 3.14

$myfloat = 3.143864

Round($myfloat,2); would produce 3.14

Arrays

print_r($array) will display all variables in an array

if you surround it with <pre> </pre> tags it will display them nicely formatted.

in_array(needle,haystack) checks for an item in an array

Boolean & NULL

Boolean means true or false, 1 or 0 (respectively).

Isset($variable) tests the Boolean state of a variable and returns true or false

empty($variable) is similar to the opposite of isset($var).However it will return TRUE for the value 0 in both integer and string format (also NULL).

Constants

Similar to variables however they do not change!

define(“MAX_WIDTH”, 980);

echo MAX_WIDTH;

If & Else statements

When using if, and elseif statements, the final else will be the default if none of the if and elseif statements are true.

Switch Statements

Use when you need to test one variable, instead of writing many if / else statements.

Make sure you use break in the code or it will continue to search through the conditions

Switch ($a) {

case 0:

echo “hi”;

break;

}

3 Different types of loops: While, For & Foreach

While Loops

$count = 0

while ($count <= 10) {

echo $count;

$count++;

}

For Loops

Same as while loops.

Format is:

for (initial, test, each) {statement;}

example: for ($count, $count <= 10; $count++) {echo $count . “<br />”; }

Foreach Loops (only used on arrays!!)

This is how you use each value

foreach ($array as $value) { statement; }

You can also loop through key, value pairs

foreach ($array as $key => $value) {statement;}

Pointers

To find the current position of the pointer in an array

current($array);

Move to the next position in an array

next($array);

Reset the pointer in an array

reset($array);

Using a while loop that moves the array pointer (similar to what you would do processing rows that are returned from a database)

$ages = array(4,8,15,22,29,33,52);

while ($age = current($ages)) { // this will loop while it can successfully assign an age from

statement;

next($ages);

}

User-Defined Functions

function name($arguments) { statement; }

Local Scope

Variables defined within a function, act as if they only exist within the function.

Global Scope

If you define a variable using the global $var syntax, then it will pull in variables outside of the function, and also make them available outside the function.

3 Ways to get information from a user

  1. GET
  2. POST
  3. COOKIE

Passing variables through GET & URLEncode

If you want to pass a character such as an ampersand (&) or space, you can include php in the link to urlencode the characters. For example:

<a href=”test.php?name=<?php echo urlencode(“david&”) ?>&surname=mara”> Link </a>

You only need to encode when using GET. Not with POST.

If you want to dynamically create an entire link, use rawurlencode($string) for everything before the ? in a link, and urlencode($string) for everything after.

Cookies

setcookie($name, $value, $expire);

Must come before ANY html, white space, tabs etc.. on a page.

Headers (and Page ReDirection),

Must come before ANY html, white space, tabs etc.. on a page.

Format:

header(header information);

How to write a page re-direct.

header(“Location: page.html”);

exit;

Output Buffering

Output buffering basically means that you can store up all the information of the page, and send it in one hit. This allows you to have headers appear in the body text of a page. This kind of ‘convenience’ comes at this cost of performance.

You can enable Output Buffering in the PHP.ini file.

You can also enable it without editing the PHP.ini file. You can do it within PHP.

ob_start(); // has to appear before any HTML is output if we’re sending headers

ob_end_flush();

CRUD – Create, Read, Update, Delete

Read

SELECT * FROM table WHERE column1 = ‘some_text’ ORDER BY column1, column2 ASC;

Create

INSERT INTO table (column1, column2, column3) VALUES (val1, val2, val3);

Note: Strings must have single quotes ‘ around them.

Update

UPDATE table SET column1 = ‘some_text’ WHERE id = 1;

mysql_affected_rows() will tell you how many rows were affected in the last update.

Delete

DELETE FROM table WHERE id = 1;

PHP Database Interaction in FIVE steps

1. Create a connection

$connection = mysql_connect(”localhost”, “root”, “password”);

2. Select a database

$db_select = mysql_select_db(”widget_corp”, $connection);

3. Perform database query

$result = mysql_query(”SELECT * FROM subjects”, $connection);

4. Use returned data (if any)

while ($row = mysql_fetch_array($result)) {

echo $row['menu_name'] . ” ” . $row['position'] . “<br />”;

}

5. Close connection

mysql_close($connection);

The 10 Essential MySQL commands

1. mysql_connect

Connects to a MySQL server

2. mysql_select_db

Selects a database

3. mysql_query

Used to query the database

4. mysql_error

You can echo mysql_error() to get the error returned by mysql

5. mysql_close

Close a MySQL connection

6. mysql_fetch_array

Retrieves the records in an array (can be accessed using associative keys)

Remember you have to loop through each record in the array.

7. mysql_num_rows

Retrieves the number of record rows retrieved from a query

8. mysql_affected_rows

Shows the affected number of rows from a query

9. mysql_real_escape_string

Escapes dangerous characters from entering your database

10. mysql_insert_id

Tells you the last inserted ID.


Text encoding and transformation

Anything you output to the browser should go through htmlentities especially if it’s coming from a database where users have entered the data.

htmlentities()

Converts any special characters to %lt; (html entities!)

strip_tags()

strips all html tags from text. You can allow specific tags as required:

strip_tags($content, “<b><br><p><a>”);

This would allow the bold, break, paragraph and link tags to be the only html formatting on this text.

nl2br()

nl2br($content); will preserve any ‘enters’ or new lines in the text entered by the user.


Login / Authorisation

When structuring your query string to search if a username/password is correct in a database, do NOT select * information and return that. This is insecure and you do not need the password returned. Instead return perhaps the id and the username and any other information you will require.

Incorrect Auth Check:

$query = “SELECT * FROM users WHERE username = ‘{$username}’ AND hashed_password = ‘{$hashed_password}’”;

Correct Auth Check:

$query = “SELECT id, username FROM users WHERE username = ‘{$username}’ AND hashed_password = ‘{$hashed_password}’”;


Building an Application (CMS)

  1. Blue printing
  2. Build databases
  3. Build the folder structure
  4. Build layout
  5. Build navigation
  6. Setup page layout using includes/requires
  7. Break the pages into chunks and start building!

Things to keep in mind

  • Don’t spend too much time refactoring or anything like that, find the balance between ‘perfect practice’ and ‘efficiency’. Don’t always go over-kill or you’ll never finish.
  • Don’t repeat yourself coding
  • Use htaccess to limit access to files which contain database logins/password details
  • Refactoring – improving your code
  • Use htaccess to limit access to your include files.

Setting menu icons to ACTIVE when the page is viewed

http://www.sebastiansulinski.co.uk/web_design_tutorials/css/active_button.php

This example uses PHP.