Classes

A class does not define an object. It defines a template for an object. Programs can have multiple objects of the same class. Classes can inherit one another. The top most parent class is called the base class. The class doing the inheriting is the derived class.

To define a class:

<?php
	class Rectangle {
		public $width;
		public $height;
	}
?>

To instantiate the class, use the new keyword:

<?php
	class Rectangle {
		public $width;
		public $height;
	}
	$rect = new Rectangle;
	$rect->width = 25;
	$rect->height = 33;
?>

Do not use the public access modifier for data members. These should be private and then define public methods to modify them.

<?php
	class Rectangle {
		private $width;
		private $height;

		public function set_width($value) {
			$this->width = $value;
		}

		public function set_height($value) {
			$this->height = $value;
		}
	}
	$rect = new Rectangle;
	$rect->set_width(25);
	$rect->set_height(33);
?>

The class constructor is a method automatically called when a new object is created. It is named __construct. The class destructor is a method automatically called when an object is destroyed. It is named __destruct.

<?php
	class Rectangle {
		private $width;
		private $height;

		public function __construct($width, $height) {
			$this->width = $width;
			$this->height = $height;
		}

		function __destruct() {
			// close files, database connections, etc.
		}

		public function set_width($value) {
			$this->width = $value;
		}

		public function set_height($value) {
			$this->height = $value;
		}
	}
	$rect = new Rectangle(25, 33);
?>

A derived class inherits its base class through the use of the extends keyword. Here, Rectangle is the base class.

<?php
	class Rectangle {
		protected $width;
		protected $height;

		public function __construct($width, $height) {
			$this->width = $width;
			$this->height = $height;
		}

		function __destruct() {
			// close files, database connections, etc.
		}

		public function set_width($value) {
			$this->width = $value;
		}

		public function set_height($value) {
			$this->height = $value;
		}
	}

	class Box extends Rectangle {
		protected $depth;

		public function set_depth($value) {
			$this->depth = $value;
		}
	}
?>

File I/O

File I/O is important in the UNIX environment so PHP provides several functions for it.

The simpliest way to open, read and write files is through the file_get_contents and file_put_contents functions.

<?php
	$contents = file_get_contents('index.html');
	$text = strip_tags($contents); // strip_tags() is covered later
	file_put_contents('temp.txt', $text);
?>

file_get_contents also works with network sockets as it does with files.

<?php
	$contents = file_get_contents('http://www.ubuntu.com/');
	$text = strip_tags($contents); // strip_tags() is covered later
	file_put_contents('ubuntu_home_page.txt', $text);
?>

file_get_contents loads the whole file into memory which, if working with large files or have many users, is not ideal. PHP provides several functions for working with files that load the file into memory piece by piece. These functions are: fopen, fread, fwrite, feof, and fclose.

feof signals when the end-of-file is reached.

fopen is to open the file. Its first parameter is the name of the file to open. The second parameter is one of these:

  • "r" - read-only.
  • "r+" - read and write; overwrites file.
  • "w" - write-only; erases existing file contents and overwrites file.
  • "w+" - read and write; erases existing file contents and overwrites file.
  • "a" - write-only; appends to the file.
  • "a+" - read and write; appends to the file.
  • "x" - write-only; file must not exist.
  • "x+" - read and write; file must not exist.

Optionally, all of these options can be switched to binary mode by adding a "b", for example, "a+b" or "rb". This example opens a text file and outputs it piece by piece.

<?php
	$file = fopen('index.html', 'rb') or die('cannot open file');
	while(!feof($file)) {
		$bytes = fread($file, 100);
		echo $bytes;
	}
	fclose($file) or die('cannot close file');
?>

This example writes to a file using the fwrite function. It also demonstates the filesize function.

<?php
	$file = fopen('browncow.txt', 'wb') or die('cannot open file');
	fwrite($file, 'How now brown cow.');
	fclose($file) or die('cannot close file');
	$size = filesize('browncow.txt');
	echo "$size bytes written";
?>

HTML Forms

PHP has several variables available to it in the $_REQUEST, $_SERVER, $_POST and $_GET arrays.

<?php
echo '<pre>';
	foreach($_SERVER as $key => $value) {
		echo '$_SERVER['."'$key'".'] => '."$value\r\n";
	}
echo '</pre>';
?>

The previous code should produce something like this:

$_SERVER['HTTP_ACCEPT'] => text/html, application/xhtml+xml, */*
$_SERVER['HTTP_ACCEPT_LANGUAGE'] => en-US
$_SERVER['HTTP_USER_AGENT'] => Mozilla/5.0
$_SERVER['HTTP_ACCEPT_ENCODING'] => gzip, deflate
$_SERVER['HTTP_HOST'] => 192.168.1.200
$_SERVER['HTTP_DNT'] => 1
$_SERVER['HTTP_CONNECTION'] => Keep-Alive
$_SERVER['PATH'] => /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
$_SERVER['SERVER_SIGNATURE'] => Apache/2.4.7 (Ubuntu) Server at 192.168.1.200 Port 80


$_SERVER['SERVER_SOFTWARE'] => Apache/2.4.7 (Ubuntu)
$_SERVER['SERVER_NAME'] => 192.168.1.200
$_SERVER['SERVER_ADDR'] => 192.168.1.200
$_SERVER['SERVER_PORT'] => 80
$_SERVER['REMOTE_ADDR'] => 192.168.1.196
$_SERVER['DOCUMENT_ROOT'] => /var/www/html
$_SERVER['REQUEST_SCHEME'] => http
$_SERVER['CONTEXT_PREFIX'] => 
$_SERVER['CONTEXT_DOCUMENT_ROOT'] => /var/www/html
$_SERVER['SERVER_ADMIN'] => webmaster@localhost
$_SERVER['SCRIPT_FILENAME'] => /var/www/html/index.php
$_SERVER['REMOTE_PORT'] => 50784
$_SERVER['GATEWAY_INTERFACE'] => CGI/1.1
$_SERVER['SERVER_PROTOCOL'] => HTTP/1.1
$_SERVER['REQUEST_METHOD'] => GET
$_SERVER['QUERY_STRING'] => 
$_SERVER['REQUEST_URI'] => /index.php
$_SERVER['SCRIPT_NAME'] => /index.php
$_SERVER['PHP_SELF'] => /index.php
$_SERVER['REQUEST_TIME_FLOAT'] => 1507924915.46
$_SERVER['REQUEST_TIME'] => 1507924915

It is popular for one page to present the HTML form to the user and then to process the form, too. To do this, check if REQUEST_METHOD is a GET or POST. If GET then write out the HTML form. If POST then process the data submitted by the form.

The htmlentities function formats the text so that &, < and > show properly. Is the file not hard to read with PHP code interlaced with the HTML??

<html>
	<head>
		<title>HTML FORM EXAMPLE</title>
	</head>
	<body>
<?php
	if ($_SERVER['REQUEST_METHOD'] == 'GET') {
?>
	<form method="post" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>">
		<input type="text" name="name" placeholder="enter your name" />
		<input type="submit" value="say hello" />
	</form>
<?php
	} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
?>
	<p>Hello, <?php echo htmlentities($_POST['name']); ?>!</p>
<?php
	}
?>
	</body>
</html>

Here is the same file written using strings. This seems easier to read.

<?php
echo '<html><head><title>HTML FORM EXAMPLE</title></head><body>';
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
	$script = $_SERVER['SCRIPT_NAME'];
	echo '<form method="post" action="'.$script.'">';
	echo '<input type="text" name="name" placeholder="enter your name" />';
	echo '<input type="submit" value="say hello" />';
	echo '</form>';
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	$name = htmlentities($_POST['name']);
	echo "<p>Hello, $name!</p>";
}
echo '</body></html>';
?>

PHP Tips and Tricks

See the Tips and Tricks article.

<< < [Page 4 of 4] > >>