PHP


Haifa Linux Club


tux.jpg
phppic.jpg
15/10/2001
by Shlomi Loubaton






---------------------

PHP - history


PHP is a language for creating interactive web sites.
It was originally called "Personal Home Page Tools"
when it was created in 1994 by Rasmus Lerdorf to keep
track of who was looking at his online resume.

Mid-1997: Technion students Andi Gutmans and Zeev Suraski
redesigned the PHP language engine and wrote some of the
most popular PHP modules.

At that time PHP already had its own site, php.net,
run by the computer science community, and was powering
thousands of Web sites. The script was just beginning
to be recognized by developers who preferred the
multi-platform script over its more limited
Microsoft ASP counterpart that interfaces only
with Windows NT.

Today PHP Web developers applaud the script's simplicity,
flexibility, and ability to generate HTML pages quickly.
Over 5,100,000 (1/2001) sites around the world use PHP.

rasmus.jpg

------------------------

PHP vs ASP


php:-) Open source
asp:-(


php:-) Very fast !!!
asp:-(

php:-) Superior Memory Management
asp:-| windows memory management

php:-) No Hidden Costs with PHP
asp:-(
Need encryption -- buy ASPEncrypt.
Need email management -- buy ServerObject's QMail.
Need file uploading -- buy Software Artisans SA-FileUp.

php:-) MySQL makes it cooler.
The following databases are currently supported:
Adabas D Ingres Oracle (OCI7 and OCI8)
dBase InterBase Ovrimos
Empress FrontBase PostgreSQL
FilePro (read-only) mSQL Solid
Hyperwave Direct MS-SQL Sybase
IBM DB2 MySQL Velocis
Informix ODBC Unix dbm
asp:-| odbc makes it ???

------------------------

...PHP vs ASP



php:-) Closer to Java/C++/Perl Style of Programming
asp:-| VBscript ?

php:-) No Show Stopper Bugs
asp:-( just surf to any asp based portal and see what i'm talking about

php:-) Cross Platform Migration Strategy.
asp:-( Chilisoft ASP ? (cost lots of $$$s)

php:-| no application variables ... but what is that anyway ? server's database ?
asp:-) application variables

php:-| HTTP GET and POST variables are automatically created as global variables (security??)
asp:-| i have to "Request." my HTTP GET and POST variables??

php:-( if your php script is not working , you can blame no one but yourself
asp:-) You can blame Micro$oft, iis , asp and so on...

php:-( you don't have time for a coffie break because your computer never crashes
asp:-) you have a lot of coffie breaks ...

---------------------------------

installing PHP - Apache DSO


requires RPMs :

compilation : bison , binutils , cpp , glibc-devel , gcc , kernel-headers
apache packs: apache , apache-devel (that's where the apxs script is from)
mysql packs : mysql , mysqlclient , mysql-devel , mysql-server
gd/graphics : gd , gd-devel , libjpeg ,libpng, freetype

1.
./configure --with-apxs=/usr/sbin/apxs --with-mysql=/usr/ --enable-track-vars --with-gd
--with-gpeg --with-png --with-ttf
2.
make
3.
make install
4.
copy php.ini-dist to /usr/local/lib/php.ini
and edit options.
5.
edit your httpd.conf - uncomment this line:(*New versions- done automatially*)
AddType application/x-httpd-php .php
6.
restart server (/etc/init.d/httpd restart)


--enable-track-vars : (php4+ enabled bt default)
enables tracking of GET/POST/Cookies variables.

--with-mysql[=DIR]
enables MySQL db functions

--with-gd[=DIR]
enable GD support.

--with-apxs[=FILE]
Build shared Apache module. (if you want to install PHP as DSO)


---------------------------------

installing PHP - Apache Module:


1. gunzip apache_1.3.x.tar.gz
2. tar xvf apache_1.3.x.tar
3. gunzip php-x.x.x.tar.gz
4. tar xvf php-x.x.x.tar
5. cd apache_1.3.x
6. ./configure --prefix=/www
7. cd ../php-x.x.x
8. ./configure --with-mysql --with-apache=../apache_1.3.x --enable-track-vars
9. make
10. make install
11. cd ../apache_1.3.x
12. ./configure --activate-module=src/modules/php4/libphp4.a
13. make
14. make install
15. cd ../php-x.x.x
16. cp php.ini-dist /usr/local/lib/php.ini
17. Edit your httpd.conf or srm.conf file and add:
AddType application/x-httpd-php .php

18. Use your normal procedure for restarting the Apache server. (You must
stop and restart the server, not just cause the server to reload by
use a HUP or USR1 signal.)

----------------------------

PHP syntax: C+Perl = PHP


If you are coming from a C, C++, Perl or Java background,
learning PHP would probably be a piece of cake. In fact, you probably
can get started writing your scripts almost immediately.

we can escape HTML using php tags(when option --enable-short-tags is enabled) :
<? SOME_PHP_SCRIPT_HERE ?>

Our first PHP script :
<? phpinfo() ?>

This should print a nice HTML table that contains information about the current
PHP build including list of all enabled/disabled options.


----------------

Hello, PHP !


simple output : ("CGI Style")
<? echo "<html>\n<head>\n</head>\n<body>\nHello world!<br>\n</body>\n</html>"?>

simple output 2 : (embeded style)
<html>
<head></head>
<body>
<?= "Hello world!" ?><br>
</body>

More ways of Escaping from HTML :
PHP3 style:
<?php
echo "Hello world!"
?>

the "<script>" tag:
<script language="php"> 
echo "Hello world!";
</script>
ASP style ():
<% echo "hello world"; %>


---------------

/*PHP Comments*/


<?
//comment

# comment

/*
multi line comment (c++ style)
*/
?>

-------------

PHP $Variables


<?
$x 
false;        # boolean
$x true;

$x 10;        # decimal
$x 1.45;        # Floating point
$x 0x1A;        # hexadecimal 

$x "mmm\"oo'oo\n";    # string = mmm"oo'oo  +return in the end of the line
$x 'mmm"oo\'oo\n';    # string = mmm"oo'oo\n

$y = &$x        # Reference

$x[1] = 10        # array of decimals
$x["name"] = "shlomi";    # associative arrays
$arr[] = "lalala";    # push "lalala"
$x[2]["lala"] = "xx";    # two dimensional

$name "shlomi";
$animals = array("dog" => "azit" "cat" => "mitzi");
echo 
"hello ! My name is $name and my dog's name is ${animals['dog']}";
?>

-------------

...PHP $Variables



considered FALSE:

boolean: FALSE
integer: 0
float: 0.0
string: empty string "", and the string "0"
array: 0 elements
object: 0 elements
NULL

C-style casting :
<? $bool true;
echo (int)
$bool?>
will output "1";

Type Juggling :
<?
$x 
"100";
$x++;
// $x is now 101
?>

Variable variables: (@#%^!!)
<?
$moo 
"xxx";
$a "moo";
$
$a "boo";

echo 
"variable \$a is '$a' and \$moo is '$moo'.<br>";

// will output: variable $a is 'moo' and $moo is 'boo';
?>


----------------

Operators



+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
& And
| Or
^ Xor
. add string (like in perl)
<< Shift left
>> Shift right

--------------------

Assignment Operators



<?
$x 
"Hello ";
$x.= "wrold!";

$x 10;
$x++;
$x *= 5;

$x = array(1,3,2,4,10);
$x = array(
     
"a" => "4",
     
"i" => "1",
     
"e" => "3",
     
"later"  => "l8r"
);
?>

--------------------

Comparison Operators



$a == $b Equal - True if $a is equal to $b.
$a === $b Identical - True if $a is equal to $b, and they are of the same type.
$a != $b Not equal - True if $a is not equal to $b.
$a !== $b Not identical - True if $a is not equal to $b, or they are not of the same type.
$a < $b Less than - True if $a is strictly less than $b.
$a > $b Greater than - True if $a is strictly greater than $b.
$a <= $b Less than or equal to - True if $a is less than or equal to $b.
$a >= $b Greater than or equal to - True if $a is greater than or equal to $b.

the ? operator - like the C operator:
<?
echo ($x==0) ? "X value is zero" "X value is not zero";
?>

-----------------

Logical Operators



$a and $b True if both $a and $b are true.
$a or $b True if either $a or $b is true.
$a xor $b True if either $a or $b is true, but not both.
! $a True if $a is not true.
$a && $b True if both $a and $b are true.
$a || $b True if either $a or $b is true.


------------------

Control Structures


if:
<?
if ($a $b) {
    print 
"a is bigger than b";
    
$b $a;
}
?>
else:
<?
if ($a $b) {
    print 
"a is bigger than b";
} else {
    print 
"a is NOT bigger than b";
}
?>
elseif:
<?
if ($a $b) {
    print 
"a is bigger than b";
} elseif (
$a == $b) {
    print 
"a is equal to b";
} else {
    print 
"a is smaller than b";
}
?>

-----------

While loops


While:
<?
$i 
1;
while (
$i <= 10) {
    print 
$i++;  /* the printed value would be
                    $i before the increment
                    (post-increment) */
}
?>
do .. while:
<?
$i 
0;
do {
   print 
$i++;
} while (
$i10);
?>


---------

For loops


<?
/* example 1 */

for ($i 1$i <= 10$i++) {
    print 
$i;
}

/* example 2 */

for ($i 1;;$i++) {
    if (
$i 10) {
        break;
    }
    print 
$i;
}

/* example 3 */

$i 1;
for (;;) {
    if (
$i 10) {
        break;
    }
    print 
$i;
    
$i++;
}

/* example 4 */

for ($i 1$i <= 10; print $i$i++);
?>

-------------

foreach loops


<?
/* values */

$a = array (12317);

foreach (
$a as $v) {
   print 
"Current value of \$v: $v.<br>";
}

/* values and keys */

$a = array (12317);
foreach(
$a as $k => $v) {
    print 
"\$a[$k] is $v<br>";
}
?>

------------

switch


<?
switch ($i) {
    case 
0:
        print 
"i equals 0";
        break;
    case 
1:
        print 
"i equals 1";
        break;
    case 
2:
        print 
"i equals 2";
        break;
    default:
        print 
"i is not equal to 0, 1 or 2";
}
?>

--------

includes


<?
include("/libs/mylib1.inc");
include_once(
"/libs/mylib2.inc");
?>

--------------------

Predefined variables


(very partial list)
<?
$x 
$SERVER_NAME;
#The name of the server host 

$x $REQUEST_METHOD;
#'GET', 'HEAD', 'POST' or 'PUT'

$x $PHP_SELF;
#The filename of the currently executing script

$x $HTTP_COOKIE_VARS["Varname"];
$x $HTTP_GET_VARS["Varname"];
$x $HTTP_POST_VARS["Varname"];
# variables that were posted using post, get or cookie.

$x $REMOTE_ADDR
# The IP address from which the user is viewing the current page. 
?>



---------

functions


<?
function la(){ 
    return 
"lalala\n<br>";


echo 
la();
// will output lalala
?>
Variable scope:
<?

$x 
"XXX";

function 
put_in_x($myparam){ 
    
$x $myparam;


put_in_x("YYY");
echo 
$x;
// will output XXX
?>
using global variables in a function.
<?

$x 
"XXX";

function 
put_in_x($myparam){ 
    global 
$x;
    
$x $myparam;


put_in_x("YYY");
echo 
$x;
// will output YYY
?>



-------------------

variables functions


(partial list)
empty - Determine whether a variable is set
isset - same as !empty($a)
gettype - Get the type of a variable
get_defined_vars - Returns an array of all defined variables
is_array - Finds whether a variable is an array
is_bool - Finds out whether a variable is a boolean
is_float - Finds whether a variable is a float
is_int - Find whether a variable is an integer
is_null - Finds whether a variable is NULL
is_numeric - Finds whether a variable is a number or a numeric string
is_object - Finds whether a variable is an object
is_string - Finds whether a variable is a string
unset - Unset a given variable
functions for debugging :
print_r - Prints human-readable information about a variable
var_dump - Dumps information about a variable

----------------------

string functions


(partial list)
chop - Strip whitespace from the end of a string
chr - Return a specific character
crypt - DES-encrypt a string
hebrev - Convert logical Hebrew text to visual text
htmlspecialchars - Convert special characters to HTML entities
md5 - Calculate the md5 hash of a string
nl2br - Inserts HTML line breaks before all newlines in a string
ord - Return ASCII value of character
sprintf - Return a formatted string
strip_tags - Strip HTML and PHP tags from a string
addslashes - Quote string with slashes
stripslashes - Un-quote string quoted with addslashes()
strlen - Get string length
strpos - Find position of first occurrence of a string
strrev - Reverse a string
strtolower - Make a string lowercase
strtoupper - Make a string uppercase
str_replace - Replace all occurrences of the search string with the replacement string
join - Join array elements with a string
split - split string into array by regular expression
<?
$date 
"04/30/1973";  // Delimiters may be slash, dot, or hyphen
list ($month$day$year) = split ('[/.-]'$date);
echo 
"Month: $month; Day: $day; Year: $year<br>\n";
?>

---------------

array functions


(partial list)
count - Count elements in a variable
array_pop - Pop the element off the end of array
array_push - Push one or more elements onto the end of array
array_reverse - Return an array with elements in reverse order
array_shift - Shift an element off the beginning of array
array_unshift - Prepend one or more elements to the beginning of array
array_sum - Calculate the sum of values in an array.
array_unique - Removes duplicate values from an array
array_values - Return all the values of an array
in_array - Return TRUE if a value exists in an array
array_search - Searches the array for a given value and returns the corresponding key if successful
sizeof - Get the number of elements in variable
sort - Sort an array
uksort - Sort an array by keys using a user-defined comparison function
usort - Sort an array by values using a user-defined comparison function
<?
function cmp ($a$b) {   
    if (
$a == $b) return 0;
    return (
$a $b) ? -1;
}

$a = array (32561);

usort ($a"cmp");
?>

array_flip - Flip all the values of an array
<?
$trans 
= array ("a" => 1"b" => 1"c" => 2);
$trans array_flip ($trans);
// now $trans is : array(1 => "b", 2 => "c");
?>

---------------

Object oriented


<?php

// base class with member properties and methods
class Vegetable {

    var 
$edible;
    var 
$color;

    function 
Vegetable$edible$color="green" ) {
        
$this->edible $edible;
        
$this->color $color;
    }

    function 
is_edible() {
        return 
$this->edible;
    }

    function 
what_color() {
        return 
$this->color;
    }
    
// end of class Vegetable


// extends the base class
class Spinach extends Vegetable {

    var 
$cooked false;

    function 
Spinach() {
        
$this->Vegetabletrue"green" );
    }

    function 
cook_it() {
        
$this->cooked true;
    }

    function 
is_cooked() {
        return 
$this->cooked;
    }
    
// end of class Spinach

$veggie = new Vegetable(true,"blue");
$leafy = new Spinach();
?>


----------------

HTML Forms


the form:
<?
//form.php file :
?>
<form action="recv.php" method="post">
    Name: <input type="text" name="username"><br>
    <input type="submit">
</form>

recv.php - the file that will recieve the data:
<?
if($username){
    echo 
"your name is $username !!! <br>";
} else { 
?>
<a href="form.php">please fill the form first !</a>
<? ?>

---------------------

"All in one" Form


same in one file (PHP style):
<?
if($username){
    echo 
"your name is $username !!! <br>";
} else { 
?>
<form action="<?= $PHP_SELF ?>" method="post">
    Name: <input type="text" name="username"><br>
    <input type="submit">
</form>
<? ?>


----------------------

opening MySQL DataBase


This is how we open and close a MySQL database:
<?php
    $link 
mysql_connect("mysql_host""mysql_login""mysql_password")
        or die (
"Could not connect");
    print (
"Connected successfully");
    
mysql_select_db ("my_database")
        or die (
"Could not select database");
    
    
$query "SELECT * FROM my_table";
    
$result mysql_query ($query) or die ("Query failed");
    
// This is where we proccess the data returned by the quary

    
mysql_close($link);
?>

mysql_num_fields($result) - Get number of fields in result
mysql_num_rows($result) - Get number of rows in result

mysql_fetch_row($result) - Get a result row as an enumerated array
mysql_fetch_array($result) - Fetch a result row as an associative array.


--------------------------------

MySQL example : guest book


we want to display a list of the other guests who signed.
We want to allow user to enter his name and comment.
This information will be stored in our MySQL DB and will
be added to the list.

1.
CREATE DATABASE gustbook
(or use existing db)

2.
Create the table containing the list.
SQL-query:
CREATE TABLE guestsign (id INT not null AUTO_INCREMENT, name TEXT not null , 
comment TEXT not null , PRIMARY KEY (id), INDEX (id), UNIQUE (id)) 

-------------------------------------------

MySQL example : guest book - the form


3.
gustbook1.php
Please sign my guestbook :
<form action="guestbook2.php" method="post">
 Name: <input type="text" name="guestname"><br>
 your comment: <input type="text" name="comment"><br>
 <input type="submit"><br>
</form>
<br>
<table border=1>
 <tr>
  <td>
   <B>name</b>
  </td>
  <td>
   <b>comment</b>
  </td>
 </tr>
<?
    $link 
mysql_connect("localhost""""")
        or die (
"Could not connect");
    
mysql_select_db ("guestbook")
        or die (
"Could not select database");
    
$query "SELECT * FROM guestsign";
    
/* you migh want to add a "LIMIT 0,30" */
    /* or maybe a "ORDER BY id DESC"*/
    
$result mysql_query ($query) or die ("Query failed");
    
$signnum mysql_num_rows($result);
    for (
$i=$i <= $signnum $i++){
         
$row_array mysql_fetch_array($result);
?>
 <tr>
  <td>
   <?= $row_array["name"?>
  </td>
  <td>
   <?= $row_array["comment"?>
  </td>
 </tr>
<?
    
}
    
mysql_close($link);
?>
</table>

-------------------------------------------

MySQL example : guest book - insert


4.
guestbook2.php
<?
    $link 
mysql_connect("localhost""""")
        or die (
"Could not connect");
    
mysql_select_db ("guestbook")
        or die (
"Could not select database");
    
$guestname stripslashes(str_replace("'","''",$guestname));
    
$comment  =  stripslashes(str_replace("'","''",$comment  ));
    
$query "insert into guestsign set name='$guestname',comment='$comment'";
    
mysql_query ($query) or die ("Query failed: $query<br>" mysql_error());
?>
Thank you for signing my guestbook !!!

-----------------------------------

GD - creating / manipulating images


With GD we can :
* Create new images .
* Load existing images and manipulate them.
* save images to disk as jpeg or png.
(gif supported only in old GD versions
- don't use unless you have to)
* resize images
* draw shapes , lines , pixels
* we can create a php file that returns
a graphical content type



-----------------

GD example : drawing graphs


graph.jpg

<?
/* We need this in order to return a picture */
header ("Content-type: image/png");

$graph_data = array(
   
"question" => "Are you addicted to PHP ?" ,
   
"yes" => 82 ,
   
"no" => 18
    
);

/* Create the images */
$im ImageCreate(200,150) or die("could not create image !! <br>");

/* allocate the colors */
$background_color ImageColorAllocate ($im200200200);
$text_color ImageColorAllocate ($im2331491);
$bar_color ImageColorAllocate ($im000);
$bar_color_fill ImageColorAllocate ($im150150255);

/* draw some text .. */
ImageFill ($im,1,1,$background_color);
ImageString ($im355,  $graph_data["question"], $text_color);
ImageString ($im230130"yes: ".$graph_data["yes"]."%" $text_color);
ImageString ($im2110130"no: ".$graph_data["no"]."%" $text_color);

/* draw the bars */
ImageRectangle ($im30120 $graph_data["yes"],50,120 ,$bar_color);
if(
$graph_data["yes"] > 2) {    #so we won't fill the bg of the image ...
       
ImageFill ($im,31,119,$bar_color_fill);
      }

ImageRectangle ($im110120 $graph_data["no"],130,120 ,$bar_color);
if(
$graph_data["yes"] > 2) {
       
ImageFill ($im,111,119,$bar_color_fill);
      }
/* returm image data */
ImagePng ($im);
?>

-----------------

Security notes


1.
<? if($pass=="NotCool") { $auth =1; } ?>
This is my secret page !
<? if($auth) { echo "My secrets .. shhhh !"; }
  else { 
?>
in order to read My secrets you must enter password : <br>
<FORM METHOD="POST" ACTION="<?= $PHP_SELF ?>">
enter password:<INPUT TYPE="PASSWORD" NAME="pass"><br>
<INPUT TYPE="SUBMIT">
</FORM>
<? ?>

2.include($libdir . "/myscript.php");

3.use is_uploaded_file() to verify upload

4.check all variable you get from get/post/cookie.
if you use one of them in a mysql query
- use :
$name1 = str_replace("'","''",$name1);
If you know you have to get a number
use is_numeric() :
if (!is_numeric($somenum)) { die("go away lammer !");}

5.block warnings and error messages -
change php.ini or use error_reporting(0)


-----------------

Links




download PHP: http://www.php.net/downloads.php
RTFM: http://www.php.net/download-docs.php

code examples: http://www.weberdev.com/
articles and forums: http://www.phpbuilder.com/
mysql: http://www.mysql.com/
Zend: http://www.zend.com/
GREAT MySQL admin tool: http://phpwizard.net/phpMyAdmin
PHP code editor for linux: http://bluefish.openoffice.nl/
PHP code editor for DOS: http://www.phpide.de/
Another PHP code editor for DOS: http://soysal.com/download2.html


---------------------

Hebrew articles



by Lior Kaplan:
Lesson no1 : http://www.guides.co.il/php/forums/msg.php?msgid=580
Lesson no2 : http://www.guides.co.il/php/forums/msg.php?msgid=827
Lesson no3 : http://www.guides.co.il/php/forums/msg.php?msgid=1184
Lesson no4 : http://www.guides.co.il/php/forums/msg.php?msgid=3504
PHP time functions: http://www.guides.co.il/php/download.php?guide=132
Hebrew and PHP: http://www.guides.co.il/php/download.php?guide=101
PHP control structures: http://www.guides.co.il/php/download.php?guide=146
PHP and MySQL: http://www.guides.co.il/php/download.php?guide=147

by Me:
PHP and Security : http://www.guides.co.il/php/forums/msg.php?msgid=3494
PHP-GTK : http://www.guides.co.il/php/forums/msg.php?msgid=3564
Regular experssions : http://www.guides.co.il/php/download.php?guide=161