Wednesday, May 5, 2010

Flickr

This is a test post from flickr, a fancy photo sharing thing.

Wednesday, March 31, 2010

PHP Tutorial User Registration SQL

A quick and easy user registration using php, sql and phpmyadmin.


For full size and source codes: http://www.neoblob.com/phpsquad/tuts/...

SQL:
CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL auto_increment,
`username` varchar(20) NOT NULL default '',
`password` varchar(50) NOT NULL default '',
`email` varchar(40) NOT NULL default '',
`ip` varchar(20) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Make A Website Publicly accessible with Port Forwarding Linksys Router networknerd007 41 videos

This tutorial shows how to make your Apache/XAMPP for Windows XP/Vista or Linux Ubuntu web server accessible to the public people over the internet by properly configuring and forwarding your ports through your router. I use a Linksys WRT54G in this tutorial, but it should be really close to the same on all Linksys routers and fairly familiar on other brands as well.

Tuesday, March 30, 2010

Build a Web Form in Dreamweaver!

In the following video we will build a web based form using html. We will cover using Labels, Text Fields, Text Boxes, Radio Button Groups, Checkboxes, The Clear and Submit buttons, Drop down Menus, as well as many of the properties you can edit while building the form. The form will be ready to be linked with a PHP file for use when you are finished with this video. Get ready to learn a whole lot! Have fun and check out http://www.tutvid.com for more great videos and downloads!

PHP Tutorial - 23 - Adding Tables to MySQL Database

PHP & MySQL Tutorial 08: logging in with MySQL Part 1

This tutorial goes over the concept of a login system in PHP while using sessions(to maintain the login status) and MySQL(a database that holds the information).
[click more info to see link to sources online]
(Hint: don't forget about Part 2 http://www.youtube.com/watch?v=ir12sx... I first go over how to make the login page, then the table in the database. After that, I make a user through PHPMyAdmin(the next tutorial will likely go over registering users). I then code how to validate that user and if they are validated, set the session information. After the session information is acceptable, they can go to a "members only" page which only allows identified people in. Then a way to log out.
This tutorial is pretty much a walkthrough in concept of a mysql login system.

PHP Basics: Install a Webserver with PHP and MySQL (Windows)

Get started with PHP by installing a webserver with PHP and MySQL support. For ease of use and convenience, i'll be showing you how to install XAMPP available from http://www.apachefriends.org/en/xampp...

Monday, March 29, 2010

PHP Mysql Tutorial

Flash PHP MySQL CMS - Content Management System Website Tutorial CS3 + CS4

PHP Tutorial - 24 - Connecting to MySQL Database

wanna watch this tutorial in high def? http://www.youtube.com/watc... there ya go! and don't forget to subscri...

PHP Tutorials: MySQL (Part 1)


Using phpMyAdmin to create a new table on a database. The basics!

Insert data Into Mysql Using PHP - Tutorial

A tutorial from - www.Pic2res.com How to Insert data Into Mysql Using PHP , step by step tutorial for beginners

Friday, March 19, 2010

Array Operators

Array Operators

Example Name Result
$a + $b Union Union of $a and $b.
$a == $b Equality TRUE if $a and $b have the same key/value pairs.
$a === $b Identity TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
$a != $b Inequality TRUE if $a is not equal to $b.
$a <> $b Inequality TRUE if $a is not equal to $b.
$a !== $b Non-identity TRUE if $a is not identical to $b.

The + operator appends the right handed array to the left handed, whereas duplicated keys are NOT overwritten.



$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");

$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);

$c = $b + $a; // Union of $b and $a
echo "Union of \$b and \$a: \n";
var_dump($c);
?>


When executed, this script will print the following: Union of $a and $b:
array(3) {
["a"]=>
string(5) "apple"
["b"]=>
string(6) "banana"
["c"]=>
string(6) "cherry"
}
Union of $b and $a:
array(3) {
["a"]=>
string(4) "pear"
["b"]=>
string(10) "strawberry"
["c"]=>
string(6) "cherry"
}


Elements of arrays are equal for the comparison if they have the same key and value.

????? 15-5. Comparing arrays

$a = array("apple", "banana");
$b = array(1 => "banana", "0" => "apple");

var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>

array_merge_recursive

(PHP 4 >= 4.0.1, PHP 5)

array_merge_recursive -- Merge two or more arrays recursively
Description
array array_merge_recursive ( array array1 [, array ...] )


array_merge_recursive() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.

????? 1. array_merge_recursive() example

$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
?>

The $result will be:

Array
(
[color] => Array
(
[favorite] => Array
(
[0] => red
[1] => green
)

[0] => blue
)

[0] => 5
[1] => 10

dns_get_record

PHP 5)

dns_get_record -- Fetch DNS Resource Records associated with a hostname
Description
array dns_get_record ( string hostname [, int type [, array &authns, array &addtl]] )



????: This function is not implemented on Windows platforms, nor does it (currently) work on *BSD systems. Try the PEAR class Net_DNS.


This function returns an array of associative arrays. Each associative array contains at minimum the following keys:

???? 1. Basic DNS attributes

Attribute Meaning
host The record in the DNS namespace to which the rest of the associated data refers.
class dns_get_record() only returns Internet class records and as such this parameter will always return IN.
type String containing the record type. Additional attributes will also be contained in the resulting array dependant on the value of type. See table below.
ttl Time To Live remaining for this record. This will not equal the record's original ttl, but will rather equal the original ttl minus whatever length of time has passed since the authoritative name server was queried.


hostname should be a valid DNS hostname such as "www.example.com". Reverse lookups can be generated using in-addr.arpa notation, but gethostbyaddr() is more suitable for the majority of reverse lookups.

By default, dns_get_record() will search for any resource records associated with hostname. To limit the query, specify the optional type parameter. type may be any one of the following: DNS_A, DNS_CNAME, DNS_HINFO, DNS_MX, DNS_NS, DNS_PTR, DNS_SOA, DNS_TXT, DNS_AAAA, DNS_SRV, DNS_NAPTR, DNS_A6, DNS_ALL or DNS_ANY. The default is DNS_ANY.

????: Because of eccentricities in the performance of libresolv between platforms, DNS_ANY will not always return every record, the slower DNS_ALL will collect all records more reliably.


The optional third and fourth arguments to this function, authns and addtl are passed by reference and, if given, will be populated with Resource Records for the Authoritative Name Servers, and any Additional Records respectively. See the example below.


???? 2. Other keys in associative arrays dependant on 'type'

Type Extra Columns
A ip: An IPv4 addresses in dotted decimal notation.
MX pri: Priority of mail exchanger. Lower numbers indicate greater priority. target: FQDN of the mail exchanger. See also dns_get_mx().
CNAME target: FQDN of location in DNS namespace to which the record is aliased.
NS target: FQDN of the name server which is authoritative for this hostname.
PTR target: Location within the DNS namespace to which this record points.
TXT txt: Arbitrary string data associated with this record.
HINFO cpu: IANA number designating the CPU of the machine referenced by this record. os: IANA number designating the Operating System on the machine referenced by this record. See IANA's Operating System Names for the meaning of these values.
SOA mname: FQDN of the machine from which the resource records originated. rname: Email address of the administrative contain for this domain. serial: Serial # of this revision of the requested domain. refresh: Refresh interval (seconds) secondary name servers should use when updating remote copies of this domain. retry: Length of time (seconds) to wait after a failed refresh before making a second attempt. expire: Maximum length of time (seconds) a secondary DNS server should retain remote copies of the zone data without a successful refresh before discarding. minimum-ttl: Minimum length of time (seconds) a client can continue to use a DNS resolution before it should request a new resolution from the server. Can be overridden by individual resource records.
AAAA ipv6: IPv6 address
A6(PHP >= 5.1.0) masklen: Length (in bits) to inherit from the target specified by chain. ipv6: Address for this specific record to merge with chain. chain: Parent record to merge with ipv6 data.
SRV pri: (Priority) lowest priorities should be used first. weight: Ranking to weight which of commonly prioritized targets should be chosen at random. target and port: hostname and port where the requested service can be found. For additional information see: RFC 2782
NAPTR order and pref: Equivalent to pri and weight above. flags, services, regex, and replacement: Parameters as defined by RFC 2915.



????: Per DNS standards, email addresses are given in user.host format (for example: hostmaster.example.com as opposed to hostmaster@example.com), be sure to check this value and modify if necessary before using it with a functions such as mail().


????? 1. Using dns_get_record()

$result = dns_get_record("php.net");
print_r($result);
?>

Produces output similar to the following:

Array
(
[0] => Array
(
[host] => php.net
[type] => MX
[pri] => 5
[target] => pair2.php.net
[class] => IN
[ttl] => 6765
)

[1] => Array
(
[host] => php.net
[type] => A
[ip] => 64.246.30.37
[class] => IN
[ttl] => 8125
)

)



Since it's very common to want the IP address of a mail server once the MX record has been resolved, dns_get_record() also returns an array in addtl which contains associate records. authns is returned as well containing a list of authoritative name servers.

????? 2. Using dns_get_record() and DNS_ANY

/* Request "ANY" record for php.net,
and create $authns and $addtl arrays
containing list of name servers and
any additional records which go with
them */
$result = dns_get_record("php.net", DNS_ANY, $authns, $addtl);
echo "Result = ";
print_r($result);
echo "Auth NS = ";
print_r($authns);
echo "Additional = ";
print_r($addtl);
?>

Produces output similar to the following:

Result = Array
(
[0] => Array
(
[host] => php.net
[type] => MX
[pri] => 5
[target] => pair2.php.net
[class] => IN
[ttl] => 6765
)

[1] => Array
(
[host] => php.net
[type] => A
[ip] => 64.246.30.37
[class] => IN
[ttl] => 8125
)

)
Auth NS = Array
(
[0] => Array
(
[host] => php.net
[type] => NS
[target] => remote1.easydns.com
[class] => IN
[ttl] => 10722
)

[1] => Array
(
[host] => php.net
[type] => NS
[target] => remote2.easydns.com
[class] => IN
[ttl] => 10722
)

[2] => Array
(
[host] => php.net
[type] => NS
[target] => ns1.easydns.com
[class] => IN
[ttl] => 10722
)

[3] => Array
(
[host] => php.net
[type] => NS
[target] => ns2.easydns.com
[class] => IN
[ttl] => 10722
)

)
Additional = Array
(
[0] => Array
(
[host] => pair2.php.net
[type] => A
[ip] => 216.92.131.5
[class] => IN
[ttl] => 6766
)

[1] => Array
(
[host] => remote1.easydns.com
[type] => A
[ip] => 64.39.29.212
[class] => IN
[ttl] => 100384
)

[2] => Array
(
[host] => remote2.easydns.com
[type] => A
[ip] => 212.100.224.80
[class] => IN
[ttl] => 81241
)

[3] => Array
(
[host] => ns1.easydns.com
[type] => A
[ip] => 216.220.40.243
[class] => IN
[ttl] => 81241
)

[4] => Array
(
[host] => ns2.easydns.com
[type] => A
[ip] => 216.220.40.244
[class] => IN
[ttl] => 81241
)

)

array_map

PHP 4 >= 4.0.6, PHP 5)

array_map -- Applies the callback to the elements of the given arrays
Description
array array_map ( callback callback, array arr1 [, array ...] )


array_map() returns an array containing all the elements of arr1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()

????? 1. array_map() example

function cube($n)
{
return($n * $n * $n);
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?>

This makes $b have:

Array
(
[0] => 1
[1] => 8
[2] => 27
[3] => 64
[4] => 125
)




????? 2. array_map() - using more arrays

function show_Spanish($n, $m)
{
return("The number $n is called $m in Spanish");
}

function map_Spanish($n, $m)
{
return(array($n => $m));
}

$a = array(1, 2, 3, 4, 5);
$b = array("uno", "dos", "tres", "cuatro", "cinco");

$c = array_map("show_Spanish", $a, $b);
print_r($c);

$d = array_map("map_Spanish", $a , $b);
print_r($d);
?>

The above example will output:

// printout of $c
Array
(
[0] => The number 1 is called uno in Spanish
[1] => The number 2 is called dos in Spanish
[2] => The number 3 is called tres in Spanish
[3] => The number 4 is called cuatro in Spanish
[4] => The number 5 is called cinco in Spanish
)

// printout of $d
Array
(
[0] => Array
(
[1] => uno
)

[1] => Array
(
[2] => dos
)

[2] => Array
(
[3] => tres
)

[3] => Array
(
[4] => cuatro
)

[4] => Array
(
[5] => cinco
)

)




Usually when using two or more arrays, they should be of equal length because the callback function is applied in parallel to the corresponding elements. If the arrays are of unequal length, the shortest one will be extended with empty elements.

An interesting use of this function is to construct an array of arrays, which can be easily performed by using NULL as the name of the callback function

????? 3. Creating an array of arrays

$a = array(1, 2, 3, 4, 5);
$b = array("one", "two", "three", "four", "five");
$c = array("uno", "dos", "tres", "cuatro", "cinco");

$d = array_map(null, $a, $b, $c);
print_r($d);
?>

The above example will output:

Array
(
[0] => Array
(
[0] => 1
[1] => one
[2] => uno
)

[1] => Array
(
[0] => 2
[1] => two
[2] => dos
)

[2] => Array
(
[0] => 3
[1] => three
[2] => tres
)

[3] => Array
(
[0] => 4
[1] => four
[2] => cuatro
)

[4] => Array
(
[0] => 5
[1] => five
[2] => cinco
)

)

New Functions

In PHP 5 there are some new functions. Here is the list of them:

Arrays:


array_combine() - Creates an array by using one array for keys and another for its values

array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function

array_udiff() - Computes the difference of arrays by using a callback function for data comparison

array_udiff_assoc() - Computes the difference of arrays with additional index check. The data is compared by using a callback function

array_udiff_uassoc() - Computes the difference of arrays with additional index check. The data is compared by using a callback function. The index check is done by a callback function also

array_walk_recursive() - Apply a user function recursively to every member of an array

array_uintersect_assoc() - Computes the intersection of arrays with additional index check. The data is compared by using a callback function

array_uintersect_uassoc() - Computes the intersection of arrays with additional index check. Both the data and the indexes are compared by using a callback functions

array_uintersect() - Computes the intersection of arrays. The data is compared by using a callback function

InterBase:


ibase_affected_rows() - Return the number of rows that were affected by the previous query

ibase_backup() - Initiates a backup task in the service manager and returns immediately

ibase_commit_ret() - Commit a transaction without closing it

ibase_db_info() - Request statistics about a database

ibase_drop_db() - Drops a database

ibase_errcode() - Return an error code

ibase_free_event_handler() - Cancels a registered event handler

ibase_gen_id() - Increments the named generator and returns its new value

ibase_maintain_db() - Execute a maintenance command on the database server

ibase_name_result() - Assigns a name to a result set

ibase_num_params() - Return the number of parameters in a prepared query

ibase_param_info() - Return information about a parameter in a prepared query

ibase_restore() - Initiates a restore task in the service manager and returns immediately

ibase_rollback_ret() - Rollback transaction and retain the transaction context

ibase_server_info() - Request statistics about a database

ibase_service_attach() - Connect to the service manager

ibase_service_detach() - Disconnect from the service manager

ibase_set_event_handler() - Register a callback function to be called when events are posted

ibase_wait_event() - Wait for an event to be posted by the database

iconv:


iconv_mime_decode() - Decodes a MIME header field

iconv_mime_decode_headers() - Decodes multiple MIME header fields at once

iconv_mime_encode() - Composes a MIME header field

iconv_strlen() - Returns the character count of string

iconv_strpos() - Finds position of first occurrence of a needle within a haystack

iconv_strrpos() - Finds the last occurrence of a needle within a haystack

iconv_substr() - Cut out part of a string

Streams:


stream_copy_to_stream() - Copies data from one stream to another

stream_get_line() - Gets line from stream resource up to a given delimiter

stream_socket_accept() - Accept a connection on a socket created by stream_socket_server()

stream_socket_client() - Open Internet or Unix domain socket connection

stream_socket_get_name() - Retrieve the name of the local or remote sockets

stream_socket_recvfrom() - Receives data from a socket, connected or not

stream_socket_sendto() - Sends a message to a socket, whether it is connected or not

stream_socket_server() - Create an Internet or Unix domain server socket

Date and time related:


idate() - Format a local time/date as integer

date_sunset() - Time of sunset for a given day and location

date_sunrise() - Time of sunrise for a given day and location

time_nanosleep() - Delay for a number of seconds and nanoseconds

Strings:


str_split() - Convert a string to an array

strpbrk() - Search a string for any of a set of characters

substr_compare() - Binary safe optionally case insensitive comparison of two strings from an offset, up to length characters

Other:


convert_uudecode() - decode a uuencoded string

convert_uuencode() - uuencode a string

curl_copy_handle() - Copy a cURL handle along with all of its preferences

dba_key_split() - Splits a key in string representation into array representation

dbase_get_header_info() - Get the header info of a dBase database

dbx_fetch_row() - Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set

fbsql_set_password() - Change the password for a given user

file_put_contents() - Write a string to a file

ftp_alloc() - Allocates space for a file to be uploaded

get_declared_interfaces() - Returns an array of all declared interfaces

get_headers() - Fetches all the headers sent by the server in response to a HTTP request

headers_list() - Returns a list of response headers sent (or ready to send)

http_build_query() - Generate URL-encoded query string

image_type_to_extension() - Get file extension for image-type returned by getimagesize(), exif_read_data(), exif_thumbnail(), exif_imagetype()

imagefilter() - Applies a filter to an image using custom arguments

imap_getacl() - Gets the ACL for a given mailbox

ldap_sasl_bind() - Bind to LDAP directory using SASL

mb_list_encodings() - Returns an array of all supported encodings

pcntl_getpriority() - Get the priority of any process

pcntl_wait() - Waits on or returns the status of a forked child as defined by the waitpid() system call

pg_version() - Returns an array with client, protocol and server version (when available)

php_check_syntax() - Check the syntax of the specified file

php_strip_whitespace() - Return source with stripped comments and whitespace

proc_nice() - Change the priority of the current process

pspell_config_data_dir() - Change location of language data files

pspell_config_dict_dir() - Change location of the main word list

setrawcookie() - Send a cookie without URL-encoding the value

snmp_read_mib() - Reads and parses a MIB file into the active MIB tree

sqlite_fetch_column_types() - Return an array of column types from a particular table

URL Functions

Introduction
Dealing with URL strings: encoding, decoding and parsing.

Requirements
No external libraries are needed to build this extension.

Installation
There is no installation needed to use these functions; they are part of the PHP core.

Runtime Configuration
This extension has no configuration directives defined in php.ini.

Resource Types
This extension has no resource types defined.

Predefined Constants
This extension has no constants defined.

????
base64_decode -- Decodes data encoded with MIME base64
base64_encode -- Encodes data with MIME base64
get_headers -- Fetches all the headers sent by the server in response to a HTTP request
get_meta_tags -- Extracts all meta tag content attributes from a file and returns an array
http_build_query -- Generate URL-encoded query string
parse_url -- Parse a URL and return its components
rawurldecode -- Decode URL-encoded strings
rawurlencode -- URL-encode according to RFC 1738
urldecode -- Decodes URL-encoded string
urlencode -- URL-encodes string

htmlentities

htmlentities
(PHP 3, PHP 4, PHP 5)

htmlentities -- Convert all applicable characters to HTML entities
Description
string htmlentities ( string string [, int quote_style [, string charset]] )


This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

Like htmlspecialchars(), the optional second quote_style parameter lets you define what will be done with 'single' and "double" quotes. It takes on one of three constants with the default being ENT_COMPAT:

???? 1. Available quote_style constants

Constant Name Description
ENT_COMPAT Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES Will convert both double and single quotes.
ENT_NOQUOTES Will leave both double and single quotes unconverted.


Support for the optional quote parameter was added in PHP 4.0.3.

Like htmlspecialchars(), it takes an optional third argument charset which defines character set used in conversion. Support for this argument was added in PHP 4.1.0. Presently, the ISO-8859-1 character set is used as the default.

Following character sets are supported in PHP 4.3.0 and later.

Monday, March 15, 2010

Forms of vulnerability

Incorrectly filtered escape characters

This form of SQL injection occurs when user input is not filtered for escape characters and is then passed into an SQL statement. This results in the potential manipulation of the statements performed on the database by the end user of the application.

The following line of code illustrates this vulnerability:

statement = "SELECT * FROM users WHERE name = '" + userName + "';"

This SQL code is designed to pull up the records of the specified username from its table of users. However, if the "userName" variable is crafted in a specific way by a malicious user, the SQL statement may do more than the code author intended. For example, setting the "userName" variable as

a' or 't'='t

renders this SQL statement by the parent language:

SELECT * FROM users WHERE name = 'a' OR 't'='t';

If this code were to be used in an authentication procedure then this example could be used to force the selection of a valid username because the evaluation of 't'='t' is always true.

The following value of "userName" in the statement below would cause the deletion of the "users" table as well as the selection of all data from the "userinfo" table (in essence revealing the information of every user), using an API that allows multiple statements:

a';DROP TABLE users; SELECT * FROM userinfo WHERE 't' = 't

This input renders the final SQL statement as follows:

SELECT * FROM users WHERE name = 'a';DROP TABLE users; SELECT * FROM userinfo WHERE 't' = 't';

While most SQL server implementations allow multiple statements to be executed with one call in this way, some SQL APIs such as PHP's mysql_query() do not allow this for security reasons. This prevents attackers from injecting entirely separate queries, but doesn't stop them from modifying queries.
[edit] Incorrect type handling

This form of SQL injection occurs when a user supplied field is not strongly typed or is not checked for type constraints. This could take place when a numeric field is to be used in a SQL statement, but the programmer makes no checks to validate that the user supplied input is numeric. For example:

statement := "SELECT * FROM userinfo WHERE id = " + a_variable + ";"

It is clear from this statement that the author intended a_variable to be a number correlating to the "id" field. However, if it is in fact a string then the end user may manipulate the statement as they choose, thereby bypassing the need for escape characters. For example, setting a_variable to

1;DROP TABLE users

will drop (delete) the "users" table from the database, since the SQL would be rendered as follows:

SELECT * FROM userinfo WHERE id=1;DROP TABLE users;

[edit] Vulnerabilities inside the database server

Sometimes vulnerabilities can exist within the database server software itself, as was the case with the MySQL server's mysql_real_escape_string() function[2]. This would allow an attacker to perform a successful SQL injection attack based on bad Unicode characters even if the user's input is being escaped. This bug was patched with the release of version 5.0.22 (released on 24th May 06).
[edit] Blind SQL injection

Blind SQL Injection is used when a web application is vulnerable to an SQL injection but the results of the injection are not visible to the attacker. The page with the vulnerability may not be one that displays data but will display differently depending on the results of a logical statement injected into the legitimate SQL statement called for that page. This type of attack can become time-intensive because a new statement must be crafted for each bit recovered. There are several tools that can automate these attacks once the location of the vulnerability and the target information has been established.[3]
[edit] Conditional responses

One type of blind SQL injection forces the database to evaluate a logical statement on an ordinary application screen.

SELECT booktitle FROM booklist WHERE bookId = 'OOk14cd' AND 1=1;

will result in a normal page while

SELECT booktitle FROM booklist WHERE bookId = 'OOk14cd' AND 1=2;

will likely give a different result if the page is vulnerable to a SQL injection. An injection like this may suggest to the attacker that a blind SQL injection is possible, leaving the attacker to devise statements that evaluate to true or false depending on the contents of another column or table outside of the SELECT statement's column list.[4]
[edit] Conditional errors

This type of blind SQL injection causes an SQL error by forcing the database to evaluate a statement that causes an error if the WHERE statement is true. For example,

SELECT 1/0 FROM users WHERE username='Ralph';

the division by zero will only be evaluated and result in an error if user Ralph exists.
[edit] Time delays

Time Delays are a type of blind SQL injection that cause the SQL engine to execute a long running query or a time delay statement depending on the logic injected. The attacker can then measure the time the page takes to load to determine if the injected statement is true.
[edit] Preventing SQL injection

To protect against SQL injection, user input must not directly be embedded in SQL statements. Instead, parameterized statements must be used (preferred), or user input must be carefully escaped or filtered.
[edit] Parameterized statements

With most development platforms, parameterized statements can be used that work with parameters (sometimes called placeholders or bind variables) instead of embedding user input in the statement. In many cases, the SQL statement is fixed. The user input is then assigned (bound) to a parameter. This is an example using Java and the JDBC API:

PreparedStatement prep = conn.prepareStatement("SELECT * FROM USERS WHERE USERNAME=? AND PASSWORD=?");
prep.setString(1, username);
prep.setString(2, password);
prep.executeQuery();

Similarly, in C#:

using (SqlCommand myCommand = new SqlCommand("SELECT * FROM USERS WHERE USERNAME=@username AND PASSWORD=HASHBYTES('SHA1',
@password)", myConnection))
{
myCommand.Parameters.AddWithValue("@username", user);
myCommand.Parameters.AddWithValue("@password", pass);

myConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader())
...................
}

In PHP version 5 and above, there are multiple choices for using parameterized statements. The PDO[5] database layer is one of them:

$db = new PDO('pgsql:dbname=database');
$stmt = $db->prepare("SELECT priv FROM testUsers WHERE username=:username AND password=:password");
$stmt->bindParam(':username', $user);
$stmt->bindParam(':password', $pass);
$stmt->execute();

There are also vendor-specific methods; for instance, using the mysqli[6] extension for MySQL 4.1 and above to create parameterized statements[7]:

$db = new mysqli("localhost", "user", "pass", "database");
$stmt = $db -> prepare("SELECT priv FROM testUsers WHERE username=? AND password=?");
$stmt -> bind_param("ss", $user, $pass);
$stmt -> execute();

In ColdFusion, the CFQUERYPARAM statement is useful in conjunction with the CFQUERY statement to nullify the effect of SQL code passed within the CFQUERYPARAM value as part of the SQL clause.[8][9]. An example is below.


SELECT *
FROM COMMENTS
WHERE COMMENT_ID =


[edit] Enforcement at the database level

Currently only the H2 Database Engine supports the ability to enforce query parameterization.[10] However, one drawback is that query-by-example may not be possible or practical because it's difficult to implement query-by-example using parametrized queries.
[edit] Enforcement at the coding level

Using object-relational mapping libraries avoids the need to write SQL code. The ORM library in effect will generate parameterized SQL statements from object-oriented code.
[edit] Escaping

A straight-forward, though error-prone, way to prevent injections is to escape dangerous characters. One of the reasons for it being error prone is that it is a type of blacklist which is less robust than a whitelist. For instance, every occurrence of a single quote (') in a parameter must be replaced by two single quotes ('') to form a valid SQL string literal. In PHP, for example, it is usual to escape parameters using the function mysql_real_escape_string before sending the SQL query:

$query = sprintf("SELECT * FROM Users where UserName='%s' and Password='%s'",
mysql_real_escape_string($Username),
mysql_real_escape_string($Password));
mysql_query($query);

How to check for SQL injection vulnerabilities

Securing your website and web applications from SQL Injection involves a three-part process:

1. Analysing the present state of security present by performing a thorough audit of your website and web applications for SQL Injection and other hacking vulnerabilities.
2. Making sure that you use coding best practice santising your web applications and all other components of your IT infrastructure.
3. Regularly performing a web security audit after each change and addition to your web components.

Furthermore, the principles you need to keep in mind when checking for SQL Injection and all other hacking techniques are the following: “Which parts of a website we thought are secure are open to hack attacks?” and “what data can we throw at an application to cause it to perform something it shouldn’t do?”.

Checking for SQL Injection vulnerabilities involves auditing your website and web applications. Manual vulnerability auditing is complex and very time-consuming. It also demands a high-level of expertise and the ability to keep track of considerable volumes of code and of all the latest tricks of the hacker’s ‘trade’.

The best way to check whether your web site and applications are vulnerable to SQL injection attacks is by using an automated and heuristic web vulnerability scanner.

An automated web vulnerability scanner crawls your entire website and should automatically check for vulnerabilities to SQL Injection attacks. It will indicate which URLs/scripts are vulnerable to SQL injection so that you can immediately fix the code. Besides SQL injection vulnerabilities a web application scanner will also check for Cross site scripting and other web vulnerabilities.

Signature-Matching versus Heuristic Scanning for SQL Injection
Whereas many organisations understand the need for automating and regularising web auditing, few appreciate the necessity of scanning both off-the-shelf AND bespoke web applications. The general misconception is these custom web applications are not vulnerable to hacking attacks. This arises more out of the “it can never happen to me” phenomenon and the confidence website owners place in their developers.

A search on Google News returned 240 matches on the keyword “SQL Injection” (at time of writing). Secunia and SecuObs report dozens of vulnerabilities of known web applications on a daily basis. Yet, examples of hacked custom applications are rarely cited in the media. This is because it is only the known organisations (e.g. Choicepoint, AT&T, PayPal) that hit the headlines over the past few months.

It is critical to understand that custom web applications are probably the most vulnerable and definitely attract the greatest number of hackers simply because they know that such applications do not pass through the rigorous testing and quality assurance processes of off-the-shelf ones.

This means that scanning a custom web application with only a signature-based scanner will not pinpoint vulnerabilities to SQL Injection and any other hacking techniques.

Establishing and testing against a database of signatures of vulnerabilities for known applications is not enough. This is passive auditing because it will only cover off-the-shelf applications and any vulnerabilities to new hacking techniques will not be discovered. In addition, signature matching would do little when a hacker launches an SQL Injection attack on your custom web applications. Hack attacks are not based on signature file testing – hackers understand that known applications, systems and servers are being updated and secured constantly and consistently by respective vendors. It is custom applications that are the proverbial honey pot.

It is only a handful of products that deploy rigorous and heuristic technologies to identify the real threats. True automated web vulnerability scanning almost entirely depends on (a) how well your site is crawled to establish its structure and various components and links, and (b) on the ability of the scanner to leverage intelligently the various hacking methods and techniques against your web applications.

It would be useless to detect the known vulnerabilities of known applications alone. A significant degree of heuristics is involved in detecting vulnerabilities since hackers are extremely creative and launch their attacks against bespoke web applications to create maximum impact.

How can Acunetix help you in auditing your site for SQL Injection?
Acunetix was founded to combat the alarming rise in web attacks including SQL Injection and Cross-Site Scripting among others. Take a product tour to find out how Acunetix Web Vulnerability Scanner can help you or download the scanner today!

SQL Injection: What is it?

SQL Injection is one of the many web attack mechanisms used by hackers to steal data from organizations. It is perhaps one of the most common application layer attack techniques used today. It is the type of attack that takes advantage of improper coding of your web applications that allows hacker to inject SQL commands into say a login form to allow them to gain access to the data held within your database.

In essence, SQL Injection arises because the fields available for user input allow SQL statements to pass through and query the database directly.

SQL Injection: An In-depth Explanation
Web applications allow legitimate website visitors to submit and retrieve data to/from a database over the Internet using their preferred web browser. Databases are central to modern websites – they store data needed for websites to deliver specific content to visitors and render information to customers, suppliers, employees and a host of stakeholders. User credentials, financial and payment information, company statistics may all be resident within a database and accessed by legitimate users through off-the-shelf and custom web applications. Web applications and databases allow you to regularly run your business.

SQL Injection is the hacking technique which attempts to pass SQL commands (statements) through a web application for execution by the backend database. If not sanitized properly, web applications may result in SQL Injection attacks that allow hackers to view information from the database and/or even wipe it out.

Such features as login pages, support and product request forms, feedback forms, search pages, shopping carts and the general delivery of dynamic content, shape modern websites and provide businesses with the means necessary to communicate with prospects and customers. These website features are all examples of web applications which may be either purchased off-the-shelf or developed as bespoke programs.

These website features are all susceptible to SQL Injection attacks which arise because the fields available for user input allow SQL statements to pass through and query the database directly.

SQL Injection: A Simple Example
Take a simple login page where a legitimate user would enter his username and password combination to enter a secure area to view his personal details or upload his comments in a forum.

When the legitimate user submits his details, an SQL query is generated from these details and submitted to the database for verification. If valid, the user is allowed access. In other words, the web application that controls the login page will communicate with the database through a series of planned commands so as to verify the username and password combination. On verification, the legitimate user is granted appropriate access.

Through SQL Injection, the hacker may input specifically crafted SQL commands with the intent of bypassing the login form barrier and seeing what lies behind it. This is only possible if the inputs are not properly sanitised (i.e., made invulnerable) and sent directly with the SQL query to the database. SQL Injection vulnerabilities provide the means for a hacker to communicate directly to the database.

The technologies vulnerable to this attack are dynamic script languages including ASP, ASP.NET, PHP, JSP, and CGI. All an attacker needs to perform an SQL Injection hacking attack is a web browser, knowledge of SQL queries and creative guess work to important table and field names. The sheer simplicity of SQL Injection has fuelled its popularity.

Other contents:
Why is it possible to pass SQL Queries to the database even though this is hidden behind a firewall?
Is my database at risk to SQL Injection?
What is the impact of SQL Injection?
Example of a SQL Injection Attack
How do I prevent SQL Injection attacks?

Why is it possible to pass SQL queries directly to a database that is hidden behind a firewall and any other security mechanism?
Firewalls and similar intrusion detection mechanisms provide little or no defense against full-scale SQL Injection web attacks.

Since your website needs to be public, security mechanisms will allow public web traffic to communicate with your web application/s (generally over port 80/443). The web application has open access to the database in order to return (update) the requested (changed) information.

In SQL Injection, the hacker uses SQL queries and creativity to get to the database of sensitive corporate data through the web application.

SQL or Structured Query Language is the computer language that allows you to store, manipulate, and retrieve data stored in a relational database (or a collection of tables which organise and structure data). SQL is, in fact, the only way that a web application (and users) can interact with the database. Examples of relational databases include Oracle, Microsoft Access, MS SQL Server, MySQL, and Filemaker Pro, all of which use SQL as their basic building blocks.

SQL commands include SELECT, INSERT, DELETE and DROP TABLE. DROP TABLE is as ominous as it sounds and in fact will eliminate the table with a particular name.

In the legitimate scenario of the login page example above, the SQL commands planned for the web application may look like the following:

SELECT count(*)
FROM users_list_table
WHERE username=’FIELD_USERNAME’
AND password=’FIELD_PASSWORD”

In plain English, this SQL command (from the web application) instructs the database to match the username and password input by the legitimate user to the combination it has already stored.

Each type of web application is hard coded with specific SQL queries that it will execute when performing its legitimate functions and communicating with the database. If any input field of the web application is not properly sanitised, a hacker may inject additional SQL commands that broaden the range of SQL commands the web application will execute, thus going beyond the original intended design and function.

A hacker will thus have a clear channel of communication (or, in layman terms, a tunnel) to the database irrespective of all the intrusion detection systems and network security equipment installed before the physical database server.

Is my database at risk to SQL Injection?
SQL Injection is one of the most common application layer attacks currently being used on the Internet. Despite the fact that it is relatively easy to protect against SQL Injection, there are a large number of web applications that remain vulnerable.

According to the Web Application Security Consortium (WASC) 9% of the total hacking incidents reported in the media until 27th July 2006 were due to SQL Injection. More recent data from our own research shows that about 50% of the websites we have scanned this year are susceptible to SQL Injection vulnerabilities.

It may be difficult to answer the question whether your web site and web applications are vulnerable to SQL Injection especially if you are not a programmer or you are not the person who has coded your web applications.

Our experience leads us to believe that there is a significant chance that your data is already at risk from SQL Injection.

Whether an attacker is able to see the data stored on the database or not, really depends on how your website is coded to display the results of the queries sent. What is certain is that the attacker will be able to execute arbitrary SQL Commands on the vulnerable system, either to compromise it or else to obtain information.

If improperly coded, then you run the risk of having your customer and company data compromised.

What an attacker gains access to also depends on the level of security set by the database. The database could be set to restrict to certain commands only. A read access normally is enabled for use by web application back ends.

Even if an attacker is not able to modify the system, he would still be able to read valuable information.

What is the impact of SQL Injection?
Once an attacker realizes that a system is vulnerable to SQL Injection, he is able to inject SQL Query / Commands through an input form field. This is equivalent to handing the attacker your database and allowing him to execute any SQL command including DROP TABLE to the database!

An attacker may execute arbitrary SQL statements on the vulnerable system. This may compromise the integrity of your database and/or expose sensitive information. Depending on the back-end database in use, SQL injection vulnerabilities lead to varying levels of data/system access for the attacker. It may be possible to manipulate existing queries, to UNION (used to select related information from two tables) arbitrary data, use subselects, or append additional queries.

In some cases, it may be possible to read in or write out to files, or to execute shell commands on the underlying operating system. Certain SQL Servers such as Microsoft SQL Server contain stored and extended procedures (database server functions). If an attacker can obtain access to these procedures, it could spell disaster.

Unfortunately the impact of SQL Injection is only uncovered when the theft is discovered. Data is being unwittingly stolen through various hack attacks all the time. The more expert of hackers rarely get caught.

Example of a SQLInjection Attack
Here is a sample basic HTML form with two inputs, login and password.






The easiest way for the login.asp to work is by building a database query that looks like this:

SELECT id
FROM logins
WHERE username = '$username'
AND password = '$password’

If the variables $username and $password are requested directly from the user's input, this can easily be compromised. Suppose that we gave "Joe" as a username and that the following string was provided as a password: anything' OR 'x'='x

SELECT id
FROM logins
WHERE username = 'Joe'
AND password = 'anything' OR 'x'='x'

As the inputs of the web application are not properly sanitised, the use of the single quotes has turned the WHERE SQL command into a two-component clause.

The 'x'='x' part guarantees to be true regardless of what the first part contains.

This will allow the attacker to bypass the login form without actually knowing a valid username / password combination!

How do I prevent SQL Injection attacks?
Firewalls and similar intrusion detection mechanisms provide little defense against full-scale web attacks. Since your website needs to be public, security mechanisms will allow public web traffic to communicate with your databases servers through web applications. Isn’t this what they have been designed to do?

Patching your servers, databases, programming languages and operating systems is critical but will in no way the best way to prevent SQL Injection Attacks.

Read the full article on How to Check for and Prevent SQL Injection Attacks.

Download Acunetix Web Vulnerability Scanner and find out if your site is vulnerable!

Saturday, February 20, 2010

substr_compare

int substr_compare ( string main_str, string str, int offset [, int length [, bool case_insensitivity]] )


substr_compare() compares main_str from position offset with str up to length characters.

Returns < 0 if main_str from position offset is less than str, > 0 if it is greater than str, and 0 if they are equal. If length is equal or greater than length of main_str and length is set, substr_compare() prints warning and returns FALSE.

If case_insensitivity is TRUE, comparison is case insensitive.

????? 1. A substr_compare() example

echo substr_compare("abcde", "bc", 1, 2); // 0
echo substr_compare("abcde", "bcg", 1, 2); // 0
echo substr_compare("abcde", "BC", 1, 2, true); // 0
echo substr_compare("abcde", "bc", 1, 3); // 1
echo substr_compare("abcde", "cd", 1, 2); // -1
echo substr_compare("abcde", "abc", 5, 1); // warning
?>

PHP str_word_count

mixed str_word_count ( string string [, int format [, string charlist]] )


Counts the number of words inside string. If the optional format is not specified, then the return value will be an integer representing the number of words found. In the event the format is specified, the return value will be an array, content of which is dependent on the format. The possible value for the format and the resultant outputs are listed below.

For the purpose of this function, 'word' is defined as a locale dependent string containing alphabetic characters, which also may contain, but not start with "'" and "-" characters.

Parameters


string
The string

format
Specify the return value of this function. The current supported values are:


0 - returns the number of words found

1 - returns an array containing all the words found inside the string

2 - returns an associative array, where the key is the numeric position of the word inside the string and the value is the actual word itself


charlist
A list of additional characters which will be considered as 'word'


Return Values
Returns an array or an integer, depending on the format chosen.

ChangeLog


Version Description
5.1.0 Added the charlist parameter



Examples
????? 1. A str_word_count() example


$str = "Hello fri3nd, you're
looking good today!";

print_r(str_word_count($str, 1));
print_r(str_word_count($str, 2));
print_r(str_word_count($str, 1, 'àáãç3'));

echo str_word_count($str);

?>

The above example will output:

Array
(
[0] => Hello
[1] => fri
[2] => nd
[3] => you're
[4] => looking
[5] => good
[6] => today
)

Array
(
[0] => Hello
[6] => fri
[10] => nd
[14] => you're
[29] => looking
[46] => good
[51] => today
)

Array
(
[0] => Hello
[1] => fri3nd
[2] => you're
[3] => looking
[4] => good
[5] => today
)

7

PHP mb_detect_encoding

Description
string mb_detect_encoding ( string str [, mixed encoding_list [, bool strict]] )


mb_detect_encoding() detects character encoding in string str. It returns detected character encoding.

encoding_list is list of character encoding. Encoding order may be specified by array or comma separated list string.

If encoding_list is omitted, detect_order is used.

????? 1. mb_detect_encoding() example

/* Detect character encoding with current detect_order */
echo mb_detect_encoding($str);

/* "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
echo mb_detect_encoding($str, "auto");

/* Specify encoding_list character encoding by comma separated list */
echo mb_detect_encoding($str, "JIS, eucjp-win, sjis-win");

/* Use array to specify encoding_list */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
echo mb_detect_encoding($str, $ary);

PHP strings

PHP Manual
????? ??? 11. Types ?????






Strings
A string is series of characters. In PHP, a character is the same as a byte, that is, there are exactly 256 different characters possible. This also implies that PHP has no native support of Unicode. See utf8_encode() and utf8_decode() for some Unicode support.

????: It is no problem for a string to become very large. There is no practical bound to the size of strings imposed by PHP, so there is no reason at all to worry about long strings.

Syntax
A string literal can be specified in three different ways.


single quoted

double quoted

heredoc syntax


Single quoted
The easiest way to specify a simple string is to enclose it in single quotes (the character ').

To specify a literal single quote, you will need to escape it with a backslash (\), like in many other languages. If a backslash needs to occur before a single quote or at the end of the string, you need to double it. Note that if you try to escape any other character, the backslash will also be printed! So usually there is no need to escape the backslash itself.

????: In PHP 3, a warning will be issued at the E_NOTICE level when this happens.

????: Unlike the two other syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.


echo 'this is a simple string';

echo 'You can also have embedded newlines in
strings this way as it is
okay to do';

// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';

// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';

// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>



Double quoted
If the string is enclosed in double-quotes ("), PHP understands more escape sequences for special characters:

???? 11-1. Escaped characters

sequence meaning
\n linefeed (LF or 0x0A (10) in ASCII)
\r carriage return (CR or 0x0D (13) in ASCII)
\t horizontal tab (HT or 0x09 (9) in ASCII)
\\ backslash
\$ dollar sign
\" double-quote
\[0-7]{1,3} the sequence of characters matching the regular expression is a character in octal notation
\x[0-9A-Fa-f]{1,2} the sequence of characters matching the regular expression is a character in hexadecimal notation

Again, if you try to escape any other character, the backslash will be printed too! Before PHP 5.1.1, backslash in \{$var} hasn't been printed.

But the most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.

Heredoc
Another way to delimit strings is by using heredoc syntax ("<<<"). One should provide an identifier after <<<, then the string, and then the same identifier to close the quotation.

The closing identifier must begin in the first column of the line. Also, the identifier used must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.


?????
It is very important to note that the line with the closing identifier contains no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs after or before the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by your operating system. This is \r on Macintosh for example. Closing delimiter (possibly followed by a semicolon) must be followed by a newline too.

If this rule is broken and the closing identifier is not "clean" then it's not considered to be a closing identifier and PHP will continue looking for one. If in this case a proper closing identifier is not found then a parse error will result with the line number being at the end of the script.

It is not allowed to use heredoc syntax in initializing class members. Use other string syntaxes instead. ????? 11-3. Invalid example

class foo {
public $bar = <<bar
EOT;
}
?>




Heredoc text behaves just like a double-quoted string, without the double-quotes. This means that you do not need to escape quotes in your here docs, but you can still use the escape codes listed above. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings. ????? 11-4. Heredoc string quoting example

$str = <<Example of string
spanning multiple lines
using heredoc syntax.
EOD;

/* More complex example, with variables. */
class foo
{
var $foo;
var $bar;

function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}

$foo = new foo();
$name = 'MyName';

echo <<My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>



????: Heredoc support was added in PHP 4.

Variable parsing
When a string is specified in double quotes or with heredoc, variables are parsed within it.

There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to parse a variable, an array value, or an object property.

The complex syntax was introduced in PHP 4, and can be recognised by the curly braces surrounding the expression.

Simple syntax
If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces if you want to explicitly specify the end of the name.


$beer = 'Heineken';
echo "$beer's taste is great"; // works, "'" is an invalid character for varnames
echo "He drank some $beers"; // won't work, 's' is a valid character for varnames
echo "He drank some ${beer}s"; // works
echo "He drank some {$beer}s"; // works
?>


Similarly, you can also have an array index or an object property parsed. With array indices, the closing square bracket (]) marks the end of the index. For object properties the same rules apply as to simple variables, though with object properties there doesn't exist a trick like the one with variables.


// These examples are specific to using arrays inside of strings.
// When outside of a string, always quote your array string keys
// and do not use {braces} when outside of strings either.

// Let's show all errors
error_reporting(E_ALL);

$fruits = array('strawberry' => 'red', 'banana' => 'yellow');

// Works but note that this works differently outside string-quotes
echo "A banana is $fruits[banana].";

// Works
echo "A banana is {$fruits['banana']}.";

// Works but PHP looks for a constant named banana first
// as described below.
echo "A banana is {$fruits[banana]}.";

// Won't work, use braces. This results in a parse error.
echo "A banana is $fruits['banana'].";

// Works
echo "A banana is " . $fruits['banana'] . ".";

// Works
echo "This square is $square->width meters broad.";

// Won't work. For a solution, see the complex syntax.
echo "This square is $square->width00 centimeters broad.";
?>


For anything more complex, you should use the complex syntax.

Complex (curly) syntax
This isn't called complex because the syntax is complex, but because you can include complex expressions this way.

In fact, you can include any value that is in the namespace in strings with this syntax. You simply write the expression the same way as you would outside the string, and then include it in { and }. Since you can't escape '{', this syntax will only be recognised when the $ is immediately following the {. (Use "{\$" to get a literal "{$"). Some examples to make it clear:


// Let's show all errors
error_reporting(E_ALL);

$great = 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad.";

// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong
// outside a string. In other words, it will still work but
// because PHP first looks for a constant named foo, it will
// throw an error of level E_NOTICE (undefined constant).
echo "This is wrong: {$arr[foo][3]}";

// Works. When using multi-dimensional arrays, always use
// braces around arrays when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " . $arr['foo'][3];

echo "You can even write {$obj->values[3]->name}";

echo "This is the value of the var named $name: {${$name}}";
?>


String access and modification by character
Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array-brackets like $str[42] so think of a string as an array of characters.

????: They may also be accessed using braces like $str{42} for the same purpose. However, using square array-brackets is preferred.

????? 11-5. Some string examples

// Get the first character of a string
$str = 'This is a test.';
$first = $str[0];

// Get the third character of a string
$third = $str[2];

// Get the last character of a string.
$str = 'This is still a test.';
$last = $str[strlen($str)-1];

// Modify the last character of a string
$str = 'Look at the sea';
$str[strlen($str)-1] = 'e';

// Alternative method using {}
$third = $str{2};

?>



Useful functions and operators
Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. Please see String operators for more information.

There are a lot of useful functions for string modification.

See the string functions section for general functions, the regular expression functions for advanced find&replacing (in two tastes: Perl and POSIX extended).

There are also functions for URL-strings, and functions to encrypt/decrypt strings (mcrypt and mhash).

Finally, if you still didn't find what you're looking for, see also the character type functions.

Converting to string
You can convert a value to a string using the (string) cast, or the strval() function. String conversion is automatically done in the scope of an expression for you where a string is needed. This happens when you use the echo() or print() functions, or when you compare a variable value to a string. Reading the manual sections on Types and Type Juggling will make the following clearer. See also settype().

A boolean TRUE value is converted to the string "1", the FALSE value is represented as "" (empty string). This way you can convert back and forth between boolean and string values.

An integer or a floating point number (float) is converted to a string representing the number with its digits (including the exponent part for floating point numbers).

Arrays are always converted to the string "Array", so you cannot dump out the contents of an array with echo() or print() to see what is inside them. To view one element, you'd do something like echo $arr['foo']. See below for tips on dumping/viewing the entire contents.

Objects are always converted to the string "Object". If you would like to print out the member variable values of an object for debugging reasons, read the paragraphs below. If you would like to find out the class name of which an object is an instance of, use get_class(). As of PHP 5, __toString() method is used if applicable.

Resources are always converted to strings with the structure "Resource id #1" where 1 is the unique number of the resource assigned by PHP during runtime. If you would like to get the type of the resource, use get_resource_type().

NULL is always converted to an empty string.

As you can see above, printing out the arrays, objects or resources does not provide you any useful information about the values themselves. Look at the functions print_r() and var_dump() for better ways to print out values for debugging.

You can also convert PHP values to strings to store them permanently. This method is called serialization, and can be done with the function serialize(). You can also serialize PHP values to XML structures, if you have WDDX support in your PHP setup.

String conversion to numbers
When a string is evaluated as a numeric value, the resulting value and type are determined as follows.

The string will evaluate as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will evaluate as an integer.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.


$foo = 1 + "10.5"; // $foo is float (11.5)
$foo = 1 + "-1.3e3"; // $foo is float (-1299)
$foo = 1 + "bob-1.3e3"; // $foo is integer (1)
$foo = 1 + "bob3"; // $foo is integer (1)
$foo = 1 + "10 Small Pigs"; // $foo is integer (11)
$foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2)
$foo = "10.0 pigs " + 1; // $foo is float (11)
$foo = "10.0 pigs " + 1.0; // $foo is float (11)
?>


For more information on this conversion, see the Unix manual page for strtod(3).

If you would like to test any of the examples in this section, you can cut and paste the examples and insert the following line to see for yourself what's going on:


echo "\$foo==$foo; type is " . gettype ($foo) . "
\n";
?>



Do not expect to get the code of one character by converting it to integer (as you would do in C for example). Use the functions ord() and chr() to convert between charcodes and characters.




????? ??? ???? ?????
Floating point numbers ????? Arrays


PHP captcha security source code

session_start();

/*
* File: CaptchaSecurityImages.php
* Author: Simon Jarvis
* Copyright: 2006 Simon Jarvis
* Date: 03/08/06
* Updated: 07/02/07
* Requirements: PHP 4/5 with GD and FreeType libraries
* Link: http://www.white-hat-web-design.co.uk/articles/php-captcha.php
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
* http://www.gnu.org/licenses/gpl.html
*
*/

class CaptchaSecurityImages {

var $font = 'monofont.ttf';

function generateCode($characters) {
/* list all possible characters, similar looking characters and vowels have been removed */
$possible = '23456789bcdfghjkmnpqrstvwxyz';
$code = '';
$i = 0;
while ($i < $characters) {
$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
$i++;
}
return $code;
}

function CaptchaSecurityImages($width='120',$height='40',$characters='6') {
$code = $this->generateCode($characters);
/* font size will be 75% of the image height */
$font_size = $height * 0.75;
$image = imagecreate($width, $height) or die('Cannot initialize new GD image stream');
/* set the colours */
$background_color = imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 20, 40, 100);
$noise_color = imagecolorallocate($image, 100, 120, 180);
/* generate random dots in background */
for( $i=0; $i<($width*$height)/3; $i++ ) {
imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
}
/* generate random lines in background */
for( $i=0; $i<($width*$height)/150; $i++ ) {
imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
}
/* create textbox and add text */
$textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function');
$x = ($width - $textbox[4])/2;
$y = ($height - $textbox[5])/2;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function');
/* output captcha image to browser */
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
$_SESSION['security_code'] = $code;
}

}

$width = isset($_GET['width']) && $_GET['width'] < 600 ? $_GET['width'] : '120';
$height = isset($_GET['height']) && $_GET['height'] < 200 ? $_GET['height'] : '40';
$characters = isset($_GET['characters']) && $_GET['characters'] > 2 ? $_GET['characters'] : '6';

$captcha = new CaptchaSecurityImages($width,$height,$characters);

?>