100% found this document useful (2 votes)
10 views

Learning PHP MySQL JavaScript CSS and HTML5 A Step by Step Guide to Creating Dynamic Websites 3rd Edition by Robin Nixon ISBN 1491906979 9781491906972 download

The document is a guide to learning PHP, MySQL, JavaScript, CSS, and HTML5, aimed at individuals looking to create dynamic websites. It covers the fundamentals of these technologies, their installation, and practical applications, including building a fully functional social networking site. The book is structured for beginners with a basic understanding of HTML, and includes resources for further learning and support.

Uploaded by

heilawaeles
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
10 views

Learning PHP MySQL JavaScript CSS and HTML5 A Step by Step Guide to Creating Dynamic Websites 3rd Edition by Robin Nixon ISBN 1491906979 9781491906972 download

The document is a guide to learning PHP, MySQL, JavaScript, CSS, and HTML5, aimed at individuals looking to create dynamic websites. It covers the fundamentals of these technologies, their installation, and practical applications, including building a fully functional social networking site. The book is structured for beginners with a basic understanding of HTML, and includes resources for further learning and support.

Uploaded by

heilawaeles
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

Learning PHP MySQL JavaScript CSS and HTML5 A

Step by Step Guide to Creating Dynamic Websites


3rd Edition by Robin Nixon ISBN 1491906979
9781491906972 download
https://ebookball.com/product/learning-php-mysql-javascript-css-
and-html5-a-step-by-step-guide-to-creating-dynamic-websites-3rd-
edition-by-robin-nixon-isbn-1491906979-9781491906972-15996/

Instantly Access and Download Textbook at https://ebookball.com


Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

Machine Learning Step by Step Guide To Implement Machine Learning


Algorithms with Python 1st Edition by Rudolph Russell ISBN
9781719528405

https://ebookball.com/product/machine-learning-step-by-step-
guide-to-implement-machine-learning-algorithms-with-python-1st-
edition-by-rudolph-russell-isbn-9781719528405-16086/

Learning Web Design A Beginner Guide to HTML CSS JavaScript and Web
Graphics 5th Edition by Jennifer Niederst Robbins ISBN 1491960159
9781491960158

https://ebookball.com/product/learning-web-design-a-beginner-
guide-to-html-css-javascript-and-web-graphics-5th-edition-by-
jennifer-niederst-robbins-isbn-1491960159-9781491960158-16006/

Research Methodology A Step By Step Guide for Beginners 3rd Edition by


Ranjit Kumar 1849203016 978-1849203012

https://ebookball.com/product/research-methodology-a-step-by-
step-guide-for-beginners-3rd-edition-by-ranjit-
kumar-1849203016-978-1849203012-17356/

Teaching Psychology A Step by Step Guide 3rd edition by Douglas


Bernstein, Sue Frantz, Stephen Chew 9780367143947

https://ebookball.com/product/teaching-psychology-a-step-by-step-
guide-3rd-edition-by-douglas-bernstein-sue-frantz-stephen-
chew-9780367143947-15176/
Excel VBA Step By Step Guide to Learning Excel Programming Language
for Beginners 1st Edition by Jason Jay ISBN 1976198127 9781976198120

https://ebookball.com/product/excel-vba-step-by-step-guide-to-
learning-excel-programming-language-for-beginners-1st-edition-by-
jason-jay-isbn-1976198127-9781976198120-15878/

Java Easy Java Programming for Beginners Step By Step Guide to


Learning Java 1st Edition by Felix Alvaro ISBN 1539509362
9781539509363

https://ebookball.com/product/java-easy-java-programming-for-
beginners-step-by-step-guide-to-learning-java-1st-edition-by-
felix-alvaro-isbn-1539509362-9781539509363-15874/

How to Use SPSS A Step By Step Guide to Analysis and Interpretation


4th Edition by Brian Cronk 188458568X 978-1884585685

https://ebookball.com/product/how-to-use-spss-a-step-by-step-
guide-to-analysis-and-interpretation-4th-edition-by-brian-
cronk-188458568x-978-1884585685-14632/

Java programming A beginners guide to java Step by Step 1st Edition


by Troy Dimes 1507562942 978-1507562949

https://ebookball.com/product/java-programming-a-beginners-guide-
to-java-step-by-step-1st-edition-by-troy-
dimes-1507562942-978-1507562949-17382/

Learning PHP and MySQL 1st edition by Davis, Michele, Phillips, Jon
9780596101107, 0596101104

https://ebookball.com/product/learning-php-and-mysql-1st-edition-
by-davis-michele-phillips-jon-9780596101107-0596101104-12444/
Learning PHP, MySQL,
JavaScript, CSS & HTML5

Robin Nixon
DEDICATION

For Julie
Preface

The combination of PHP and MySQL is the most convenient


approach to dynamic, database-driven web design, holding its own
in the face of challenges from integrated frameworks—such as Ruby
on Rails—that are harder to learn. Due to its open source roots
(unlike the competing Microsoft .NET Framework), it is free to
implement and is therefore an extremely popular option for web
development.
Any would-be developer on a Unix/Linux or even a Windows/Apache
platform will need to master these technologies. And, combined with
the partner technologies of JavaScript, CSS, and HTML5, you will be
able to create websites of the caliber of industry standards like
Facebook, Twitter, and Gmail.

Audience
This book is for people who wish to learn how to create effective and
dynamic websites. This may include webmasters or graphic
designers who are already creating static websites but wish to take
their skills to the next level, as well as high school and college
students, recent graduates, and self-taught individuals.
In fact, anyone ready to learn the fundamentals behind the Web 2.0
technology known as Ajax will obtain a thorough grounding in all of
these core technologies: PHP, MySQL, JavaScript, CSS, and HTML5.
Assumptions This Book Makes
This book assumes that you have a basic understanding of HTML
and can at least put together a simple, static website, but does not
assume that you have any prior knowledge of PHP, MySQL,
JavaScript, CSS, or HTML5—although if you do, your progress
through the book will be even quicker.

Organization of This Book


The chapters in this book are written in a specific order, first
introducing all of the core technologies it covers and then walking
you through their installation on a web development server so that
you will be ready to work through the examples.
In the first section, you will gain a grounding in the PHP
programming language, covering the basics of syntax, arrays,
functions, and object-oriented programming.
Then, with PHP under your belt, you will move on to an introduction
to the MySQL database system, where you will learn everything from
how MySQL databases are structured to how to generate complex
queries.
After that, you will learn how you can combine PHP and MySQL to
start creating your own dynamic web pages by integrating forms and
other HTML features. Following that, you will get down to the nitty-
gritty practical aspects of PHP and MySQL development by learning a
variety of useful functions and how to manage cookies and sessions,
as well as how to maintain a high level of security.
In the next few chapters, you will gain a thorough grounding in
JavaScript, from simple functions and event handling to accessing
the Document Object Model and in-browser validation and error
handling.
With an understanding of all three of these core technologies, you
will then learn how to make behind-the-scenes Ajax calls and turn
your websites into highly dynamic environments.
Next, you’ll spend two chapters learning all about using CSS to style
and lay out your web pages, before moving on to the final section on
the new features built into HTML5, including geolocation, audio,
video, and the canvas. After this, you’ll put together everything
you’ve learned in a complete set of programs that together
constitute a fully functional social networking website.
Along the way, you’ll also find plenty of pointers and advice on good
programming practices and tips that could help you find and solve
hard-to-detect programming errors. There are also plenty of links to
websites containing further details on the topics covered.

Supporting Books
Once you have learned to develop using PHP, MySQL, JavaScript,
CSS, and HTML5, you will be ready to take your skills to the next
level using the following O’Reilly reference books. To learn more
about any of these titles, simply search the O’Reilly website or any
good online book seller’s website:
Dynamic HTML: The Definitive Reference by Danny Goodman

PHP in a Nutshell by Paul Hudson

MySQL in a Nutshell by Russell J.T. Dyer

JavaScript: The Definitive Guide by David Flanagan

CSS: The Definitive Guide by Eric A. Meyer

HTML5: The Missing Manual by Matthew MacDonald


Conventions Used in This Book
The following typographical conventions are used in this book:
Plain text
Indicates menu titles, options, and buttons.

Italic
Indicates new terms, URLs, email addresses, filenames, file
extensions, pathnames, directories, and Unix utilities.

Constant width
Indicates command-line options, variables and other code
elements, HTML tags, macros, and the contents of files.

Constant width bold


Shows program output or highlighted sections of code that are
being discussed in the text.

Constant width italic


Shows text that should be replaced with user-supplied values.

NOTE
This element signifies a tip, suggestion, or general note.

WARNING
This element indicates a warning or caution.
Using Code Examples
Supplemental material (code examples, exercises, etc.) is available
at http://lpmj.net.
This book is here to help you get your job done. In general, if
example code is offered with this book, you may use it in your
programs and documentation. You do not need to contact us for
permission unless you’re reproducing a significant portion of the
code. For example, writing a program that uses several chunks of
code from this book does not require permission. Selling or
distributing a CD-ROM of examples from O’Reilly books does require
permission. Answering a question by citing this book and quoting
example code does not require permission. Incorporating a
significant amount of example code from this book into your
product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually
includes the title, author, publisher, and ISBN. For example:
“Learning PHP, MySQL, JavaScript, CSS & HTML5, Third Edition, by
Robin Nixon. Copyright 2014 Robin Nixon, 978-1-4919-4946-7.”
If you feel your use of code examples falls outside fair use or the
permission given here, feel free to contact us at
[email protected].

We’d Like to Hear from You


Every example in this book has been tested on various platforms,
but occasionally you may encounter problems—for example, if you
have a nonstandard installation or a different version of PHP. The
information in this book has also been verified at each step of the
production process. However, mistakes and oversights can occur and
we will gratefully receive details of any you find, as well as any
suggestions you would like to make for future editions. You can
contact the author and editors at:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 998-9938 (in the United States or Canada)
(707) 829-0515 (international or local)
(707) 829-0104 (fax)

We have a web page for this book, where we list errata, examples,
and any additional information. You can access this page at
http://bit.ly/lpmjch_3e.
There is also a companion website to this book at http://lpmj.net,
where you can download all the examples from this book in a single
zip file.
To comment or ask technical questions about this book, send email
to [email protected].
For more information about our books, courses, conferences, and
news, see our website at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia

Safari® Books Online


Safari Books Online (www.safaribooksonline.com) is an on-demand
digital library that delivers expert content in both book and video
form from the world’s leading authors in technology and business.
Technology professionals, software developers, web designers, and
business and creative professionals use Safari Books Online as their
primary resource for research, problem solving, learning, and
certification training.
Safari Books Online offers a range of product mixes and pricing
programs for organizations, government agencies, and individuals.
Subscribers have access to thousands of books, training videos, and
prepublication manuscripts in one fully searchable database from
publishers like O’Reilly Media, Prentice Hall Professional, Addison-
Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press,
Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan
Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress,
Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course
Technology, and dozens more. For more information about Safari
Books Online, please visit us online.

Acknowledgments
I would like to once again thank my editor, Andy Oram, and
everyone who worked so hard on this book, including Albert Wiersch
for his comprehensive technical review, Kristen Brown for overseeing
production, Rachel Monaghan for her copyediting, Jasmine Kwityn
for proofreading, Robert Romano for his original illustrations,
Rebecca Demarest for her new illustrations, David Futato for interior
design, Lucie Haskins for creating the index, Karen Montgomery for
the original sugar glider front cover design, Randy Comer for the
latest book cover, and everyone else too numerous to name who
submitted errata and offered suggestions for this new edition.
Chapter 1. Introduction to
Dynamic Web Content

The World Wide Web is a constantly evolving network that has


already traveled far beyond its conception in the early 1990s, when
it was created to solve a specific problem. State-of-the-art
experiments at CERN (the European Laboratory for Particle Physics—
now best known as the operator of the Large Hadron Collider) were
producing incredible amounts of data—so much that the data was
proving unwieldy to distribute to the participating scientists who
were spread out across the world.
At this time, the Internet was already in place, with several hundred
thousand computers connected to it, so Tim Berners-Lee (a CERN
fellow) devised a method of navigating between them using a
hyperlinking framework, which came to be known as Hypertext
Transfer Protocol, or HTTP. He also created a markup language
called HTML, or Hypertext Markup Language. To bring these
together, he wrote the first web browser and web server, tools that
we now take for granted.
But back then, the concept was revolutionary. The most connectivity
so far experienced by at-home modem users was dialing up and
connecting to a bulletin board that was hosted by a single computer,
where you could communicate and swap data only with other users
of that service. Consequently, you needed to be a member of many
bulletin board systems in order to effectively communicate
electronically with your colleagues and friends.
But Berners-Lee changed all that in one fell swoop, and by the mid-
1990s, there were three major graphical web browsers competing
for the attention of five million users. It soon became obvious,
though, that something was missing. Yes, pages of text and graphics
with hyperlinks to take you to other pages was a brilliant concept,
but the results didn’t reflect the instantaneous potential of
computers and the Internet to meet the particular needs of each
user with dynamically changing content. Using the Web was a very
dry and plain experience, even if we did now have scrolling text and
animated GIFs!
Shopping carts, search engines, and social networks have clearly
altered how we use the Web. In this chapter, we’ll take a brief look
at the various components that make up the Web, and the software
that helps make it a rich and dynamic experience.

NOTE
It is necessary to start using some acronyms more or less right away. I
have tried to clearly explain them before proceeding. But don’t worry
too much about what they stand for or what these names mean,
because the details will all become clear as you read on.

HTTP and HTML: Berners-Lee’s Basics


HTTP is a communication standard governing the requests and
responses that take place between the browser running on the end
user’s computer and the web server. The server’s job is to accept a
request from the client and attempt to reply to it in a meaningful
way, usually by serving up a requested web page—that’s why the
term server is used. The natural counterpart to a server is a client,
so that term is applied both to the web browser and the computer
on which it’s running.
Between the client and the server there can be several other
devices, such as routers, proxies, gateways, and so on. They serve
different roles in ensuring that the requests and responses are
correctly transferred between the client and server. Typically, they
use the Internet to send this information.
A web server can usually handle multiple simultaneous connections
and—when not communicating with a client—spends its time
listening for an incoming connection. When one arrives, the server
sends back a response to confirm its receipt.

The Request/Response Procedure


At its most basic level, the request/response process consists of a
web browser asking the web server to send it a web page and the
server sending back the page. The browser then takes care of
displaying the page (see Figure 1-1).
Figure 1-1. The basic client/server request/response sequence

Each step in the request and response sequence is as follows:


1. You enter http://server.com into your browser’s address bar.

2. Your browser looks up the IP address for server.com.

3. Your browser issues a request for the home page at server.com.

4. The request crosses the Internet and arrives at the server.com


web server.
5. The web server, having received the request, looks for the web
page on its hard disk.

6. The web page is retrieved by the server and returned to the


browser.

7. Your browser displays the web page.


For an average web page, this process takes place once for each
object within the page: a graphic, an embedded video or Flash file,
and even a CSS template.
In step 2, notice that the browser looked up the IP address of
server.com. Every machine attached to the Internet has an IP
address—your computer included. But we generally access web
servers by name, such as google.com. As you probably know, the
browser consults an additional Internet service called the Domain
Name Service (DNS) to find its associated IP address and then uses
it to communicate with the computer.
For dynamic web pages, the procedure is a little more involved,
because it may bring both PHP and MySQL into the mix (see
Figure 1-2).
Figure 1-2. A dynamic client/server request/response sequence

Here are the steps for a dynamic client/server request/response


sequence:
1. You enter http://server.com into your browser’s address bar.

2. Your browser looks up the IP address for server.com.

3. Your browser issues a request to that address for the web


server’s home page.
4. The request crosses the Internet and arrives at the server.com
web server.

5. The web server, having received the request, fetches the home
page from its hard disk.

6. With the home page now in memory, the web server notices
that it is a file incorporating PHP scripting and passes the page
to the PHP interpreter.

7. The PHP interpreter executes the PHP code.

8. Some of the PHP contains MySQL statements, which the PHP


interpreter now passes to the MySQL database engine.

9. The MySQL database returns the results of the statements back


to the PHP interpreter.

10. The PHP interpreter returns the results of the executed PHP
code, along with the results from the MySQL database, to the
web server.

11. The web server returns the page to the requesting client, which
displays it.
Although it’s helpful to be aware of this process so that you know
how the three elements work together, in practice you don’t really
need to concern yourself with these details, because they all happen
automatically.
HTML pages returned to the browser in each example may well
contain JavaScript, which will be interpreted locally by the client, and
which could initiate another request—the same way embedded
objects such as images would.
The Benefits of PHP, MySQL, JavaScript, CSS,
and HTML5
At the start of this chapter, I introduced the world of Web 1.0, but it
wasn’t long before the rush was on to create Web 1.1, with the
development of such browser enhancements as Java, JavaScript,
JScript (Microsoft’s slight variant of JavaScript), and ActiveX. On the
server side, progress was being made on the Common Gateway
Interface (CGI) using scripting languages such as Perl (an alternative
to the PHP language) and server-side scripting—inserting the
contents of one file (or the output of a system call) into another one
dynamically.
Once the dust had settled, three main technologies stood head and
shoulders above the others. Although Perl was still a popular
scripting language with a strong following, PHP’s simplicity and built-
in links to the MySQL database program had earned it more than
double the number of users. And JavaScript, which had become an
essential part of the equation for dynamically manipulating CSS
(Cascading Style Sheets) and HTML, now took on the even more
muscular task of handling the client side of the Ajax process. Under
Ajax, web pages perform data handling and send requests to web
servers in the background—without the web user being aware that
this is going on.
No doubt the symbiotic nature of PHP and MySQL helped propel
them both forward, but what attracted developers to them in the
first place? The simple answer has to be the ease with which you
can use them to quickly create dynamic elements on websites.
MySQL is a fast and powerful, yet easy-to-use, database system that
offers just about anything a website would need in order to find and
serve up data to browsers. When PHP allies with MySQL to store and
retrieve this data, you have the fundamental parts required for the
development of social networking sites and the beginnings of Web
2.0.
And when you bring JavaScript and CSS into the mix too, you have a
recipe for building highly dynamic and interactive websites.

Using PHP
With PHP, it’s a simple matter to embed dynamic activity in web
pages. When you give pages the .php extension, they have instant
access to the scripting language. From a developer’s point of view,
all you have to do is write code such as the following:

<?php
echo " Today is " . date("l") . ". ";
?>

Here's the latest news.

The opening <?php tells the web server to allow the PHP program to
interpret all the following code up to the ?> tag. Outside of this
construct, everything is sent to the client as direct HTML. So the text
Here's the latest news. is simply output to the browser; within
the PHP tags, the built-in date function displays the current day of
the week according to the server’s system time.
The final output of the two parts looks like this:

Today is Wednesday. Here's the latest news.

PHP is a flexible language, and some people prefer to place the PHP
construct directly next to PHP code, like this:

Today is <?php echo date("l"); ?>. Here's the latest news.

There are also other ways of formatting and outputting information,


which I’ll explain in the chapters on PHP. The point is that with PHP,
web developers have a scripting language that, although not as fast
as compiling your code in C or a similar language, is incredibly
speedy and also integrates seamlessly with HTML markup.

NOTE
If you intend to enter the PHP examples in this book to work along with
me, you must remember to add <?php in front and ?> after them to
ensure that the PHP interpreter processes them. To facilitate this, you
may wish to prepare a file called example.php with those tags in place.

Using PHP, you have unlimited control over your web server.
Whether you need to modify HTML on the fly, process a credit card,
add user details to a database, or fetch information from a third-
party website, you can do it all from within the same PHP files in
which the HTML itself resides.

Using MySQL
Of course, there’s not much point to being able to change HTML
output dynamically unless you also have a means to track the
changes that users make as they use your website. In the early days
of the Web, many sites used “flat” text files to store data such as
usernames and passwords. But this approach could cause problems
if the file wasn’t correctly locked against corruption from multiple
simultaneous accesses. Also, a flat file can get only so big before it
becomes unwieldy to manage—not to mention the difficulty of trying
to merge files and perform complex searches in any kind of
reasonable time.
That’s where relational databases with structured querying become
essential. And MySQL, being free to use and installed on vast
numbers of Internet web servers, rises superbly to the occasion. It is
a robust and exceptionally fast database management system that
uses English-like commands.
The highest level of MySQL structure is a database, within which you
can have one or more tables that contain your data. For example,
let’s suppose you are working on a table called users, within which
you have created columns for surname, firstname, and email, and
you now wish to add another user. One command that you might
use to do this is:

INSERT INTO users VALUES('Smith', 'John', '[email protected]');

Of course, as mentioned earlier, you will have issued other


commands to create the database and table and to set up all the
correct fields, but the INSERT command here shows how simple it
can be to add new data to a database. The INSERT command is an
example of SQL (Structured Query Language), a language designed
in the early 1970s and reminiscent of one of the oldest programming
languages, COBOL. It is well suited, however, to database queries,
which is why it is still in use after all this time.
It’s equally easy to look up data. Let’s assume that you have an
email address for a user and need to look up that person’s name. To
do this, you could issue a MySQL query such as:

SELECT surname,firstname FROM users WHERE email='[email protected]';

MySQL will then return Smith, John and any other pairs of names
that may be associated with that email address in the database.
As you’d expect, there’s quite a bit more that you can do with
MySQL than just simple INSERT and SELECT commands. For example,
you can join multiple tables according to various criteria, ask for
results in a variety of orders, make partial matches when you know
only part of the string that you are searching for, return only the nth
result, and a lot more.
Using PHP, you can make all these calls directly to MySQL without
having to run the MySQL program yourself or use its command-line
interface. This means you can save the results in arrays for
processing and perform multiple lookups, each dependent on the
results returned from earlier ones, to drill right down to the item of
data you need.
For even more power, as you’ll see later, there are additional
functions built right into MySQL that you can call up for common
operations and extra speed.

Using JavaScript
The oldest of the three core technologies in this book, JavaScript,
was created to enable scripting access to all the elements of an
HTML document. In other words, it provides a means for dynamic
user interaction such as checking email address validity in input
forms, displaying prompts such as “Did you really mean that?”, and
so on (note, however, that it cannot be relied upon for security,
which should always be performed on the web server).
Combined with CSS (see the following section), JavaScript is the
power behind dynamic web pages that change in front of your eyes
rather than when a new page is returned by the server.
However, JavaScript can also be tricky to use, due to some major
differences in the ways different browser designers have chosen to
implement it. This mainly came about when some manufacturers
tried to put additional functionality into their browsers at the
expense of compatibility with their rivals.
Thankfully, the developers have mostly now come to their senses
and have realized the need for full compatibility with one another, so
they don’t have to write multi-exception code. But there remain
millions of legacy browsers that will be in use for a good many years
to come. Luckily, there are solutions for the incompatibility problems,
and later in this book we’ll look at libraries and techniques that
enable you to safely ignore these differences.
For now, let’s take a quick look at how you can use basic JavaScript,
accepted by all browsers:

<script type="text/javascript">
document.write("Today is " + Date() );
</script>

This code snippet tells the web browser to interpret everything


within the script tags as JavaScript, which the browser then does
by writing the text Today is to the current document, along with the
date, by using the JavaScript function Date. The result will look
something like this:

Today is Sun Jan 01 2017 01:23:45

NOTE
Unless you need to specify an exact version of JavaScript, you can
normally omit the type="text/javascript" and just use <script> to
start the interpretation of the JavaScript.

As previously mentioned, JavaScript was originally developed to offer


dynamic control over the various elements within an HTML
document, and that is still its main use. But more and more,
JavaScript is being used for Ajax. This is a term for the process of
accessing the web server in the background. (It originally meant
“Asynchronous JavaScript and XML,” but that phrase is already a bit
outdated.)
Ajax is the main process behind what is now known as Web 2.0 (a
term popularized by Tim O’Reilly, the founder and CEO of this book’s
publishing company), in which web pages have started to resemble
standalone programs, because they don’t have to be reloaded in
their entirety. Instead, a quick Ajax call can pull in and update a
single element on a web page, such as changing your photograph on
a social networking site or replacing a button that you click with the
answer to a question. This subject is fully covered in Chapter 18.

Using CSS
With the emergence of the CSS3 standard in recent years, CSS now
offers a level of dynamic interactivity previously supported only by
JavaScript. For example, not only can you style any HTML element to
change its dimensions, colors, borders, spacing, and so on, but now
you can also add animated transitions and transformations to your
web pages, using only a few lines of CSS.
Using CSS can be as simple as inserting a few rules between
<style> and </style> tags in the head of a web page, like this:

<style>
p {
text-align:justify;
font-family:Helvetica;
}
</style>

These rules will change the default text alignment of the <p> tag so
that paragraphs contained in it will be fully justified and will use the
Helvetica font.
As you’ll learn in Chapter 19, there are many different ways you can
lay out CSS rules, and you can also include them directly within tags
or save a set of rules to an external file to be loaded in separately.
This flexibility not only lets you style your HTML precisely, but it can
also, for example, provide built-in hover functionality to animate
objects as the mouse passes over them. You will also learn how to
access all of an element’s CSS properties from JavaScript as well as
HTML.
And Then There’s HTML5
As useful as all these additions to the web standards became, they
were not enough for ever more ambitious developers. For example,
there was still no simple way to manipulate graphics in a web
browser without resorting to plug-ins such as Flash. And the same
went for inserting audio and video into web pages. Plus, several
annoying inconsistencies had crept into HTML during its evolution.
So, to clear all this up and take the Internet beyond Web 2.0 and
into its next iteration, a new standard for HTML was created to
address all these shortcomings. It was called HTML5 and it began
development as long ago as 2004, when the first draft was drawn up
by the Mozilla Foundation and Opera Software (developers of two
popular web browsers). But it wasn’t until the start of 2013 that the
final draft was submitted to the World Wide Web Consortium (W3C),
the international governing body for web standards.
With nine years for it to develop, you might think that would be the
end of the specification, but that’s not how things work on the
Internet. Although websites come and go at great speed, the
underlying software is developed slowly and carefully, and so the
stable recommendation for HTML5 is not expected until after this
edition of the book has been published—in late 2014. And then
guess what? Work will move on to versions 5.1 and higher,
beginning in 2015. It’s a never-ending cycle of development.
However, while HTML5.1 is planned to bring some handy
improvements (mainly to the canvas), basic HTML5 is the new
standard web developers now need to work to, and it will remain in
place for many years to come. So learning everything you can about
it now will stand you in very good stead.
There’s actually a great deal of new stuff in HTML (and quite a few
things that have been changed or removed), but in summary, here’s
what you get:
Markup
Including new elements such as <nav> and <footer>, and
deprecated elements like <font> and <center>.

New APIs
For example, the <canvas> element for writing and drawing on a
graphics canvas, <audio> and <video> elements, offline web
apps, microdata, and local storage.

Applications
Including two new rendering technologies: MathML (Math
Markup Language) for displaying mathematical formulae) and
SVG (Scalable Vector Graphics) for creating graphical elements
outside of the new <canvas> element. However, MathML and SVG
are somewhat specialist, and are so feature-packed they would
need a book of their own, so I don’t cover them here.
All these things (and more) are covered in detail starting in
Chapter 22.

NOTE
One of the little things I like about the HTML5 specification is that
XHTML syntax is no longer required for self-closing elements. In the
past you could display a line break using the <br> element. Then, to
ensure future compatibility with XHTML (the planned replacement for
HTML that never happened), this was changed to <br />, in which a
closing / character was added (because all elements were expected to
include a closing tag featuring this character). But now things have
gone full circle, and you can use either version of these element types.
So, for the sake of brevity and fewer keystrokes, in this book I have
reverted to the former style of <br>, <hr>, and so on.
The Apache Web Server
In addition to PHP, MySQL, JavaScript, CSS, and HTML5, there’s
actually a sixth hero in the dynamic Web: the web server. In the
case of this book, that means the Apache web server. We’ve
discussed a little of what a web server does during the HTTP
server/client exchange, but it actually does much more behind the
scenes.
For example, Apache doesn’t serve up just HTML files—it handles a
wide range of files from images and Flash files to MP3 audio files,
RSS (Really Simple Syndication) feeds, and so on. To do this, each
element a web client encounters in an HTML page is also requested
from the server, which then serves it up.
But these objects don’t have to be static files such as GIF images.
They can all be generated by programs such as PHP scripts. That’s
right: PHP can even create images and other files for you, either on
the fly or in advance to serve up later.
To do this, you normally have modules either precompiled into
Apache or PHP or called up at runtime. One such module is the GD
(Graphics Draw) library, which PHP uses to create and handle
graphics.
Apache also supports a huge range of modules of its own. In
addition to the PHP module, the most important for your purposes
as a web programmer are the modules that handle security. Other
examples are the Rewrite module, which enables the web server to
handle a varying range of URL types and rewrite them to its own
internal requirements, and the Proxy module, which you can use to
serve up often-requested pages from a cache to ease the load on
the server.
Later in the book, you’ll see how to actually use some of these
modules to enhance the features provided by the three core
technologies.
About Open Source
Whether the open source quality of these technologies is the reason
they are so popular has often been debated, but PHP, MySQL, and
Apache are the three most commonly used tools in their categories.
What can be said definitively, though, is that their being open source
means that they have been developed in the community by teams of
programmers writing the features they themselves want and need,
with the original code available for all to see and change. Bugs can
be found and security breaches can be prevented before they
happen.
There’s another benefit: all these programs are free to use. There’s
no worrying about having to purchase additional licenses if you have
to scale up your website and add more servers. And you don’t need
to check the budget before deciding whether to upgrade to the
latest versions of these products.

Bringing It All Together


The real beauty of PHP, MySQL, JavaScript, CSS, and HTML5 is the
wonderful way in which they all work together to produce dynamic
web content: PHP handles all the main work on the web server,
MySQL manages all the data, and the combination of CSS and
JavaScript looks after web page presentation. JavaScript can also
talk with your PHP code on the web server whenever it needs to
update something (either on the server or on the web page). And
with the powerful new features in HTML5, such as the canvas, audio
and video, and geolocation, you can make your web pages highly
dynamic, interactive, and multimedia packed.
Without using program code, let’s summarize the contents of this
chapter by looking at the process of combining some of these
technologies into an everyday Ajax feature that many websites use:
checking whether a desired username already exists on the site
when a user is signing up for a new account. A good example of this
can be seen with Gmail (see Figure 1-3).

Figure 1-3. Gmail uses Ajax to check the availability of usernames

The steps involved in this Ajax process would be similar to the


following:
1. The server outputs the HTML to create the web form, which
asks for the necessary details, such as username, first name,
last name, and email address.

2. At the same time, the server attaches some JavaScript to the


HTML to monitor the username input box and check for two
things: (a) whether some text has been typed into it, and (b)
whether the input has been deselected because the user has
clicked on another input box.

3. Once the text has been entered and the field deselected, in the
background the JavaScript code passes the username that was
entered back to a PHP script on the web server and awaits a
response.

4. The web server looks up the username and replies back to the
JavaScript regarding whether that name has already been
taken.

5. The JavaScript then places an indication next to the username


input box to show whether the name is one available to the
user—perhaps a green checkmark or a red cross graphic, along
with some text.

6. If the username is not available and the user still submits the
form, the JavaScript interrupts the submission and
reemphasizes (perhaps with a larger graphic and/or an alert
box) that the user needs to choose another username.

7. Optionally, an improved version of this process could even look


at the username requested by the user and suggest an
alternative that is currently available.
All of this takes place quietly in the background and makes for a
comfortable and seamless user experience. Without Ajax, the entire
form would have to be submitted to the server, which would then
send back HTML, highlighting any mistakes. It would be a workable
solution, but nowhere near as tidy or pleasurable as on-the-fly form
field processing.
Ajax can be used for a lot more than simple input verification and
processing, though; we’ll explore many additional things that you
can do with it in the Ajax chapters later in this book.
In this chapter, you have read a good introduction to the core
technologies of PHP, MySQL, JavaScript, CSS, and HTML5 (as well as
Apache), and have learned how they work together. In Chapter 2,
we’ll look at how you can install your own web development server
on which to practice everything that you will be learning.
Questions
1. What four components (at the minimum) are needed to create
a fully dynamic web page?

2. What does HTML stand for?

3. Why does the name MySQL contain the letters SQL?

4. PHP and JavaScript are both programming languages that


generate dynamic results for web pages. What is their main
difference, and why would you use both of them?

5. What does CSS stand for?

6. List three major new elements introduced in HTML5.

7. If you encounter a bug (which is rare) in one of the open


source tools, how do you think you could get it fixed?

See Chapter 1 Answers in Appendix A for the answers to these


questions.
Chapter 2. Setting Up a
Development Server

If you wish to develop Internet applications but don’t have your own
development server, you will have to upload every modification you
make to a server somewhere else on the Web before you can test it.
Even on a fast broadband connection, this can still represent a
significant slowdown in development time. On a local computer,
however, testing can be as easy as saving an update (usually just a
matter of clicking once on an icon) and then hitting the Refresh button
in your browser.
Another advantage of a development server is that you don’t have to
worry about embarrassing errors or security problems while you’re
writing and testing, whereas you need to be aware of what people
may see or do with your application when it’s on a public website. It’s
best to iron everything out while you’re still on a home or small office
system, presumably protected by firewalls and other safeguards.
Once you have your own development server, you’ll wonder how you
ever managed without one, and it’s easy to set one up. Just follow the
steps in the following sections, using the appropriate instructions for a
PC, a Mac, or a Linux system.
In this chapter, we cover just the server side of the web experience,
as described in Chapter 1. But to test the results of your work—
particularly when we start using JavaScript, CSS, and HTML5 later in
this book—you should also have an instance of every major web
browser running on some system convenient to you. Whenever
possible, the list of browsers should include at least Internet Explorer,
Mozilla Firefox, Opera, Safari, and Google Chrome.
If you plan to ensure your sites look good on mobile devices too, then
you should also try to arrange access to a wide range of Apple iOS
and Google Android phones and tablets.

What Is a WAMP, MAMP, or LAMP?


WAMP, MAMP, and LAMP are abbreviations for “Windows, Apache,
MySQL, and PHP,” “Mac, Apache, MySQL, and PHP,” and “Linux,
Apache, MySQL, and PHP.” These abbreviations describe a fully
functioning setup used for developing dynamic Internet web pages.
WAMPs, MAMPs, and LAMPs come in the form of a package that binds
the bundled programs together so that you don’t have to install and
set them up separately. This means you can simply download and
install a single program, and follow a few easy prompts, to get your
web development server up and running in the quickest time with a
minimum hassle.
During installation, several default settings are created for you. The
security configurations of such an installation will not be as tight as on
a production web server, because it is optimized for local use. For
these reasons, you should never install such a setup as a production
server.
But for developing and testing websites and applications, one of these
installations should be entirely sufficient.

WARNING
If you choose not to go the WAMP/MAMP/LAMP route for building your
own development system, you should know that downloading and
integrating the various parts yourself can be very time-consuming and
may require a lot of research in order to configure everything fully. But if
you already have all the components installed and integrated with one
another, they should work with the examples in this book.
Installing a WAMP on Windows
There are several available WAMP servers, each offering slightly
different configurations, but the best is probably Zend Server Free
Edition, because it’s free and is from the developers of PHP itself. You
can download it at http://tinyurl.com/zendfree, as shown in Figure 2-
1.

NOTE
Throughout this book, whenever there’s a long URL to type, I use the
TinyURL web address shortening service to save you time and reduce
typos. For example, the URLs http://tinyurl.com/zendfree and
http://tinyurl.com/zenddocs are much shorter than the URLs that they
lead to:
http://www.zend.com/en/products/server/free-edition

http://files.zend.com/help/Zend-Server-6/zend-server.htm
Figure 2-1. You can download the Free Edition from the Zend website

I recommend that you always download the latest stable release (in
this instance, it’s 6.3.0/PHP 5.5 for Windows). It will probably be listed
first in the Download section of the web page, which should display
the correct installer for your computer out of Linux, Windows OS X,
and IBM i.

NOTE
During the lifetime of this edition, some of the screens and options shown
in the following walkthrough may change. If so, just use your common
sense to proceed in as similar a manner as possible to the sequence of
actions described.

Once you’ve downloaded the installer, run it to bring up the window


shown in Figure 2-2.
Figure 2-2. The main installation window of the installer

Click Next and accept the license agreement that follows to move on
to the Setup Type screen (see Figure 2-3), then select the Custom
option so that the MySQL server can also be installed.
Figure 2-3. Choose the Custom install option

When the Custom Setup window appears, scroll down the list of
options to the bottom and ensure that MySQL Server is checked, as
shown in Figure 2-4, then click Next.
Figure 2-4. Check MySQL Server before continuing

On the following screen (see Figure 2-5), even if you already have an
IIS web server installed, I recommend that you choose to install the
Apache web server, because the examples in this book are for Apache.
Then click Next.
Figure 2-5. Install the Apache web server

Now accept the default values of 80 for the Web Server Port, and
10081 for the Zend Server Interface Port (see Figure 2-6) and click
Next.

NOTE
If either of the ports offered states that it is occupied (generally this will
be because you have another web server running) and doesn’t allow you
to use the defaults, then try a value of 8080 (or 8000) for the Web Server
Port, and 10082 for the Zend Server Interface Port. You’ll need to
remember these values for later when you’re accessing either web pages
or the Zend server. For example, instead of visiting localhost/index.htm in
your web browser, you would use localhost:8080/index.htm.
Figure 2-6. Accept the default values offered for the ports

Once the ports have been assigned, you will reach the screen in
Figure 2-7, where you should click Install to start the installation.
Figure 2-7. Now you are ready to click Install to proceed

During installation some extra files may be downloaded, so it may


take a few minutes for the programs to get set up. During installation
you might also see a pop-up dialog box from Windows Firewall. If so,
accept the request to give it access. When the files have been
installed, you will be notified and prompted to start using the software
by clicking Finish. When you do so, your default browser will be
opened with the page shown in Figure 2-8, where, to continue, you
must check the box to agree with the terms.
Figure 2-8. You must agree to the terms in order to use the server

Next, you are asked how you will be using the server. I recommend
that you select the Development option for the purposes of working
through the exercises in this book (see Figure 2-9).
Figure 2-9. Select the Development option

Now you are ready to set a password for the user admin (see
Figure 2-10). You do not need to enter a password for the user
developer. Make sure you choose a password you will remember and
click Next. After the library packages show as deployed, click Next
again to proceed to the screen shown in Figure 2-11, where you can
now click Launch to finish installation. Note that the Cluster
Configuration option may not appear on the OS X version of the
installer.
Figure 2-10. Choose your password and enter it twice
Figure 2-11. Click Submit to complete setup

After a short wait, your browser will show the Dashboard screen in
Figure 2-12, which is where you can administer the server.
Figure 2-12. The Zend Server administration screen

You can return to this screen at any time by entering


http://localhost:10081 into your browser. Or, if you entered a value
other than 10081 for the Zend Server Interface Port (or 10088 on a
Mac), then you can get to this screen by using that value after the
colon instead.

Testing the Installation


The first thing to do at this point is verify that everything is working
correctly. To do this, you are going to try to display the default web
page, which will have been saved in the server’s document root folder
(see Figure 2-13). Enter either of the following two URLs into the
address bar of your browser:

localhost
127.0.0.1
Figure 2-13. How the home page should look by default

The word localhost is used in URLs to specify the local computer,


which will also respond to the IP address of 127.0.0.1, so you can use
either method of calling up the document root of your web server.
NOTE
If you chose a server port other than 80 during installation (e.g., 8080),
then you must place a colon followed by that value after either of the
preceding URLs (e.g., localhost:8080). You will have to do the same for all
example files in this book. For example, instead of the URL
localhost/example.php, you should enter localhost:8080/example.php (or
whatever value you chose).

The document root is the directory that contains the main web
documents for a domain. This is the one that is entered when a basic
URL without a path is typed into a browser, such as http://yahoo.com
or, for your local server, http://localhost.
By default, Zend Server uses one of the following locations for this
directory (the former for 32-bit computers, and the latter for 64-bit):

C:/Program Files/Zend/Apache2/htdocs
C:/Program Files (x86)/Zend/Apache2/htdocs

NOTE
If you are not sure whether your computer is 32-bit or 64-bit, try to
navigate to the first directory and, if it exists, you have a 32-bit machine.
If not, open up the second directory because you have a 64-bit computer.
When they include spaces, older versions of Windows may require you to
place path and filenames in quotation marks, like this:

cd "C:/Program Files/Zend/Apache2/htdocs"

To ensure that you have everything correctly configured, you should


now create the obligatory “Hello World” file. So create a small HTML
file along the following lines using Windows Notepad or any other
program or text editor, but not a rich word processor such as Microsoft
Word (unless you save as plain text):
<html>
<head>
<title>A quick test</title>
</head>
<body>
Hello World!
</body>
</html>

Once you have typed this, save the file into the document root
directory previously discussed, using the filename test.htm. If you are
using Notepad, make sure that the “Save as type” box is changed
from “Text Documents (*.txt)” to “All Files (*.*)”. Or, if you prefer, you
can save the file using the .html file extension; either is acceptable.
You can now call this page up in your browser by entering one of the
following URLs (according to the extension you used) in its address
bar (see Figure 2-14):

http://localhost/test.htm
http://localhost/test.html

You should now have had a trouble-free installation, resulting in a fully


working WAMP. But if you encountered any difficulties, check out the
comprehensive documentation at http://tinyurl.com/zenddocs, which
should sort out your problem.

Figure 2-14. Your first web page


Alternative WAMPs
When software is updated, it sometimes works differently than you’d
expected, and bugs can even be introduced. So if you encounter
difficulties that you cannot resolve, you may prefer to choose one of
the various other solutions available on the Web instead.
You will still be able to make use of all the examples in this book, but
you’ll have to follow the instructions supplied with each WAMP, which
may not be as easy to follow as the preceding guide.
Here’s a selection of the best in my opinion:
EasyPHP

XAMPP

WAMPServer

Glossword WAMP

Installing a MAMP on Mac OS X


Zend Server Free Edition is also available on OS X, and you can
download it from http://tinyurl.com/zendfree, as shown in Figure 2-
15.
I recommend that you always download the latest stable release (in
this instance, it’s 6.3.0/PHP 5.5 for OS X). It will usually be listed first
in the Download section of the web page, which should display the
correct installer for your computer out of Linux, Windows, OS X, and
IBM i. You may be asked to log in before you download, but you can
also click a link to get the file without logging in or registering,
although you’ll miss out on product update emails and other news.
Other documents randomly have
different content
society. Many of this gang are Dacoits, and their breasts, arms and
necks are picture galleries of tattooed devices, fondly cherished by
the owners as charms against death or capture. Some have rows of
unsightly warts, like large peas, upon the breast and arms which
mark the spots where the charms have been inserted,—scraps of
metal and other substances inscribed with spells known only to the
wise men who deal in such things. One or two natives of India are
amongst the gang, and these are conspicuous by the absence of the
tattooing universally found on the Burman’s thighs. A powerfully
built convict at the end of the rank, in addition to the usual irons,
has his ankle rings connected by a single straight bar, so that he can
only stand with his feet twelve inches apart. ‘Look at that fellow,’
says the superintendent; ‘he is in for five years, and his time would
have been up in three months. A week ago he was down at the
creek with his gang working timber, and must needs try to escape.
He was up to his waist in water and dived under a raft, coming to
the surface a good fifty yards down the stream. The guard never
missed him until a shout from another man drew their attention,
when they saw him swimming as hard as he could go, irons and all,
towards a patch of jungle on the opposite side.’ Amongst a repulsive
horde this man would take first place without competition. ‘Reckless
scoundrel,’ is written on every line of his scowling face, and such he
undoubtedly is. After the severe flogging his attempted escape
earned for him, he assaulted and bit his guards and fellow prisoners,
and the bar between his anklets was the immediate result.

“Conspiracies to break out are not uncommon, although they are


seldom matured, owing to the system of never allowing one batch of
men to remain together for more than a night or two in succession.
A determined attempt to ‘break gaol’ took place in the great central
prison at Rangoon a few years ago, resulting in a stand-up fight
between warders and convicts. Some twenty ‘lifers’ confined in a
large stone cell, whose gate opened upon their workyard, were the
culprits. The hammers and road metal which provided their daily
labour were kept in this yard, and the first aim of the convicts was to
obtain access to the shed where these weapons lay. About midnight
the attention of the sentry was called to the illness of one of the
occupants of the cell by another man, who was apparently the only
wakeful member of the gang besides the sham invalid. A Madrassee
apothecary was called to the grated window of the den, and
obtained sufficient information to enable him to prepare some
remedy. On his return with the potion, seeing that all the convicts
were sound asleep, he did not attempt to give the medicine to the
sick man through the window, but against the rules caused the
guard to open the gate intending to take it into the cell himself. The
instant the gate was opened, the slumbering convicts sprang to their
feet, rushed at the apothecary and knocked him down in such a
position that his recumbent form effectually prevented the guard
behind from closing it. They quickly made their way into the
workshed, and arming themselves with hammers and stones,
prepared to resist the warders who had been attracted by the noise
and the shouts of a sentry on the wall. A furious conflict now ensued
between the warders, big, muscular Punjabees armed with heavy
cudgels, and the convicts with their extemporised weapons. The
warders were reinforced until both parties were fairly matched, and
the rough and tumble fight in the dark progressed amid
extraordinary confusion. The workyard was overlooked by two huge
wings of the gaol in which a large number of prisoners were
confined; these men, roused to a frantic pitch of excitement by the
uproar below, dashed about their wards like caged animals with
screams and yells of encouragement to their fellows; while the
sentries in the watch towers on the main wall kept up a desultory
fire in the air to prove to the convicts the impossibility of escaping,
even if they should succeed in scaling the high spiked iron railing of
their yard.

“The combatants fought hand-to-hand for some time, neither side


gaining any advantage, whilst above the roar of human voices and
the sickening crash of heavy clubs on the convicts’ shaven skulls the
alarm bell clashed out warning that military assistance from the
distant barracks was required. Warders had been summoned from all
parts of the gaol, and a general outbreak seemed imminent when
the appearance of the superintendent with a revolver suddenly
decided matters. Panic seized the convicts; they dropped their
weapons with one accord and crowded back into the cell, leaving
two of their number dead in the yard. It would be impossible to
conceive a more ghastly sight than that row of naked, trembling
convicts as the warders now ranged them in the vault-like den to be
counted. The dim light of oil-lanterns fell upon upturned faces,
before repulsive enough, but now positively startling in their hideous
disfigurement of dust and clotting blood. Every man was streaming
with blood from wounds about the head, more or less severe, for the
convicts had fought with the desperation of men to whom success
meant liberty. They were doomed to drag out their lives in that
earthly hell; a flogging was the worst that could happen to them if
their attempt failed, possible freedom the reward if it succeeded.
Who would not risk the first for the slenderest chance of the second?
They took the risk and fate had gone against them. The excitement
was over, and they huddled together against the wall of the cell in
an agony of fear for the consequences their night’s work would bring
upon them to-morrow, staring enviously at those whose wounds
necessitated their removal to hospital. For them, at least, a few days’
reprieve was certain before they suffered lash and punishment drill.”
PRISONS OF CHINA
CHAPTER VIII
CRIME IN CHINA

Great cruelty in the administration of the law in China—Experience of


Lord Loch—Iron collar, chains and creeping vermin—Earth
maggot—The “Ling che,” a slow ignominious death—Internal
arrangement of prisons—Whole families detained as hostages
for fugitive offenders—Mortality large; dead-house always full—
Military guard—Public flogging of thieves—The “Cangue” or
heavy wooden collar—Six classes of punishment—Method of
infliction—Chinese punishment in the seventeenth century—
Some cruel practices of to-day.

According to Chinese law, theoretically, no prisoner is punished until


he confesses his crime. He is therefore proved guilty and then by
torture made to acknowledge the accuracy of the verdict. The
cruelty shown to witnesses as well as culprits is a distinct blot on the
administration of justice in China. The penal code is ferocious, the
punishments inflicted are fiendishly cruel, and the prisons’ pig-stys in
which torture is hardly more deadly than the diseases engendered
by the most abominable neglect. The commonest notions of justice
and fair play are continually ignored. The story is told of a wretched
old man who had been detained years in the filthy prison of Peking,
dragging out a weary existence in the company of criminals of the
worst description. According to his own account, he had been living
on his land with his wife and family. One night he took out his gun to
scare crows and trespassers off his ripening crops, in the execution
of which innocent design he let off his weapon two or three times.
On the following day a man was found murdered on the far confines
of his land. Immediately he was apprehended, not as one might
suppose, to give evidence or relate what he knew, but to be made to
confess that he himself was the author of the crime. To extort this
confession he was cruelly and repeatedly tortured. “Of course,” he
said, “I shall never leave this prison alive, for they will keep me here
until, reduced to the last extremity by torture, I confess myself guilty
of a crime of which I am entirely innocent, and when I do confess
they will cut off my head on the strength of that confession.” This is
founded on unimpeachable fact, and the case is constantly recurring
under different forms. “In China it is not the prosecution who prove
a prisoner guilty, but the prisoner who has to prove that he is not
guilty.” In this same prison of Peking a visitor once was permitted to
enter a chamber in which was a barred cage eight feet by eight, and
in it twenty-six human beings were incarcerated, of whom six were
dying of gaol fever. He asked that they might be taken out of the
cage “in order that he might medically examine and if possible
relieve them. The gaoler opened the door of the cage and seizing
the six by their pig-tails, or by any other portion of their bodies that
happened to present itself, dragged them out one by one over the
pavement into the courtyard outside. No doubt several of these men
were innocent of the crimes imputed to them and were waiting to be
tortured into a confession of guilt.”

Few Europeans have experienced imprisonment in China. One


Englishman, Lord Loch, has given an account of the sufferings he
endured when treacherously captured during the war of 1860. “The
discipline of the prison was not in itself very strict and had it not
been for the starvation, the pain arising from the cramped position
in which the chains and ropes retained the arms and legs, with the
heavy drag of the iron collar on the bones of the spine, and the
creeping vermin that infested every place, together with the
occasional beatings and tortures which the prisoners were from time
to time taken away for a few hours to endure, returning with
bleeding legs and bodies and so weak as to be scarcely able to
crawl, there was no very great hardship to be endured.... There was
a small maggot which appears to infest all Chinese prisons: the earth
at a depth of a few inches swarms with them; they are the scourge
most dreaded by every poor prisoner. Few enter a Chinese prison
who have not on their bodies or limbs some wounds, either inflicted
by blows to which they have been subjected, or caused by the
manner in which they have been bound; the instinct of the insect to
which I allude appears to lead them direct to these wounds. Bound
and helpless, the poor wretch cannot save himself from their
approach, although he knows full well that if they once succeed in
reaching his lacerated skin, there is the certainty of a fearful
lingering and agonising death before him.”

Punishment varies in cruelty and intensity with the crime; for the
murder of a father, mother, or several people of one family the
sentence is “ignominious and slow death.” This method is known as
ling che, and the victim is attached to a post and cut to pieces by
slow degrees, the pieces being thrown about among the crowd. This
cruel death was more than once publicly inflicted in Peking during
the year 1903. Some of the most horrible passages in the Peking
Gazette are those which announce the infliction of this awful
punishment on madmen and idiots who in sudden outbreaks of
mania have committed parricide. For this offence no infirmity is
accepted, even as a palliation. A culprit condemned to ling che is
tied to a cross, and while he is yet alive gashes are made by the
executioner on the fleshy parts of his body, varying in number
according to the disposition of the judge. When this part of the
sentence has been carried out, a merciful blow severs the head from
the body. It is said that the executioner can be bribed to put
sufficient opium into the victim’s last meal to make him practically
unconscious, or even to inflict the fatal stab in the heart at first,
which should ordinarily be the last. Common cases of capital
punishment are comparatively merciful, for the executioners are so
skilful that they generally sever the head from the trunk with one
swift blow. The Chinese prefer death by strangulation to any other
form, because it enables the body to appear unmutilated in the next
world. This feeling has such a hold on them that when four victims
were decapitated in Peking, their relatives instantly claimed the
bodies and sewed on the heads. The permission to do this was
regarded by them as a great privilege and a mitigation of the
sentence.

The prisons of China are made up of a certain number of wards


according to their class. Thus, for example, the prisons of the
respective counties of Nam-hoi and Pun-yu in the province of
Kwang-tung, which are first-class county prisons, consist (besides
chambers in which prisoners on remand are confined) of six large
wards in each of which are four large cells, making in all twenty-four
cells. The same arrangements may be said to prevail in all county
prisons. The walls of the various wards abut one upon another and
form a parallelogram. Round the outer wall a paved pathway runs
upon which the gates of the various wards open. This pathway is
flanked by a large wall which constitutes the boundary wall of the
prison. The cells are of considerable size. The four cells in each ward
are arranged two on a side so as to form the two sides of a square,
and they much resemble cattle sheds, the front of each being
enclosed in a strong palisading of wood which extends from the
ground to the roof. They are paved with granite, and each is
furnished with a raised wooden platform on which the prisoners sit
by day and sleep by night. They are polluted with vermin and filth of
almost every kind, and the prisoners seldom or never have an
opportunity afforded them of washing their bodies or even dressing
their hair, as water in Chinese prisons is a scarce commodity and
hair-combs are almost unknown. The approach to the prison is a
narrow passage at the entrance of which there is an ordinary sized
door. Above this entrance door is painted a tiger’s head with large
staring eyes and widely extended jaws. Upon entering, the visitor
finds an altar on which stands the figure of a tiger hewn in granite.
This image is regarded as the tutelary deity of the prison gates. The
turnkeys worship it morning and evening, with the view of
propitiating it and securing its watchfulness, gaolers in China being
held responsible for the safe custody of the miserable beings who
are entrusted to their care. At the base of the large wall which forms
the prison boundary there are several hovels—for by no other name
can they be designated—in some of which all the female felons are
lodged and in others whole families who are held as witnesses by
the mandarins.

There is a law which admits of the seizure and detention as hostages


of entire families, any members of which have broken the laws of
the empire and fled from justice. Such hostages are not liberated
until the offending relatives have been secured, and consequently
they are not unfrequently imprisoned during a period of five, ten or
twenty years. Indeed, many of them pass the period of their natural
lives in captivity. Thus the mother or aunt of Hung Sow-tsuen, the
leader of the Taiping rebellion, died after an imprisonment of several
years in the prison of the Nam-hoi magistrate at Canton. The
unoffending old woman grievously felt this long detention for no
crime or offence of her own. Should the crime of the fugitive be a
very aggravated and serious one, such, for example, as an attempt
upon the life of the sovereign of the empire, it is not unusual to put
the immediate, although perfectly innocent, relations of the offender
to death, while those who are not so nearly related to him are sent
into exile. In 1803 an attempt was made to assassinate the emperor
Ka-hing. The assassin was no sooner apprehended than he was
sentenced to be put to death by torture; and his sons who were
young children were put to death by strangling. The mortality in
Chinese prisons is very great. The bodies of all who die in prison are
thrown into the dead-house and remain there until the necessary
preliminaries, which are of a very simple kind, have been arranged
for their interment. In the prisons of Canton these receptacles may
be seen full of corpses and presenting the most revolting and
disgusting appearance. Some of the unhappy victims have died from
the effects of severe and often repeated floggings. Others have
fallen victims to one or other of the various diseases which such
dens are only too well fitted to create and foster. In the prison of
Pun-yu there were on one occasion in the dead-house five bodies, all
with the appearance of death from starvation—a form of capital
punishment which in China is frequently inflicted upon kidnappers
and other grave offenders. Directly in front of the door of the dead-
house and at the base of the outer boundary wall of the prison there
is a small door of sufficient size to admit of a corpse being passed
through. The corpses of all who die in prison are carried through this
aperture into the adjoining street for burial. It would be paying too
much reverence to the deceased prisoner to allow the remains to be
carried through the gates of the yamun to which the prison is
attached.

In point of appearance the unfortunate inmates of Chinese prisons


are perhaps of all men the most abject and miserable. Their death-
like countenances, emaciated forms and long coarse black hair,
which, according to prison rules, they are not allowed to shave, give
them the appearance rather of demons than of men, and strike the
mind of the beholder with impressions of gloom and sorrow that are
not easily forgotten. Prisoners in every ward with one exception only
wear fetters. The exception is the prisoner who is supposed to be
more respectable and who conducts himself better than any of his
fellows in crime. He is allowed the full freedom of his limbs and as a
mark of confidence and trust the privilege is conferred upon him of
acting as overseer and guardian of his comrades. The dress worn by
Chinese prisoners consists of a coat and trousers of a coarse red
fabric. On the back of the coat is printed in large indelible characters
the name of the prison in which its wearer is confined so that should
he escape from durance he would at once be recognised as a
runaway or prison breaker, and his recapture facilitated. Each prison
is presided over by a governor who has under him a considerable
number of turnkeys. Thus each large prison in Canton has a
governor, twenty-four turnkeys, thirty-seven watchmen and fifteen
spearmen. In a barrack beyond the doors or gates of each prison is
a resident guard of soldiers. The turnkeys, watchmen, spearmen,
and so forth, become the most casehardened and incorrigible of the
criminals from the great amount of misery which they daily witness.
The policemen who are attached to the yamun are also men of vile
character, and it is unfortunately too common for them to share the
booty with the thief and hoodwink or deceive the magistrate.
The governor of a Chinese prison purchases his appointment from
the local government. He receives no salary from the state and is
compelled, therefore, to recoup himself by exacting money from
such relatives or friends of prisoners as are in good circumstances
and naturally anxious that their unhappy friends should escape as
far as possible the sad deprivations and cruelties for which Chinese
prisons are so notorious. To each prison a granary is attached in
which rice of the cheapest and coarsest kind is stored by the
governor. This rice is one of his perquisites, and he retails it to the
prisoners at a remunerative price. Vegetables and firewood for
culinary purposes, both of which are daily offered for sale to the
prisoners, are also supplied by him. As the government daily
allowance to each prisoner does not exceed twenty-five cash, the
prisoners who are without friends are not often able to buy even
vegetables and firewood.

Besides the prison in which convicts are confined there is also within
the precincts of the yamun a house of detention. This is neither so
large nor so strongly enclosed as the common gaol. Generally, in
such a house of detention there is a large chamber which is set
apart for the reception of prisoners on remand, who have friends
able and willing to satisfy the demands of the governor. By this
arrangement such prisoners avoid the misery of being shut up in the
same ward with men of the vilest character and often most
loathsome condition, covered with filth or suffering from various
kinds of cutaneous diseases. The arrangement is a great advantage
to the governor of the gaol and to all prisoners who can afford to
pay for it, but a great disadvantage to other inmates. The space
required for the convenience of prisoners who have friends to look
after their wants leaves very little room indeed for the reception of
the great majority of the poorer criminals, who are huddled together
in a common ward sometimes too crowded to allow its occupants to
lie down. In the city of Canton, on the streets adjoining the yamuns,
there are other houses of detention, all densely crowded.
Imprisonment is not the only penalty inflicted; cases of petty larceny
are generally dealt with by flogging. The culprit is handcuffed and
with the identical article which he stole, or one similar, suspended
from his neck, is marched through the streets of the neighbourhood
in which the theft was committed. He is preceded by a man beating
a gong, and at each beat of the gong an officer who walks behind
gives him a severe blow with a double rattan across the shoulders,
exclaiming, “This is the punishment due to a thief.” As the culprit has
to pass through three or four streets his punishment, although
regarded by the Chinese as a minor one, is certainly not lacking in
severity, and is often accompanied by a considerable flow of blood.

A thief who had stolen a watch from one of his countrymen was
flogged through the Honam suburb of Canton, but the officer
appointed to flog him was very corpulent, and from his great
earnestness in the discharge of his duty became quite breathless
before the various streets along which the culprit was sentenced to
pass had been fully traversed. The person from whom the watch had
been stolen, seeing that the thief might escape the full severity of
his penalty, snatched the double rattan from the hand of the
exhausted officer and applied it himself most unmercifully to the
thief’s back. Women who are convicted of thieving are in some
instances punished in this way. Occasionally a long bamboo is used
in cases of petty larceny. When this is the case, however, the culprit
receives his flogging in court in front of the tribunal. He is at once
denuded of his trousers and the number of blows varies according to
the nature of the larceny, from ten to three hundred.

Mr. Henry Norman, who witnessed a most cruel flogging in court,


which left the prisoner in a pitiable state, asserts that when a
policeman was called to suffer the same punishment, it was seen
that he had bound strips of wood on himself to catch the full force of
the bamboo. The prescribed number of strokes were administered,
but the fraud was plainly apparent to the magistrate and all the
spectators, and the policeman, who was none the worse for the
flogging, went about his duties as usual when the ordeal was over.
Spectacles of this kind, says the same authority, seem to be highly
enjoyed by a Chinese audience.

Chinese Punishment

The cangue, or square and heavy wooden collar, is one of the


modes by which petty offenders are punished in China. The
weight varies with the offence, and they are worn from a
fortnight to three months, during which time the cangue is not
removed by day or night. This device inflicts severe punishment,
preventing the culprit from assuming any position of rest. The
name of the prisoner and the nature of his offence are written
on the cangue in large letters, so that “he who runs may read,”
and he is often made to stand at one of the principal gates or in
some other conspicuous place as an object of universal
contempt.

The cangue, or square, heavy wooden collar, is another mode by


which petty offenders in China are punished. Cangues vary in
weight, some being considerably larger and heavier than others. The
period for which an offender is sentenced to wear this collar varies
from a fortnight to three months. During the whole of this time the
cangue is not removed from the neck of the prisoner either by day
or by night. Its form prevents the wearer from stretching himself on
the ground at full length, and to judge from the attenuated
appearance of prisoners who have undergone it, the punishment
must be terribly severe. The name of the lawbreaker and the nature
of his offence are written on the cangue in large letters, “so that all
the world may read.” The authorities often make the victim stand
from sunrise to sunset at one of the principal gates or in front of one
of the chief temples or public halls of the city, where he is regarded
as an object of universal scorn and contempt.

Another mode of punishing a criminal is that of confining him in a


cage. The cages are of different forms, the worst being too short to
allow the occupants to place themselves in a recumbent position and
too low to admit of their standing. To the top of one kind is attached
a wooden collar or cangue by which the neck of the criminal, which
it is made to fit, is firmly held. Another cage resembles the former in
all respects but one. The difference consists in its being higher than
its occupant, so that while his neck is held fast by the wooden collar
attached to the top of the cage, the tips of his toes barely touch the
floor. Indeed, the floor, which is only a few inches from the ground,
is sometimes removed so that the prisoner may be suspended by the
neck. This punishment almost invariably proves fatal. The victims are
as a rule thieves and robbers. They are often punished by being
bound to stones by means of long chains passed round their necks.
The stones are not large, but sufficiently heavy to inconvenience
them as they walk to and from the prison to the entrance gates of
the yamun, in front of which they are daily exposed. These stones
are their inseparable companions by night and by day throughout
the whole period of their incarceration. In some instances they are
bound to long bars of iron and are daily exposed to the scorn of all
passers by.
For capital and other offences of a serious nature there are six
classes of punishment. The first, called ling che, has already been
mentioned. It is inflicted upon traitors, parricides, matricides,
fratricides and murderers of husbands, uncles and tutors. The
criminal is cut into either one hundred and twenty, seventy-two,
thirty-six or twenty-four pieces. Should there be extenuating
circumstances, his body, as a mark of imperial clemency, is divided
into eight portions only. The punishment of twenty-four cuts is
inflicted as follows: the first and second cuts remove the eyebrows;
the third and fourth the shoulders; the fifth and sixth the breasts;
the seventh and eighth the parts between each hand and elbow; the
ninth and tenth the parts between each elbow and shoulder; the
eleventh and twelfth the flesh of each thigh; the thirteenth and
fourteenth the calf of each leg; the fifteenth pierces the heart; the
sixteenth severs the head from the body; the seventeenth and
eighteenth cut off the hands; the nineteenth and twentieth the
arms; the twenty-first and twenty-second the feet; the twenty-third
and twenty-fourth the legs. That of eight cuts is inflicted as follows;
the first and second cuts remove the eyebrows; the third and fourth
the shoulders; the fifth and sixth the breasts; the seventh pierces
the heart; the eighth severs the head from the body. A great many
political offenders underwent executions of the first class at Canton
during the vice-royalty of His Excellency, Yeh. On the fourteenth day
of December, 1864, the famous Hakka rebel leader, Tai Chee-kwei by
name, was put to death at Canton in the same manner.

The second class of capital punishment, which is called chan or


decapitation, is the penalty due to murderers, rebels, pirates,
burglars, etc. Prisoners who are sentenced to decapitation are kept
in ignorance of the hour fixed for their execution until the preceding
day. Occasionally they have only a few hours’ and in some instances
only a few minutes’ warning. When the time has arrived for making
the condemned man ready for execution, an officer in full costume,
carrying in his hand a board on which is pasted a list of the names
of the prisoners who are that day to atone for their crimes, enters
the prison, and in the hearing of all the prisoners assembled in the
ward, reads aloud the list of the condemned. Each prisoner whose
name is called at once answers to it, and he is then made to sit in a
basket to be carried once more into the presence of a judge. As he
is taken through the outer gate, he is interrogated through an
interpreter by an official who acts on the occasion as the viceroy’s
representative.

Mr. Henry Norman described in 1895 an execution of fifteen


offenders of this class which he had witnessed. The condemned
were carried into the place of execution in flat baskets suspended
from bamboo poles, and literally dumped out, bound hand and foot.
A slip of paper was stuck in the queue of each condemned man,
which described the nature of the crime. These were taken out and
stacked up by one of the executioners, and then the work of
severing the heads began, one of the executioners holding the
victim’s shoulders while the other used the knife. All of those about
to be beheaded witnessed the decapitation of their comrades, and
the spectators yelled with delight and frenzy. When the last head
had been severed, the place was ankle-deep in blood and the
executioner, who used the knife, was covered with it. The bodies
were thrown into a pond and the heads were put in earthenware
jars and stacked up with others surrounding this potter’s field.

A third punishment is called nam-kow, or death by strangulation.


This is inflicted on kidnappers and all thieves who with violence steal
articles the value of which amounts to five hundred dollars and
upward. The manner in which this form of capital punishment is
inflicted is as follows:—A cross is erected in the centre of the
execution ground, at the foot of which a stone is placed, and upon
this the prisoner stands. His body is made fast to the perpendicular
beam of the cross by a band passing round the waist, while his arms
are bound to the transverse beam. The executioner then places
round the neck of the prisoner a thin but strong piece of twine,
which he tightens to the utmost and then ties in a firm knot round
the upper part of the perpendicular beam. Death by this cruel
process is very slow and is apparently attended with extreme agony.
The body remains on the cross during a period of twenty-four hours,
the sheriff before leaving the execution ground taking care to attach
his seal to the knot of the twine which passes round the neck of the
malefactor.

The fourth class of punishment is called man-kwan, or transportation


for life. The criminals who are thus punished are embezzlers,
forgers, etc. The places of banishment in the north of China and
Tartary are named respectively Hack-loong-kong, Elee Ning-koo-tap
and Oloo-muk-tsze. All convicts from the midland and southern
provinces are sent to one or the other of these places, where the
unhappy men are employed in a great measure according to their
former circumstances of life. Those who are of a robust nature and
who have been accustomed to agricultural pursuits are daily
occupied in reclaiming and cultivating waste lands. Others, more
especially those who have been sent from the southern provinces,
where the heat in summer is almost tropical, are, in consequence of
the severity of the cold which prevails in northern latitudes, made to
work in government iron foundries. The aged and those who have
not been accustomed to manual labour are daily employed in
sweeping the state temples and other public buildings.

The fifth class of punishment is termed man-low, or transportation


for ten or fifteen years. The criminals of this class are petty burglars
and persons who harbour those who have broken the laws. Such
offenders are generally sent to the midland provinces of the empire,
where the arrangements for convict labour are similar to those of
the penal settlements of the north. Convicts of this class who are
natives of the midland provinces are sent either to the eastern,
western or southern provinces of the empire. The barbarous practice
of tattooing the cheeks is also resorted to with these prisoners. The
sixth class is called man-tow, or transportation for three years. A
punishment of this nature is the portion of gamblers, salt smugglers,
etc. A convict of this class is transported to one of the provinces
immediately bordering upon that of which he is a native or in which
his crime was committed.
Oppression by the ruling class was always rife in China, and
instances might be multiplied recording the cruel misusage of
inferiors by the mandarins. One case in which ample vengeance was
exacted by the aggrieved victim may be quoted here. The story is
told by Lady Susan Townley in her “Chinese Note Book.”

“A well-to-do farmer called Chiang-lo lived happily on his estate with


a pretty wife whom he loved, until one day, as ill luck would have it,
a rich Mandarin passed that way, who, seeing the fair dame,
straightway desired her. Anxious to get rid of the husband by fair
means or foul, he trumped up a charge against him, and the farmer
was condemned ‘to be a slave to a soldier,’ which meant that he
would be marched in heavy chains from Peking to the northern
frontier of China, cruelly beaten at every station (they occur about
every eighteen miles), and ill-treated at will by the soldier in charge
of him. This sentence is usually equivalent to death, for few can
survive the hardships of such a journey, the fatigue, heat, cold,
hunger and torture. But our friend with hatred in his heart resolved
to live in order to be revenged upon his enemy. So he bore all his
sufferings with superhuman courage, and finally arrived at his
destination on the frontier, where he was put to work in a mine.”
After he had been there about three years His Majesty Kwang Hsu
assumed the reins of government, and accorded a general pardon to
all criminals. Thus in a night Chiang-lo recovered his freedom, and
without a moment’s hesitation set off to trudge back to Peking. “This
time there was hope in his heart for he meant to kill his enemy and
the wife who had betrayed him. When he saw her again, however,
all his old love for her returned and though she refused to go with
him, and though he knew that if he killed them both, Chinese law
would account him guiltless, whereas if he killed her lover and
spared her, he would be considered guilty of murder, and would have
to bear the penalty, he did not hesitate one moment, but left her
and went to find her seducer.

“For days he tracked him about the town, waiting for a favourable
opportunity. At last it came, as his rival passed him in the deep
embrasure of the Chien-men gate. Springing from his place of
concealment he challenged him to fight, but the coward refused.
Then Chiang-lo ... drew his knife and repeatedly stabbed him in the
heart. When he saw his enemy lying dead at his feet, the apathy of
despair fell upon him. Wiping his knife on his sleeve he bowed his
head, and turning his steps to the nearest police station calmly gave
himself up. A few weeks later he was beheaded.”

It is interesting to read that the prevailing method of punishment in


China in the seventeenth century differed little from that in force at a
very recent date. In the memoirs of the Jesuit Louis le Comte,
published in 1698, he says: “They have several ways of inflicting
death. Mean and ignoble persons have their heads cut off, for in
China the separation of the head from the body is disgraceful. On
the contrary, persons of quality are strangled, which among them is
a death of more credit.... Rebels and traitors are punished with the
utmost severity; that is, to speak as they do, they cut them into ten
thousand pieces. For after that the executioner hath tied them to a
post, he cuts off the skin all round their forehead which he tears by
force till it hangs over their eyes, that they may not see the torments
they are to endure. Afterwards he cuts their bodies in what places
he thinks fit, and when he is tired of this barbarous employment, he
leaves them to the tyranny of their enemies and the insults of the
mob.”

Cruelty, which is one of the strongest characteristics of the Chinese


nature, manifests itself not only in the application of criminal law,
but with a peculiar callousness they delight to torture dumb animals
and enjoy witnessing the sufferings of children and adults of their
own race. A common practice of the professional kidnapper is to
blind a child after stealing it, and then carry it away to another town
and sell it for a professional beggar. Infant life is still being destroyed
by parents in some districts of China, and the abominable custom is
difficult to eradicate, as the children are simply abandoned and left
to starve, and if the crime is discovered it is difficult to prove
deliberate murder.
Cases have been known of Chinese boatmen refusing to rescue
persons who had thrown themselves overboard from a sinking craft
and were drowning, unless they agreed to pay an exorbitant sum
asked as the price of rescue. They have even been known to look on
passively while their fellow-countrymen were struggling for life in the
water, without raising a hand to help them.

It is but natural to expect that in a country where such occurrences


are common, the punishments inflicted on the really guilty should
exceed anything known in the practices of the enlightened nations of
to-day.
PRISONS OF JAPAN
CHAPTER IX
ENLIGHTENED METHODS OF JAPAN

Enlightened Japan has striven to establish a perfect prison system—


New prisons—Deportation to the island of Yezo—Agricultural
labour and work in coal mines—Two fine prisons in Tokio—
Description by Mr. Norman—The gallows—Training school for
prison officials—Disciplinary punishments and rewards.

Japan as an enlightened and progressive country has made


strenuous efforts to establish “as perfect a prison system as
possible; one which is in harmony with the advancement of science
and the results of experience.” These reforms were commenced in
1871 and were continued in various new prisons at Tokio, Kobold,
Kiogo and upon the island of Yezo, all admirably organised and
maintained. This movement was hurried on by the great
overcrowding of the small provincial prisons on account of the
accumulation of long-term prisoners. No proper discipline could be
applied and there was absolutely no room for short-term offenders.
Most of those sentenced to hard labour and deportation are now
sent to the penal settlement on the island of Yezo, where they are
employed both within the prisons and at agriculture in the open air.
Every advantage is taken of the natural aptitudes of the Japanese,
and the inmates of gaols prove the most expert and artistic
workmen. The very worst criminals are sent to the prison of Sorachi
in the remote island of Yezo, beyond Poronaibuto—a bleak, desolate
spot surrounded by the usual bamboo fence—which holds about
sixteen hundred convicts. They are to be seen squatted on mats at
work, each in front of his own sleeping place, and on a shelf above
are his wadded bed-quilt, with a mosquito curtain on top of each.
The place is so isolated and surrounded by such an impenetrable
jungle that escapes are out of the question. A little further on is the
prison of Poronai, in a delightful spot, where the most extensive coal
fields of Japan are located. A small building houses some six
hundred convicts who work in the coal seams on the side of the hill.
“Hard labour indeed,” says Mr. Wingfield. “Heavily chained, by light
of a safety lamp the wretched convicts were crouching in holes
where there was no room to raise the head or stretch the limbs, and
here they had to remain for eighteen hours at a time.” Their
sentences were for twelve years, although remission might by good
conduct be secured after seven. Yet these luckless Japanese bore
their irksome lot with a light heart. “As we were leaving Poronai at 5
A. M.,” says the same observer, “we met a batch of miners marching
to face their ordeal and many after the eighteen hours are
completed have to be removed to hospital. They were clanking their
chains right merrily, talking and laughing loudly, bandying quips and
jokes.”

Japan is a land of rapid transition and nothing has changed more


completely in recent years than Japanese prisons. Still there was
some system, even in ancient days. The sexes were kept apart, the
penalty of the log worn round the neck and fastened to the ankle
was not imposed upon the aged or juvenile offender, nor upon
dwarfs, invalids or pregnant women. In the sixteenth century a
prison reformer arose who organised five new prisons in Yeddo for
five different classes of prisoners, comprising females and persons of
different conditions of life. Proper prison officers were appointed,
and security was obtained without despising sanitary needs. Still
there must have been much mutual contamination, owing to the
indiscriminate herding together, and the maintenance of internal
order was left to the prisoners who chose among themselves a
nanoushi, or head, with eleven assistants to control the whole body.
Flogging was inflicted and handcuffs were universally worn. In 1790
a house of correction was established on the island of Yshikavoy in
the Bay of Yeddo, to which were committed all vagabonds or
incorrigible prisoners whom it was thought unsafe to set free lest
they should relapse into crime. The work on this island was chiefly
the manufacture of oil. In cases of escape and recapture the
fugitives were branded with a certain tattoo mark on the left arm.

Even in the middle of the nineteenth century the same brutal


methods of torture prevailed as in China (from where their bloody
codes were mostly borrowed), and there are preserved collections of
instruments of torture as diabolical as any known to history. Crime,
too, was not lacking in those “isles of the blest,” and every species of
moral filth and corruption abounded, which was shown in its true
colours when the liberty of the press was granted, in 1872-1874.
The number of executions and deaths in the native prisons at that
time was said to average three thousand per annum.

The chief prison of the empire, in Tokio, as described by Mr. William


M. Griffis, who visited it in 1875, was very different in its sanitary
appointments and general condition from the prisons of Tokio to-day.
A curious feature was a small roofed in structure in the prison yard,
with open sides, where condemned men of rank were allowed to
expiate their crimes by plunging the dirk into their own bodies, after
which the executioner cut off their heads. The head, laid on a tray,
was then inspected by an officer of justice. There were very few of
such executions after 1871. The ordinary criminal was beheaded in
the blood-pit, so-called, which was a pit surrounded with a much
stained and slashed wooden curb, and kept covered by a sort of
trap-door. In the pit were mats, one above the other, which had
been soaked with the blood of many criminals. “The faint odour that
ascended,” says Mr. Griffis, “was more horrible in the awful cloud of
associations which it called up than the mere stench.” It was then
April and twenty-five heads had fallen there since the year began.
The criminal was led to the pit blindfolded and was beheaded with
an ordinary sword, sharp as a razor. Death followed frequently on
the day of sentence and never later than the day after.

Tokio has now two prisons; the first and chief is situated upon the
island of Oshikawa at the south of the city, and the second, the
convict and female prison of Ichigawa, is in the centre of the city.
The former is completely isolated, all communication with the
mainland being by police ferry, and can accommodate two thousand
men and boys, who are serving terms of ten years or less. The
prison of Ichigawa usually contains fifteen hundred men and about
one hundred women, among whom are many serving life sentences.
Attached to the prison is a convict farm, and it is here that capital
punishment is carried out. Otherwise the two prisons resemble each
other closely and a description of one will answer for both, says Mr.
Norman, who described them in 1892, and gives the following
account:

“The entrance is through a massive wooden gateway, into a guard-


room adjoining which are the offices of the director and officials. The
prison itself consists of a score or more of detached one-story
buildings, all of wood and some of them merely substantial sheds,
under which the rougher labour, like stone-breaking, is performed.
The dormitories are enormous wooden cages, the front and part of
the back formed of bars as thick as one’s arm, before which again is
a narrow covered passage, where the warder on guard walks at
night. There is not a particle of furniture or a single article of any
kind upon the floor, which is polished till it reflects your body like a
mirror. No boot, of course, ever touches it. The thick quilts, or futon,
which constitute everywhere the Japanese bed, are all rolled up and
stacked on a broad shelf running round the room overhead. Each
dormitory holds ninety-six prisoners, and there is a long row of
them. The sanitary arrangements are situated in a little addition at
the back, and I was assured that these had not been made pleasant
for my inspection. If not, I can only say that in this most important
respect a Japanese prison could not well be improved. In fact, the
whole dormitory, with its perfect ventilation, its construction of solid,
highly-polished wood, in which there is no chance for vermin to
harbour, and its combined simplicity and security, is an almost ideal
prison structure. Of course the fact that every Japanese, from the
emperor to the coolie, sleeps upon quilts spread out on the floor,
greatly simplifies the task of the prison architect in Japan.
“On leaving the dormitories we passed a small, isolated square
erection, peaked and gabled like a little temple. The door was
solemnly unlocked and flung back, and I was motioned to enter. It
was the punishment cell, another spotless wooden box, well
ventilated, but perfectly dark, and with walls so thick as to render it
practically silent. ‘How many prisoners have been in it during the last
month?’ I asked. The director summoned the chief warder, and
repeated my question to him. ‘None whatever,’ was the reply. ‘What
other punishments have you?’ ‘None whatever.’ ‘No flogging?’ When
this question was translated the director and the little group of
officials all laughed together at the bare idea. I could not help
wondering whether there was another prison in the world with no
method of punishment for two thousand criminals except one dark
cell, and that not used for a month. And the recollection of the filthy
and suffocating sty used as a punishment cell in the city prison of
San Francisco came upon me like a nausea.”

In Japan a prison consists of two parts—dormitories and workshops.


There is nothing whatever of cells or regulation prison buildings
properly speaking. It is a place of detention, of reformation, and of
profitable work. The visitors found in the first workshop, to their
great surprise, a couple of hundred prisoners making machinery and
steam boilers. One warder, carrying only a sword, was in charge of
every fifteen men. The prisoners were working on contract orders
for private firms, under the supervision of one skilled master and
one representative of the firm giving the contract. They work nine
hours a day, and are dressed in cotton suits of a peculiar terra-cotta
colour. When the foreigners entered, the warder on guard came to
attention and cried, “Pay attention!” Every one ceased work and
bowed with his forehead to the floor, remaining in that attitude until
a second order bade them rise. They were making large brass and
iron steam pumps, and the workshop, with its buzz of machinery
and its intelligent labour, was much like a part of an arsenal here or
in Europe.
Another shop contained the wood-carvers, where more than a
hundred men, with blocks of wood between their knees, were
carving with keen interest upon all sorts of things, from simple trays
and bowls to fragile and delicate long-legged storks. “I bought,” says
our author, “an admirably-carved tobacco box, representing the God
of Laughter being dragged along by his cloak by six naked boys, and
afterward I asked some Japanese friends who supposed I had picked
it up at a curio-dealer’s, how much it was worth. They guessed ten
yen—thirty shillings. I paid sixty-eight sen for it—less than two
shillings. It is a piece of work that would be admired anywhere, and
yet it was the work of a common burglar who had made the
acquaintance of a carving tool and a prison at the same time.”

There were also paper-makers, weavers (who were making the


fabric for the prison clothing), fan-makers, lantern-makers and
workers in baskets, mats, and nets. A printing shop, too, there was,
where the proof-reader was a criminal of more than ordinary
interest. He had been secretary of legation in France and had
absconded with a large sum, leaving his shoes on the river bank to
lead the authorities to believe he had committed suicide, but he had
been arrested eventually in Germany with his mistress.

In one of the shops jinrikishas were being made, in another


umbrellas were being carved elaborately and in another every kind
of pottery was being turned out. To the amazement of the visitors,
they found sixty men, common thieves and burglars, making the
exquisite cloisonné ware—“cutting by eye-measurement only the tiny
strips of copper to make the outline of a bird’s beak or the shading
of his wing or the articulations of his toe, sticking these upon the
rounded surface of the copper vase, filling up the interstices with
pigment, coat upon coat, and firing and filing and polishing it.” The
finished work was true and beautiful and it was difficult to believe
that these men knew nothing at all about it before they were
sentenced. It would be hard to imagine teaching such a thing to the
convicts at Dartmoor or at Sing Sing. In the prison at Tokio the
convict is taught to do whatever is the limit of his natural ability. If
he cannot make cloisonné, he is assigned to the wood-carving
department, or perhaps to make pottery. If he cannot do these, he
can possibly make fans or basket-work, or set type or cast brass.
And for those who cannot reach so high a limit as these occupations
there is left the rice mill or stone-breaking, but of two thousand men
only thirty were unable to do any other work but that of breaking
stones.

Prisoners receive one-tenth of the sum their handiwork earns. A


curious custom is that every adult prisoner is kept for an additional
six months after his sentence expires unless he is claimed by friends
in the meantime, and if he has not reached adult age he is detained
until that is attained. During the added six months these prisoners
wear blue instead of the universal reddish garb.

“The women’s quarter at Ichigawa,” continues Norman, “is separated


from the men’s by a high wooden fence and gateway guarded by a
sentinel, and consists of two or three dormitories and one large
comfortable workshop, where all are employed together at labour let
out by contract. When I was there they were all hemming silk
handkerchiefs, each seated upon the matted floor before a little
table, and very neat they all looked, and very pretty some of them,
with their loose red gowns and simply twisted hair. ‘Those are
forgers,’ said the officer, pointing to three of them; ‘I do not like
them to be so pretty.’ One of the women had a young baby playing
beside her, and another of them as she glanced up at us showed a
face entirely different from the rest, pale, sad and refined, and I saw
that her hands were small and very white. It was Hanai Ume, the
once famous geisha of Tokio, famous for her beauty, her samisen-
playing, her dancing, her pride, and most famous of all for her
affaire d’amour. Two years ago a man-servant managed to make
trouble between herself and her lover, whom she expected to buy
her out of the life of a professional musician at anybody’s call, and
then offered to make peace again between them on his own terms.
So one night she called him out of the house and stabbed him to
death with a kitchen knife. Now music is mute for her and song is
silent and love is left behind.

“To the gallows is an easy transition, as it is a natural conclusion. In


a secluded part of the grounds at Ichigawa, there is a forbidding
object like a great black box, raised six feet from the earth at the
foot of a long incline cut in the grass. A sloping walk of black boards
leads into the box on the left-hand side. The condemned criminal is
led up this and finds himself inside upon the drop. The rope is
adjusted and the cap fitted, and then at a signal the bottom of the
box falls back. Thus the Japanese method is exactly the opposite of
our own, the official spectators, including a couple of privileged
reporters, being spared the ghastly details of the toilette on the
scaffold, and seeing nothing until an unrecognisable corpse is
suddenly flung out and dangles before them.”

The state of Japanese advancement in matters of penology is shown


by the fact that in Tokio a school is maintained for the training of
prison officials in theory and practice, with an annual attendance of
from eighty to one hundred students. They are instructed in the laws
relating to prisons and prisoners, in the general outline of the penal
code, the sanitary care of prisons, the treatment of criminal patients,
and kindred subjects.

The number of felons and misdemeanants is decreasing annually,


while there has been a slight increase, on the other hand, in the
number of contraveners. There are three disciplinary punishments in
the prisons: first, solitary confinement in a windowed cell; second,
reduction of food supply; third, solitary confinement in a dark room.

Medals are granted by the prison governors as rewards to any


prisoners who have worked diligently and conducted themselves
properly in prison, but no medal can be awarded more than three
times to any one individual. Medallists enjoy certain privileges and
leniency of treatment, and pardons are based on the medal system.
PRISONS OF EGYPT
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookball.com

You might also like