bidvertiser

Friday, September 12, 2008

Example 4 file reading

PHP file reading

The fgets( ) function.
The fgets() functions is used to read a line from a file. Using this function we either read the entire line into a string or specify the number characters we like to read.
fgets ($handle, $length);
$handle - the file pointer
$length - number of bytes to read. If length is not specified it will read at the end of the line.

Example open for read

PHP file open for read

fopen ($filename, $mode);
Arguments same as before. Return value same as mode write already seen.
Read mode table.

Example code 4 create & open

PHP file create and open

The fopen( ) function.
fopen ($filename, $mode);
$filename - the name of the file. This may also include the absolute path where you want to create the file. Example, "/www/myapp/myfile.txt".
$mode - mode is used to specify how you want to create the file. For example, you can set the mode to create for read only, or create a file for read and write. Below is the list of possible modes you can use.
If successful this function returns the file handle, otherwise it returns a false value.

Other functions

bool session_is_registered ( string $name )
Finds out whether a global variable is registered in a session.

bool isset($_SESSION[$name]) may also be used.

void session_unset ( void )
The session_unset() function frees all session variables currently registered.
No value is returned.

bool session_unregister ( string $name )
session_unregister() unregisters the global variable named name from the current session.
string session_save_path ([ string $path ] )
session_save_path() returns the path of the current directory used to save session data.

bool session_destroy ( void )
session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie.
Returns TRUE on success or FALSE on failure.

Monday, September 8, 2008

Session Name & ID

string session_name ([ string $name ] )
session_name() returns the name of the current session.
The session name is reset to the default value stored in session.name at request startup time.

string session_id ([ string $id ] )
session_id() is used to get or set the session id for the current session.
The constant SID can also be used to retrieve the current name and session id as a string suitable for adding to URLs.

bool session_regenerate_id ([ bool $delete_old_session ] )
session_regenerate_id() will replace the current session id with a new one, and keep the current session information.

Session Start

bool session_start ( void )
Creates a session or resumes the current one based on the current session id that's being passed via a request, such as GET, POST, or a cookie.
This function always returns TRUE.
Example:
?>

PHP Session Functions Reference

session_cache_expire — Return current cache expire
session_cache_limiter — Get and/or set the current cache limiter
session_commit — Alias of session_write_close
session_decode — Decodes session data from a string
session_destroy — Destroys all data registered to a session
session_encode — Encodes the current session data as a string
session_get_cookie_params — Get the session cookie parameters
session_id — Get and/or set the current session id
session_is_registered — Find out whether a global variable is registered in a session
session_module_name — Get and/or set the current session module
session_name — Get and/or set the current session name
session_regenerate_id — Update the current session id with a newly generated one
session_register — Register one or more global variables with the current session
session_save_path — Get and/or set the current session save path
session_set_cookie_params — Set the session cookie parameters
session_set_save_handler — Sets user-level session storage functions
session_start — Initialize session data
session_unregister — Unregister a global variable from the current session
session_unset — Free all session variables
session_write_close — Write session data and end session

What is a PHP Session?

A way to preserve certain data across subsequent accesses.

A session allows you to store user information on the server for later use (i.e. username, shopping cart items, etc).

A session stores such information in the form of session variables for as long as the user is logged in or the application is running.
SAMPLE CODE:
$_SESSION["username"] = “IMRAN";
$_SESSION[“nickname"] = “delta";

?>

PHP Form handling – POST Method


To receive data from POST method form we can use $_POST[ ] collection.
echo "Your name is: ".$_POST["txtName"]."
";
echo "Your roll number is: ".$_POST["txtRno"]."
";
echo "Your address is: ".$_POST["txtAdrs"]."
";
?>

PHP provides another collection by the name $_REQUEST[ ].
This collection may be used for both the methods; GET & POST.

foreach ($_REQUEST as $key => $value)
{
echo $key."=".$value."
";
}
?>

PHP Form handling – GET Method

HTML Forms same as before.
Two submission methods: POST and GET.






The ‘include’ and ‘require’ functions Example

Example:

The ‘include’ and ‘require’ functions

Include and require are used to reuse external php scripts that may contain HTML, PHP, etc.

DATE & TIME Formats

The basic PHP date and time functions let you format timestamps for use in database queries or simply for displaying the date and time in the browser window.
PHP includes the following date and time functions:
date(format)
Returns the current server time, formatted according to a given set of parameters.

checkdate(month, day, year)
Validates a given date. Successful validation means that the year is between 0 and 32767, the month is between 1 and 12, and the proper number of days in each month.

time()
Returns the current server time, measured in seconds since the Epoch or January 1, 1970.
a Prints "am" or "pm“
A Prints "AM" or "PM".
h Hour in 12-hour format (01 to 12)
H Hour in 24-hour format (00 to 23)
g Hour in 12-hour format without a leading zero (1 to 12)
G Hour in 24-hour format without a leading zero (0 to 23)
i Minutes (00 to 59)
s Seconds (00 to 59)
d Day of the month in two digits (01 to 31)
D Day of the week in text (Mon to Sun)
l Day of the week in long text (Monday to Sunday)
F Month in long text (January to December)
n Month in two digits (1 to 12)
Y Year in four digits (2005)
y Year in two digits (05)
s English ordinal suffix (th, nd, st)

SAMPLE CODES

PHP Contents (Continued)

PHP Strings.
•Strings can be specified using one of two sets of delimiters.
•If the string is enclosed in double-quotes ("), variables within the string will be expanded (subject to some parsing limitations).
•As in C the backslash ("\") character can be used in specifying special characters:



String manipulation functions.
•substr(,,[]);
•strlen();
•trim();
•ltrim(); // Trim left
•rtrim(); // Trim right
•strtolower();
•strtoupper();
•str_replace(,,,[]);
•strpos(, );
•strcmp(,); (Binary safe string comparison)
•strcasecmp(,); (Binary safe case-insensitive comparison)
•explode(,,[]); (Break string into array)
•implode(,); (Join array into string separated by delim)

PHP Contents (Continued)

The IF statement.
if ()
{ ; }
elseif ()
{ ; }
else
{ ; }
The inline (ternary) if.
? true : false;





The switch-case statement.
switch ()
{
case :
;
[break;]
case :
;
[break;]
default:
;
}



The for loop statement.
for (;;)
{
;
}
The foreach loop statement.
foreach ( as [ => ])
{
;
[break];
[continue];
}



The while loop statement.
while ()
{
;
}
The do-while loop statement.
do
{
;
} while ();



The PHP functions.
function ([])
{
;
[return ;]
}

PHP Contents (Continued)

Comments in PHP.
–// Comment text
–/* Multi-line comment text */
–# Comment text


Operators in PHP.
•Arithmetic Operators.
–+ (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulus)
•Relational Operators.
–== (Equal), === (Equal with type comparison),
–!= (Not equal), <> (Not equal), !== (Not Equal with type comparison),
–< (Less than), > (Greater than), <= (Less than or equal to), >= (Greater than or equal to)
•Logical Operators.
–! (logical NOT), && (logical AND), (logical OR), xor (logical XOR)
•Assignment Operators.
–= (Assign), += (Addition), -= (Subtraction), *= (Multiplication), /= (Division),
–.=(Concatenation), %= (Modulus), &= (And), = (Or),
–^= (Exclusive Or), <<= (Left Shift), >>=(Right Shift)
•Concatenation Operator.
–. (dot)


Predefined Super Globals.
•$GLOBALS (Access all global variables in script)
•$_SERVER (Access web server variables)
•$_GET (Values passed to script through URL)
•$_POST (Values passed to script through HTTP Post)
•$_COOKIE (Values passed by user cookie)
•$_FILES (Values passed by HTTP Post File Uploads)
•$_ENV (Values passed to script via the environment)
•$_REQUEST (Values passed by URL, HTTP Post, or user Cookies)
•$_SESSION (Values passed through user's session)

PHP Contents

Data Types & Variable Declarations.
•Data Types.
–integer, float, boolean, string, array, object, resource, NULL
•Variable Declarations.
–$variablename = ;
–$anothervariable =& $variablename; (Assign by Reference)
•Array Declarations.
–$arrayname = array();

More on arrays.
$a[0] = "abc";
$a[1] = "def";
$b["foo"] = 13; (Associative subscript).
You can also create an array by simply adding values to the array.
When you assign a value to an array variable using empty brackets, the value will be added onto the end of the array.
$a[] = "hello"; // $a[2] == "hello"
$a[] = "world"; // $a[3] == "world"

Double dimension arrays.
$arr[2][3] = array();
$arr[0][0] = 34;

Array Functions.
•sort(); (Sort array assigns new keys)
•asort(); (Sort array maintain keys)
•rsort(); (Sort array in reverse, new keys)
•arsort(); (Sort array in reverse, maintain keys)
•count(); (Count elements)
•count(,COUNT_RECURSIVE); (Count multidimensional array)
•array_push(,); (Push item onto end of array)
•array_pop(); (Pop item off end of array)