PHP tutorial – Learn PHP programming in a simple way

Posted on December 20, 2007 Categories: Search

post author

Written by: Jan

Jan is an eccentric Slovakian SEO wizard. When he's not researching search, optimising sites, building inbound links, or working on content creation, he's a part-time professor, teaching PHP to his students at university.

(Important: All quotes within PHP code are normal quotes; 34th character in the ASCII table; also the — character is double hypen)

Step 1

When you’re done with the installation of PHP and Apache it’s time to create your first PHP script. In order to make things easier, download a PHP editor (Google “PHP editor” – PSPad is a good one) and install it. Run it and a blank file should be opened by default. Save it as “index.php“.

Sponsored links

Step 2

The first line should start with <? and the last should end with ?>. So go ahead and type this:

<?

//here will be the script

/*
This is just a comment
*/

?>

The line which starts with // symbols is a comment. If you’re going to write a long comment (into several lines), put it between /* and */ . Right now your script just shows a blank page. When we want to see output in our browser (after uploading your index.php to the server and opening it inside of the browser), it is necessary to use one of common functions designed for showing anything what we want. Say that we want to use the echo function: add this line into your index.php (somewhere between <? and ?> , and outside of comments)

echo “Hi, this is just a test! The script’s going to end soon. <br /> \”Mr. Santa Claus\”";

Now, do you see that text in your browser (after uploading the script to the server and opening it in the browser)? If you can see it, it has worked fine. If you don’t see anything or if you see an error, make sure your PHP file looks like this:

<?
echo “Hi, this is just a test! The script’s going to end soon. <br /> \”Mr. Santa Claus\”";
?>

If you still see an error, it’s likely that there’s something wrong on the server’s side. Why these ( \” ) symbols were used? The reason is simple: the echo function shows everything between the first and last . And if you didn’t use \ before , it would also cause an error. Also note the HTML tag within our echo. Since echo is a real universal function, it is possible to use any HTML, CSS, or JavaScript entities and tags within.

Basically, now you should be able to convert all your HTML pages into PHP ones. Bear in mind that every file which contains PHP should have a .php extension. It is up to server’s configuration if files named *.html can run PHP code, but in general this feature is not enabled.

Step 3

Now we should use cycles along with some variables. Each variable starts with $ . You’ll need to know how to use the while and for cycles. Let’s create another small script:

<?
$a = 10;
$j = 10;

for($i=1;$i<=$a;$i++)
echo “This is a line no. $i <br />”;

while($j>0)
{
echo “This is a cycle with the j variable $n <br />”;
$j–;
}
?>

First, we assigned some values to the two variables and then ran two cycles. The for cycle is characterised by the known amount of repetitions: this is given by the condition $i<=$a . The $i++ syntax means that our $i variable’s value is increased by 1 each time we write $i++ . The while cycle also contains a simple condition, and it runs until that condition is valid. The $j– line means that the $j variable is lowered by 1 each time this line is called.

Step 4

Comparing is a very important part of every programming language. For this purpose you should use the if condition. Its syntax is simple:

<?
for($a=1;$a<=10$;a++)
if($a==5)
echo “A = 5 right now”;
?>

As you can see, we don’t write if($a=5) but if($a==5). Also, the “if not equal” is written as != . Higher is > and lower is < . These are the basic things we should know.

Step 5

Of course, you may use functions while coding PHP scripts. A function has one output, but it can have a lot of inputs. Say that we want to simplify something in order to save time:

<?
function divide($a,$b)
{
if($b==0)
return “Invalid denominator”;
else
return $a/$b;
}
for($x=0;$x<=5;$x++)
for($y=0;$y<=3;$y++)
echo “The result of $x divided by $y is : “.divide($x,$y).”<br />”;
?>

Step 6

Since we can call functions, they should be logically separated in another file. Now it’s time for the include function. Of course, if we want to use it, it is necessary to have two files. Say that the first is called functions.php and the second is index.php.

<?
//this is functions.php
function do_something($input1,$input2)
{
return $input1.$input2;
}
?>

<?
//this is index.php
include “./functions.php”;

echo do_something(”My name is”,”John”).”<br />”;
echo do_something(”My name is”,”Edward”).”<br />”;
echo do_something(”My name is”,”Samantha”).”<br />”;
?>

Simple, isn’t it? Naturally, there are a lot of predefined functions. The functions below deal with strings.

addcslashes
addslashes
bin2hex
chop
chr
chunk_split
convert_cyr_string
convert_uudecode
convert_uuencode
count_chars
crc32
crypt
echo
explode
fprintf
get_html_translation_table
hebrev
hebrevc
html_entity_decode
htmlentities
htmlspecialchars_decode
htmlspecialchars
implode
join
levenshtein
localeconv
ltrim
md5_file
md5
metaphone
money_format
nl_langinfo
nl2br
number_format
ord
parse_str
print
printf
quoted_printable_decode
quotemeta
rtrim
setlocale
sha1_file
sha1
similar_text
soundex
sprintf
sscanf
str_getcsv
str_ireplace
str_pad
str_repeat
str_replace
str_rot13
str_shuffle
str_split
str_word_count
strcasecmp
strchr
strcmp
strcoll
strcspn
strip_tags
stripcslashes
stripos
stripslashes
stristr
strlen
strnatcasecmp
strnatcmp
strncasecmp
strncmp
strpbrk
strpos
strrchr
strrev
strripos
strrpos
strspn
strstr
strtok
strtolower
strtoupper
strtr
substr_compare
substr_count
substr_replace
substr
trim
ucfirst
ucwords
vfprintf
vprintf
vsprintf
wordwrap

Functions dealing with files

basename
chgrp
chmod
chown
clearstatcache
copy
delete
dirname
disk_free_space
disk_total_space
diskfreespace
fclose
feof
fflush
fgetc
fgetcsv
fgets
fgetss
file_exists
file_get_contents
file_put_contents
file
fileatime
filectime
filegroup
fileinode
filemtime
fileowner
fileperms
filesize
filetype
flock
fnmatch
fopen
fpassthru
fputcsv
fputs
fread
fscanf
fseek
fstat
ftell
ftruncate
fwrite
glob
is_dir
is_executable
is_file
is_link
is_readable
is_uploaded_file
is_writable
is_writeable
lchgrp
lchown
link
linkinfo
lstat
mkdir
move_uploaded_file
parse_ini_file
pathinfo
pclose
popen
readfile
readlink
realpath
rename
rewind
rmdir
set_file_buffer
stat
symlink
tempnam
tmpfile
touch
umask
unlink

MySQL functions

mysql_affected_rows
mysql_change_user
mysql_client_encoding
mysql_close
mysql_connect
mysql_create_db
mysql_data_seek
mysql_db_name
mysql_db_query
mysql_drop_db
mysql_errno
mysql_error
mysql_escape_string
mysql_fetch_array
mysql_fetch_assoc
mysql_fetch_field
mysql_fetch_lengths
mysql_fetch_object
mysql_fetch_row
mysql_field_flags
mysql_field_len
mysql_field_name
mysql_field_seek
mysql_field_table
mysql_field_type
mysql_free_result
mysql_get_client_info
mysql_get_host_info
mysql_get_proto_info
mysql_get_server_info
mysql_info
mysql_insert_id
mysql_list_dbs
mysql_list_fields
mysql_list_processes
mysql_list_tables
mysql_num_fields
mysql_num_rows
mysql_pconnect
mysql_ping
mysql_query
mysql_real_escape_string
mysql_result
mysql_select_db
mysql_set_charset
mysql_stat
mysql_tablename
mysql_thread_id
mysql_unbuffered_query

Math functions

debug_zval_dump
doubleval
empty
floatval
get_defined_vars
get_resource_type
gettype
import_request_variables
intval
is_array
is_binary
is_bool
is_buffer
is_callable
is_double
is_float
is_int
is_integer
is_long
is_null
is_numeric
is_object
is_real
is_resource
is_scalar
is_string
is_unicode
isset
print_r
serialize
settype
strval
unserialize
unset
var_dump
var_export

Actually there are many other functions, but those which work with databases, strings, variables and files are the most commonly used.

Follow us:

Leave a Reply

Archive

July 2010

June 2010

May 2010

April 2010

March 2010

February 2010

January 2010

December 2009

November 2009

May 2009

April 2009

March 2009

February 2009

January 2009

December 2008

November 2008

October 2008

September 2008

July 2008

June 2008

March 2008

February 2008

January 2008

December 2007

November 2007

October 2007

About Us

A team of nerds, creatives and strategy ninjas based in central London, building websites, social networks, widgets and social media apps.

We have a portfolio that is good enough to make a male peacock blush, and some killer outside-the-box products...in a box.
Ask us a Question

Blog posts