Wednesday, 26 December 2012

CLI SAPI differences


In many ways, the CLI SAPI works in the same way as the CGI SAPI and other SAPIs. However, it is important to keep track of where it differs and why, because it will directly affect how you write your scripts. The three easiest to remember differences are that the CLI SAPI does not output headers, does not use HTML formatting for its error messages, and also does not change the working directory to that of the script. The latter is particularly important - when using the CGI SAPI, calling /home/paul/foo.php would set the working directory (where it references files and other objects from) to /home/paul. This is not the same for the CLI SAPI - it uses the location of the CLI SAPI binary as its working directory.

Four php.ini directives are automatically overridden when using the CLI SAPI. These are: html_errors, implicit_flush, max_execution_time, and register_argc_argv. html_errors is set to False by default because, naturally, one is working inside a shell where HTML would only clutter things. implicit_flush is set to True by default. For those unfamiliar with how PHP works, it internally buffers output, sending it to output in chunks. When implicit_flush is set to True , PHP sends any output from print, echo, etc, straight to output without trying to buffer it. In PHP's normal operating environment, the web, this can slow things down tremendously, and is generally not advised. However, it would not be very helpful for PHP to buffer things when the output is a shell, because users want their feedback immediately. As such, implicit_flush defaults to False for the CLI SAPI.

Owing to the fact that shell scripts can run for much longer than web scripts, max_execution_time defaults to 0 for the CLI SAPI. This allows your shell scripts to have an infinite execution time. Finally, register_argc_argv is automatically set to True to allow you easy access to argc (the number of arguments passed to your script) and argv (an array of the arguments themselves). The final key difference between the CLI SAPI and other SAPIs is that the CLI SAPI automatically sets the constants STDIN, STDOUT, and STDERR for you, simply because you are likely to be working with at least one of these three fairly regularly. These are common terms in the Unix world, but if you're on Windows it might be the first time you've heard them. Put simply, each process (program) has a place where it can write its output, accept input, and print errors. By default these are all the terminal that launched the program, but they can be redirected so that, for example, one programs STDIN (input) might read from another's STDOUT (output), thereby chaining them together.

As the CLI SAPI is designed to work with the terminal, these three streams are opened for you as constants so you have easy access to them. Also, it is important to note that there are two ways you can execute your PHP scripts. The first way is to use php -f /path/to/yourfile.php - this simply calls the binary and passes your script as a parameter and is a little clumsy, if effective. My preferred manner is to chmod +x PHP files I wish to call from a shell, then add an appropriate shebang line at the top, something like this: #!/usr/local/bin/php.

Shell scripts

A Command Line Interface Server Application Programming Interface (CLI SAPI) has existed for 

PHP since v4.2, but only with the release of 4.3 did it come to maturity. In PHP 5 it is built 

automatically, and can be configured to be installed automatically also. Although you can use 

the code given here in previous versions of PHP, you may encounter problems with versions 

prior to PHP 4.3.


If you are not already using shell scripts as part of your daily life, you are probably expending 

too much energy on little tasks! Shell scripts are a great way to automate repetitive tasks, 

receive and process user input, and create basic applications.

Using PHP to build your shell scripts allows you to not only take advantage of the power and 

flexibility inherent to the language, but it also brings you one more step closer to the magical 

day when you can type "rm /usr/bin/perl" and not worry about the repercussions!

PHP-CLI can also be used as part of a daisy-chain between other commands. 

For example: php -f foo.php | sort -u > myfile.txt. 


Sunday, 2 December 2012

Create a Connection to a MySQL Database

Before you can access data in a database, you must create a connection to the database.
In PHP, this is done with the mysql_connect() function.

Syntax

mysql_connect(servername,username,password);

Parameter Description
servername Optional. Specifies the server to connect to. Default value is "localhost:3306"
username Optional. Specifies the username to log in with. Default value is the name of the user that owns the server process
password Optional. Specifies the password to log in with. Default is ""
Note: There are more available parameters, but the ones listed above are the most important. Visit our full PHP MySQL Reference for more details.

Example

In the following example we store the connection in a variable ($con) for later use in the script. The "die" part will be executed if the connection fails:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

// some code
?>

Closing a Connection

The connection will be closed automatically when the script ends. To close the connection before, use the mysql_close() function:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

// some code

mysql_close($con);
?>

PHP Variables

As with algebra, PHP variables are used to hold values or expressions.
A variable can have a short name, like x, or a more descriptive name, like carName.
Rules for PHP variable names:
  • Variables in PHP starts with a $ sign, followed by the name of the variable
  • The variable name must begin with a letter or the underscore character
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • A variable name should not contain spaces
  • Variable names are case sensitive (y and Y are two different variables)

Creating (Declaring) PHP Variables

PHP has no command for declaring a variable.
A variable is created the moment you first assign a value to it:
$myCar="Volvo";
After the execution of the statement above, the variable myCar will hold the value Volvo.
Tip: If you want to create a variable without assigning it a value, then you assign it the value of null.

Thursday, 29 November 2012

Apache Handlers - Running HTML as PHP

Apache handlers allow you to control what Apache will do with certain file types. When Apache sees a file, it has an action built in for that file type, and will perform that action.

If you wish Apache to do a different action, you will need to make a handler to tell Apache to perform that action. For example, if you use a file type that requires a special service to run it, such as a file with server side includes that is not named with a .shtml extension, you need to tell Apache to treat these files differently.

To get regular html pages to handle php code, you need to add this line to your htaccess file.

It is highly recommended that you never allow html pages to automatically handle php or shtml, because this forces all of your html pages to be processed by the server first. Instead, please rename your files to .php or .shtml whenever possible.

System Mime Type defaults
Handler Code File Extensions
application/x-hdf hdf
application/vnd.wap.wbxml wbxml
image/x-xbitmap xbm
image/x-icon ico
image/vnd.djvu djvu djv
application/x-troff-me me
application/perl pl plx ppl perl pm
application/x-tcl tcl
image/bmp bmp
text/x-sql sql
image/png png
text/x-log log
audio/x-realaudio ra
application/x-latex latex
application/x-director dcr dir dxr
text/rtf rtf
application/xhtml+xml xhtml xht
application/vnd.ms-powerpoint ppt
application/x-csh csh
image/svg+xml svg
application/x-troff-ms ms
image/x-rgb rgb
application/x-img img
image/jpeg jpeg jpg jpe
image/x-portable-pixmap ppm
text/plain asc txt
image/cgm cgm
application/x-sh sh
application/andrew-inset ez
application/vnd.wap.wmlscriptc wmlsc
text/x-registry reg
video/vnd.mpegurl mxu
image/ief ief
audio/x-pn-realaudio ram rm
image/x-xpixmap xpm
video/mpeg mpeg mpg mpe
text/tab-separated-values tsv
application/rdf+xml rdf
application/x-httpd-php phtml php php3 php4 php5 php6
x-conference/x-cooltalk ice
image/tiff tiff tif
text/richtext rtx
text/css css
application/ruby rb
application/x-wais-source src
application/xml xml xsl
application/voicexml+xml vxml
image/x-portable-graymap pgm
chemical/x-xyz xyz
model/iges igs iges
application/vnd.mif mif
application/mathml+xml mathml
application/x-ustar ustar
application/x-troff-man man
text/vbscript vbs
text/calendar ics ifb
chemical/x-pdb pdb
application/smil smi smil
application/srgs+xml grxml
image/x-portable-anymap pnm
application/x-shockwave-flash swf
audio/mpeg mpga mp2 mp3
video/x-sgi-movie movie
application/cgi cgi
application/x-cpio cpio
application/x-javascript js
text/x-setext etx
audio/basic au snd
text/sgml sgml sgm
application/x-tar tgz tar
application/vnd.mozilla.xul+xml xul
application/x-futuresplash spl
application/xslt+xml xslt
model/mesh msh mesh silo
application/mac-binhex40 hqx
text/vnd.wap.wml wml
image/x-cmu-raster ras
application/x-sv4cpio sv4cpio
audio/x-aiff aif aiff aifc
application/x-gtar gtar
audio/x-ms-wax wax
audio/x-ms-wma wma
image/x-xwindowdump xwd
application/x-cdlink vcd
application/msword doc
video/quicktime qt mov
application/x-bcpio bcpio
application/x-tex tex
text/x-config cnf conf
application/x-sv4crc sv4crc
application/x-dvi dvi
application/x-troff t tr roff
audio/x-mpegurl m3u
application/x-shar shar
audio/mp4 a-latm m4p m4a mp4
application/pdf pdf
application/mac-compactpro cpt
application/vnd.wap.wmlc wmlc
video/x-msvideo avi
application/ogg ogg
text/html html htm shtml
image/gif gif
audio/midi mid midi kar
application/x-pkcs7-crl crl
application/x-chess-pgn pgn
audio/x-pn-realaudio-plugin rpm
application/srgs gram
application/x-koan skp skd skt skm
image/vnd.wap.wbmp wbmp
application/x-netcdf nc cdf
model/vrml wrl vrml
application/x-httpd-php-source phps
application/vnd.ms-excel xls
application/postscript ai eps ps
application/x-texinfo texinfo texi
application/zip zip
image/x-portable-bitmap pbm
audio/x-wav wav
application/x-x509-ca-cert crt
application/oda oda
application/xml-dtd dtd
application/octet-stream bin dms lha lzh exe class so dll iso dmg
text/vnd.wap.wmlscript wmls
application/x-stuffit sit