Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Advantages of MySQL and PHP

Certain technologies play together better than others. PHP, a simple and powerful scripting language, and MySQL, a solid and reliable database server, make a perfect marriage between two modern technologies for building databasedriven, dynamic Web sites. Some of the advantages of both PHP and MySQL are:
•  High performance
•  Built-in libraries
•  Extensibility
•  Relatively low cost
•  Portability
•  Developer community
•  Ease of learning
High Performance
PHP is no longer considered just a grassroots scripting language, but now with PHP 5, and its highly efficient built-in Zend engine, PHP accommodates developers and IT decision makers in the business trend to rapidly release and update software on the Web faster than conventional programming cycles have allowed.
MySQL, a highly optimized database server, provides the response time and throughput to meet the most demanding applications.With PHP scripts connected to a MySQL database, millions of pages can be served on a single inexpensive server.
Built-In Libraries
PHP comes with many built-in functions addressing common Web development tasks. Problems encountered by other programmers have been solved and packaged into a library of routines, made available to the PHP community. The official PHP Web site at http://www.php.netprovides excellent documentation explaining how to use all of the functions currently available.
Extensibility
PHP and MySQL are both extensible, meaning that developers around the world are contributing add-on modules to extend the functionality and power of the languages to stay current with the growing market needs and standards of the day. You can also obtain the source code for both PHP and MySQL. Source code is the code that a program consists of before theprogram is compiled; that is, the original building instructions of a program.
Relatively Low Cost
As a Web developer you can demand a lot more money for your time if you can master PHP and MySQL. Because they are open source projects, there is no licensefee associated with using PHP or MySQL. Because both applications run on almost any platform, you also have a wide range of hardware choices lowering the total cost of ownership. With so many qualified PHP developers sharing information on the Web, and excellent online documentation, you can get the most up-to-date, reliable information without paying for it.
Portability
PHP and MySQL run on almost any platform, including Linux, Windows, Mac OS X, FreeBSD, Solaris, and so on. If well written, you can simply copy the code from one server to another and expect the same results, perhaps with some minor adjustments.
Developer Community
Both PHP and MySQL have a huge following in the development community. If you run into a problem, you can usually very quickly find support on the Web, where your problem can be posted, identified, and resolved by other users and developers sharing your problem. Developers worldwide are constantly finding and resolving bugs and security holes, while working to keep these languagesup-to-date and optimized.
Ease of Learning
PHP and MySQL are relatively easy to learn. Most of the PHP constructs are similar to other languages, specifically Perl, making it familiar to most developers. MySQL uses the SQL query language and English-like language used by most modern database management systems today. If you have had any experience with SQL, you will find using it with MySQL an easy transition.

MySQL is a relational database management system. Whether you’re involved with a Web site that processes millions of requests a day like eBay or Yahoo!, or a smaller site such as your own online shop or training course, the data must be stored in an organized and structured way for easy access and processing.
This is handled by a database management system such as MySQL where the data is stored in tables rather than in a flat file.

MySQL uses the client/server model; that is, a database server (MySQL) that serves (communicates) with multiple clients application programs), where the clients may or may not be on the same computer. It also supports SQL, the structured query language, a standardized language used by most modern databases for working with data and administering the database.

MySQL software is open source. As discussed earlierin this chapter, open source means that it is possible for anyone to download MySQL from the Internet, and use and modify the software without paying anything. The MySQL software uses the GPL GNU General Public License, http://www.fsf.org/licenses/, to define what you may and may not do with the software in different situations. If you need to use MySQL code in a commercial application, you can buy a commercially licensed version. See the MySQL Licensing Overview for more information http://www.mysql.com/company/legal/licensing .
The MySQL Database Server is very fast, reliable, and easy to use. MySQL Server was originally developed to handle large databases much faster than existing solutions and has been successfully used in highly demanding production environments for several years. Its connectivity, speed, and security make MySQL Server highly suited for accessing databases on the Internet.

MySQL serves as a back end for all kinds of information such as e-mail, Web images and content, games, log files, and so on. The server can be embedded in applications such as cell phones, electronic devices, public kiosks, and more.

configuring PHP-impact security

The primary mechanism for configuring PHP is the php.inifile.
As the master file, this provides you with control over all configuration settings.
Entries generally take the format:
setting= value

Be sure to read the comments provided in the file before making changes, though.
There are a few tricks, such as include_pathusing a colon (:) as a seperator on
Unix, and a semicolon (;) on Windows.
Most Web hosts will not provide you access to your php.inifile unless you have
root access to the system (which is typically not the case if you’re using a cheap
virtual hosting service). Your next alternative is to use .htaccessfiles to configure
PHP assuming the Web server is Apache.
An .htaccessfile is a plain text file that you place in a public Web directory to
determine the behavior of Apache when it comes to serving pages from that directory; for instance, you might identify which pages you’ll allow public access to.
Note that the effect of an .htaccessfile is recursive—it applies to subdirectories
as well.

To configure PHP with .htaccessfiles, your hosting provider must have the
Apache setting AllowOverride Optionsor AllowOverride Allapplied to your
Web directory in Apache’s main httpd.confconfiguration file. Assuming that
is done, there are two Apache directives you can use to modify PHP’s configuration:
php_flag
used for settings that have boolean values (i.e. on/offor 1/0) such as
register_globals

php_value
used to specify a string value for settings, such as you might have with the
include_pathsetting
Here’s an example .htaccessfile:

# Switch off register globals
php_flag register_globals off
# Set the include path
php_value include_path ".;/home/username/pear"

The final mechanism controlling PHP’s configuration is the group of functions
ini_setand ini_alter, which let you modify configuration settings, as well as
ini_get, which allows you to check configuration settings, and ini_restore,
which resets PHP’s configuration to the default value as defined by php.iniand
any .htaccessfiles. Using ini_set, here’s an example which allows us to avoid
having to define our host, user name and password when connecting to MySQL:
ini_set('mysql.default_host', 'localhost');
ini_set('mysql.default_user', 'harryf');
ini_set('mysql.default_password', 'secret');
if (!mysql_connect()) {
echo mysql_error();
} else {
echo 'Success';
}

Be aware that PHP provides for some settings, such as error_reporting, alternative functions that perform effectively the same job as ini_set.

php.ini Settings for Session Management

Before you get started with this chapter, you may have to make a couple of minor changes to your php.ini file so that sessions work correctly.

On Windows

If you are using a Windows version of PHP, the first thing you need to do is to edit your php.ini file. The default session setting in php.ini will not work correctly under Windows.
Open your php.ini file, which is found in c:\windows or c:\winnt, in a text editor and search for the line:
session.save_path = /tmp 
Change it to a directory in which you keep temporary files, for example:
session.save_path = C:/temp 
You could also leave the value as /tmp and create a directory named "tmp" at the root of the drive on which your Web server resides. For example, if your Web server was located in D:/apache/bin, then you could create the directory d:/tmp and you would not have to change the session.save_path setting in php.ini.
A good indication that the session.save_path has not been set correctly on Windows is if Apache crashes when you try to load a session-enabled page.

On Linux

If you are using Linux, you need to make sure that your /tmp directory can be written to by the user who runs the Web processes. Typically this is the user nobody, and most systems, by default, allow the nobody user to write to the /tmp directory.
The rest of the default session settings should work fine for you in the examples in this chapter.

General Considerations

You should not store the session files in any directory which is viewable from your Web server. If you are using Apache, then that would be any directory under the htdocs directory. The reason you do not want to place session files in a directory that is viewable from your Web server is because malicious users may be able to open those files and view individual session data, and even hijack user's sessions in this manner.

You cannot track variables across a user session unless you start the session on each page on which you want to use or alter those variables. Starting a session uses the session_start() function:
session_start(); 
session_start() takes no arguments. If you are starting a new session, then the function initializes the session and creates the necessary temp files to track the session. If a $PHPSESSID is found by the function, either by a cookie or a GET variable, then the function resumes the current session and the page has access to any variables that have been registered to the session.
Once you have started the session, you need to register some variables with it. The session will not track variables until they have been registered using the session_register() function:
session_register(STRING); 
The STRING argument to session_register() should be the name of the variable that you want to register with the session so that it may be accessed across any session-enabled pages.
Once you have started the session and registered one or more variables, you can use those variables across any session enabled pages on your site. , session.php, provides a simple example of starting a session and registering a variable.


PHPGTK-application window

PHPGTK is an extension to PHP that allows you to create graphical user interface (GUI) applications. Instead of running in a browser, your PHP application runs in its own application window. These applications are client-side only. They do not reside on the Web server. The files instead reside on the user's hard drive. For users to use the PHPGTK application, they must have the proper version of PHP with the GTK+ extension installed on their system.

GTK+ was originally designed for the open-source image editing program called the GIMP (GNU Image Manipulation Program). GTK stands for the GIMP Tool Kit. Later, the Gnome team decided to use GTK+ to create their desktop environment for Linux. GTK+ has been ported to Windows, Linux, and BeOS, and thus makes for a good cross-platform GUI library.

PHPGTK uses GTK+ to draw the widgets required in any GUI application. Widgets are things like scroll bars, text input fields, and buttons, among other things. When you start almost any Windows application, such as a Web browser, you are looking at a collection of widgets.

Widgets need to be contained in some type of framework to be useful and logical. You can't just have a bunch of buttons and text fields scattered randomly about the screen. To solve this problem, we use a special kind of widget called a container. A container is another structure that organizes the widgets however you think it best for your application. For example, the menu bar at the top of most applications is a container.

Before you can start using PHPGTK, you need to download the appropriate files. The PHPGTK team has set up a nice Web site at http://gtk.php.net. The PHPGTK Web site has downloads and documentation for the GTK extension.

Before You Install

PHPGTK still has not reached the 1.0 version, and as such I wouldn't recommend that you use this version of PHP on your production Web server. In fact, there really isn't a reason that you'd want to install PHPGTK on your production Web server. It is a client-side application!
PHPGTK is a developers' toy at the moment, and anything is subject to change, at least before PHPGTK reaches version 1.0. Have some fun with it, try it out, but don't base your company's next big product on PHPGTK 0.5.0.

Installing on Windows

Installing PHPGTK on a Windows machine is fairly straightforward and similar to installing the normal version of PHP. Download the Windows binary file from the PHPGTK Web site at http://gtk.php.net.
Unzip the file using a zip utility such as WinZip. Extract the files to your C: drive.
The following folders are created when you unzip the file:
  • php4— Contains the PHP executable, as well as some GTK library files.
  • test— Contains some sample *.php files that use the GTK widget set.
If you are using Windows 98 or Windows ME, then you will notice that folders called "winnt" and "winnt/system32" have been created. You should copy the contents of those folders into your C:\windows directory. Note that you may have to set your system files to be viewable so that you can see the necessary DLL files to copy them over to C:\windows.
Additionally, you should see a new php.ini file. Copy this to your C:\Windows or C:\WINNT directory. Be sure to first back up your existing php.ini file.
To test out the installation, type the following from a command prompt:

c:\php4\php.exe -q c:\test\gtk.php 
 

Installing on Linux

Installing PHPGTK on Linux is easier than installing the normal PHP; you don't have to worry about compiling with Apache. You can compile GTK functionality into an existing standalone version of PHP, but for our purposes we'll start from scratch and make a brand new PHP executable that has GTK functionality built in. Before you begin:
  1. Download the source file for PHP from the download page at www.php.net.
  2. Download the source file PHPGTK from the download page of http://gtk.php.net.
Once you have the necessary file, unzip and untar the regular PHP source file:
tar -zxvf php-4.x.x.tar.gz
This creates a new directory named php-4.x.x, where the "x" denotes the exact version number of PHP that you downloaded.
Compile PHP using the minimum options. We just want to create a standalone executable. If you want to add additional functionality, you can recompile later. For now, you just want to make sure you can create a working version of PHPGTK. Change directory into your newly created PHP source directory. Compile by typing:
./configure
That's all there is to it. This automatically creates an executable that has built-in MySQL support as well.
Once you have the php binary file, you must copy it to /usr/local/bin. The PHPGTK installation will be looking for it in that location. You need to be root to do this.
cp php /usr/local/bin
Now, it's time to build the GTK extension onto your PHP executable. Go back to where you downloaded the PHPGTK source file and extract it:
tar -zxvf php-gtk-0.5.0.tar.gz
This creates a new directory named php-gtk-0.5.0. Change directory into that directory and compile the source file. You will need to be root to perform the final step, make install. To compile PHPGTK, type the following (a lot of text will print to the screen after you type each command):
  1. ./compile
  2. make
  3. make install
You can test your installation by going into the test directory and running a few of the scripts. X-Windows will need to be running!
cd test php -q gtk.php
A window should pop up showing various GTK widget buttons. Click the different widgets to get a brief idea of what they do.
 


top Database management system-PHP

This summary is not available. Please click here to view the post.

PHP-script-Related Variables



PHP-script Related Variables

PHP automatically creates variables for all the data it receives in an HTTP request. This can include GET data, POST data, cookie data, and environment variables. The variables are either in PHP's global symbol table or in one of a number of superglobal arrays, depending on the value of the register_globals setting in your php.ini file.
In PHP 4.2.0 and after, the default setting for register_globals is off. With register_globals off, all the various variables that are usually available directly in the global symbol table are now available via individual superglobal arrays. There is a limited set of superglobals and they cannot be created from a user-level script. The superglobal array to use depends on the source of the variable. Here is the list:
$_GET
GET-method variables. These are the variables supplied directly in the URL. For example, with http://www.example.com/script.php?a=1&b=2, $_GET['a'] and $_GET['b'] are set to 1 and 2, respectively.
$_POST
POST-method variables. Form field data from regular POST-method forms.
$_COOKIE
Any cookies the browser sends end up in this array. The name of the cookie is the key and the cookie value becomes the array value.
$_REQUEST
This array contains all of these variables (i.e., GET, POST, and cookie). If a variable appears in multiple sources, the order in which they are imported into $_REQUEST is given by the setting of the variables_order php.ini directive. The default is 'GPC', which means GET-method variables are imported first, then POST-method variables (overriding any GET-method variables of the same name), and finally cookie variables (overriding the other two).
$_SERVER
These are variables set by your web server. Traditionally things like DOCUMENT_ROOT, REMOTE_ADDR, REMOTE_PORT, SERVER_NAME, SERVER_PORT, and many others. To get a full list, have a look at your phpinfo( ) output, or run a script like the following to have a look:
<?php
  foreach($_SERVER as $key=>$val) {
    echo '$_SERVER['.$key."] = $val<br>\n";
  }
?>
$_ENV
Any environment variables that were set when you started your web server are available in this array.
$_FILES
For RFC 1867-style file uploads the information for each uploaded file is available in this array. For example, for a file upload form containing:
<input name="userfile" type="file">
The $_FILES array will look something like this:
$_FILES['userfile']['name'] => photo.png
$_FILES['userfile']['type'] => image/png
$_FILES['userfile']['tmp_name'] => /tmp/phpo3kdGt
$_FILES['userfile']['error'] => 0
$_FILES['userfile']['size'] => 158918
Note that the 'error' field is new for PHP 4.2.0 and the values are: 0 no error, file was uploaded); 1 (the uploaded file exceeds the upload_max_filesize directive in php.ini; 2 the uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form; 3 the actual number of bytes uploaded was less than the specified upload file size; and 4.

However, having seen some of the possible values of HTTP_USER_AGENT in the last chapter, you can imagine that there are hundreds of slightly different values. So it's time to learn some basic pattern matching.
You'll use the preg_match() function to perform this task. This function needs two arguments: what you're looking for, and where you're looking:

preg_match("/[what you're looking for]/", "[where you're
looking]");
 
This function will return a value of true or false, which you can use in an ifelse block to do whatever you want. The goal of the first script is to determine if a Web browser is Microsoft Internet Explorer, Netscape, or something else. This can be a little tricky, but not because of PHP.
Within the value of HTTP_USER_AGENT, Netscape always uses the string Mozilla to identify itself. Unfortunately, the value of HTTP_USER_AGENT for Microsoft Internet Explorer also uses Mozilla to show that it's compatible. Luckily, it also uses the string MSIE, so you can search for that. If the value of HTTP_USER_AGENT doesn't contain either Mozilla or MSIE, chances are very good that it's not one of those Web browsers.

php-Data Types

Data Types

PHP provides four primitive data types: integers, floating point numbers, strings, and booleans. In addition, there are two compound data types: arrays and objects.

 Integers

Integers are whole numbers. The range of integers in PHP is equivalent to the range of the long data type in C. On 32-bit platforms, integer values range from -2,147,483,648 to +2,147,483,647. PHP automatically converts larger values to floating point numbers if you happen to overflow the range. An integer can be expressed in decimal (base-10), hexadecimal (base-16), or octal (base-8). For example:
$decimal=16;
$hex=0x10;
$octal=020;

 Floating Point Numbers

Floating point numbers represent decimal values. The range of floating point numbers in PHP is equivalent to the range of the double type in C. On most platforms, a double can be between 1.7E-308 to 1.7E+308. A double may be expressed either as a regular number with a decimal point or in scientific notation. For example:
$var=0.017;
$var=17.0E-3
PHP also has two sets of functions that let you manipulate numbers with arbitrary precision. These two sets are known as the BC and the GMP functions. See http://www.php.net/bc and http://www.php.net/gmp for more information. 

Strings

A string is a sequence of characters. A string can be delimited by single quotes or double quotes:
'PHP is cool'
"Hello, World!"
Double-quoted strings are subject to variable substitution and escape sequence handling, while single quotes are not. For example:
$a="World";
echo "Hello\t$a\n";
This displays "Hello" followed by a tab and then "World" followed by a newline. In other words, variable substitution is performed on the variable $a and the escape sequences are converted to their corresponding characters. Contrast that with:
echo 'Hello\t$a\n';
In this case, the output is exactly "Hello\t$a\n". There is no variable substitution or handling of escape sequences.
Another way to assign a string is to use what is known as

Arrays

An array is a compound data type that can contain multiple data values, indexed either numerically or with strings. For example, an array of strings can be written like this:
$var[0]="Hello";
$var[1]="World";
Note that when you assign array elements like this, you do not have to use consecutive numbers to index the elements.
As a shortcut, PHP allows you to add an element onto the end of an array without specifying an index. For example:
$var[ ] ="Test";
PHP picks the next logical numerical index. In this case, the "Test" element is given the index 2 in our $var array: if the array has nonconsecutive elements, PHP selects the index value that is one greater than the current highest index value. This autoindexing feature is most useful when dealing with multiple-choice HTML <select> form elements, as we'll see in a later example.


PHP Online Resources

The major sites that use PHP, and a listing of all the books written on PHP. Not only does this site contain a plethora of resources, it also contains links to the other PHP sites, the latest news about all things PHP

The Official PHP Web Site





The Zend Web Site

The Zend engine is the engine that powers PHP. The Zend Web site is the site of the company that puts out the Zend engine, as well as many other tools. For example, at this site you can also download the Zend Optimizer, which gives your PHP scripts a 40-100% increase in speed on average.




PHPBuilder

The documentation on PHP is an awesome reference, but some of the more abstract concepts of PHP can't be covered by a simple function reference; they need to be explained by experts who have been there and done that. PHPBuilder offers an impressive set of tutorials ranging in level from beginner to advanced.




PHPWizard.net

This site contains an excellent repository of daily tips and tricks. In addition to the daily tips, this Web site contains high-quality programs such as an online quiz system and an online chat program.




The PHP Class Repository

This Web site in search of classes that will make  life easier. 



DevShed

DevShed is an excellent resource for all things open source including Perl, Python, Jserv, Zope, and, of course, PHP. It contains a nice repository of introductory PHP tutorials and an active message board.




PHP-Mail Functions

PHP contains two dedicated mail functions, which are built into PHP by default. The mail() function allows for the sending of email directly from a script, and ezmlm_hash() provides a hash calculation useful for interfacing a script to an  mailing list system.
The mail() function requires an installed and working email subsystem for sending mail. The program to be used is defined by configuration directives in the php.ini file. A common pitfall is that these are not set up correctly, rendering mail() inoperable. Note that the first two directives are for use only on Windows systems; the third is for use only on Unix-type systems.
  • SMTP: The host to which to connect to send mail. Can be either a fully qualified hostname or an IP address. Used only on Windows systems.
  • sendmail_from: The email address from which sent mail should appear to have been sent. Used only on Windows systems.
  • sendmail_path: Full pathname of the mail executable to run when sending mail. This can also include command-line arguments. The default is created during the precompilation configuration: For example, if a sendmail executable is found in /usr/sbin, the default will be usr/sbin/sendmail -t -i. If no sendmail executable is found, one must be specified here. Used only on Unix-type systems.

    mail

    bool mail(string recipient, string subject, string message, 
     [string extra_headers], [string extra_arguments]) 
    recipient
    Address of the recipient
    subject
    Message subject
    message
    Body of the message
    extra
    Extra headers for the message
    extra_arguments
    Extra arguments for the underlying mail program (PHP 4.0.5 and later)
    Sends a message via email.
    Returns:
    TRUE on success; FALSE on failure
    Description:
    mail() allows you to send email directly from a PHP script. recipient can be either a single email address or a comma-delimited list of addresses. If you want to set extra headers—for instance, in order to use Cc: or Bcc:—these may be placed in a newline-delimited string in the extra_headers parameter. As of PHP 4.0.5, you can also specify extra arguments to the system mail program in the extra_arguments parameter. For example, this is useful if you want to set the envelope From: header so that it doesn't look like email is coming from your web server daemon. If you do this, however, you may want to add your daemon process to the trusted users list in your sendmail configuration (if using sendmail); otherwise, sendmail will add an X-Authentication-Warning: header to the email, indicating that an untrusted user has modified the envelope.

    Send email from a PHP script

    /* When the following code was executed, I received this email: 
     * 
     * From: Apache httpd <www@pinc.com> 
     * To: torben@php.net 
     * Subject: This is a test 
     * Date: Mon, 20 Aug 2001 16:33:17 -0700 
     * 
     * Hi there, 
     * 
     * This is a test message. Please disregard. 
     */ 
    $address = 'torben@php.net'; 
    $subject = 'This is a test'; 
    $message = 'Hi there, 
    
    This is a test message. Please disregard. 
    '; 
    mail($address, $subject, $message); 
    
    /* Now, tell it that I want it to look like it's from me, using 
     * the extra_arguments parameter. 
     * The email I got back from this one was as follows. However, 
     * because this was run on a web page and the httpd is not a 
     * sendmail-trusted user, the resulting email also included this 
     
     * Subject: This is a test 
     * Date: Mon, 20 Aug 2001 16:47:56 -0700 
     * 
     * 
     * Hi there, 
     * 
     * This is a test message. Please disregard. 
     * 
     */ 
    mail($address, $subject, $message, '', 'ftorpden@php.net'); 
    
    /* Send the same message, but to a blind carbon-copy list. */ 
    mail($address, $subject, $message, 'Bcc: fif@bar.brz, king.ttrfgrut@abc.com'); 


Networking Functions-PHP

When using the PHP binaries for Windows that are available from http://php.net/, the getprotobyname(), getprotobynumber(), getservbyport(), and getservbyname() may not function as anticipated under Windows 2000.

DNS resource records:
  • checkdnsrr()
  • getmxrr()
Domain name/IP address lookups and conversions:
  • gethostbyaddr()
  • gethostbyname()
  • gethostbynamel()
  • ip2long()
  • long2ip()
Internet protocol and service information:
  • getprotobynumber()
  • getservbyname()
  • getprotobyname()
  • getservbyport()
PHP 3 debugger (warning: very broken!):
  • debugger_off()
  • debugger_on()
Sockets:
  • fsockopen()
  • pfsockopen()
  • socket_get_status()
  • socket_set_blocking()
  • socket_set_timeout()

    gethostbyaddr() 
    gethostbyname() 
    gethostbynamel() 
    getmxrr() 
    Example:
    Check whether a given domain name has an MX resource record
    <?php 
    $url = "http://www.php.net/"; 
    $component = parse_url ($url); 
    checkdnsrr ($component['host'], 'MX') 
        or die ('No MX record exists for <i>$component[host]</i>. 
            Did you enter the URL correctly?'); 
    echo "MX record found for <i>$component[host]</i>"; 
    ?> 

    fsockopen

    mixed fsockopen(string host, int port, [reference error_number], 
     [reference error_string], [double timeout]) 
    host
    Hostname or IP address
    port
    Port number
    error_number
    Reference to a variable that will store the system-level error number if the function fails
    error_string
    Reference to a variable that will store the system-level error message if the function fails
    timeout
    Number of seconds before the connect system call times out
    Opens a connection to a socket.
    Returns:
    File pointer identifying the open socket; FALSE on failure
    Description:
    fsockopen() attempts to open a network socket connection to the specified host and port. TCP connections are assumed by default, but UDP connections can be specified by placing udp:// at the start of the host .

    There are three optional arguments: error_number , error_string , and timeout . Both the error_number and error_string arguments must be passed as references, as in &$error_number and &$error_string. If an error occurs, these variables will contain an error code and a message. If the error number is 0, this is usually due to a problem that occurs before the socket initializes, such as an incorrect hostname.

    The timeout argument should contain the maximum number of seconds to wait for a connection before timing out.

open a socket

<?php 
$host = 'www.abcxyz.com'; 
$port = 80; 

$fp = fsockopen($host, $port, &$err_no, &$err_msg, 10) 
    or die ("Could not open a socket connection to host 
         <i>$host</i> on port <i>$port</i>. 
         The error message returned was '<i>$err_msg</i>'."); 
echo "A socket connection to host <i>$host</i> on port 
   <i>$port</i> was successfully opened." 
?> 

PHP-max_execution_time

php.ini Directives Related to the Connection-Handling Functions

The following configuration directives can be used to control the behavior of the connection-handling functions.
Directive Name
Value Type
Description
ignore_user_abort
bool (on/off)
If this setting is enabled, PHP continues running the script even after the user aborts the script or disconnects.
max_execution_time
integer
The maximum amount of time that a script can run before execution is halted.

connection_timeout

connection_timeout() is broken and has been removed from PHP 4 (as of version 4.0.5). Do not use this function—use connection_status() instead.

ignore_user_abort() allows developers to control whether a remote client can abort the running of a script. If the user_abort_setting argument is set to FALSE, client aborts (and some network errors) will cause the script to stop running. If user_abort_setting is set to TRUE, the script continues running until an error occurs, the script finishes execution, or the script times out.


To check whether script execution has been aborted:
connection_aborted() 
To set ignore_user_abort globally:
ignore_user_abort ini directive 


 


Make a PHP session code

 Make a PHP session code

session_start

int session_start(void) 
Initializes a session.
Returns:
Always returns TRUE
Description:
Initializes a session. If a session ID is sent as a GET or in a cookie and is a valid session identifier, the session is resumed.
Version:
Existing since version 4.0
Example:
Start a session
session_start(); 
if (!$counter) session_register("counter"); 
echo $counter; 
$counter++; 



<?php
// include URL utils library
require_once ‘include/url_utils.inc.php’;
// load configuration script
require_once ‘include/config.inc.php’;
// start PHP session
session_start();
// redirect affiliate links
if (isset($_REQUEST[‘aff_id’]))
{
// save the affiliate ID
$_SESSION[‘aff_id’] = $_REQUEST[‘aff_id’];
// obtain the URL with no affiliate ID
$clean_url = SITE_DOMAIN . remove_query_param($_SERVER[‘REQUEST_URI’], ‘aff_id’);
// 301 redirect to the new URL
header(‘HTTP/1.1 301 Moved Permanently’);
header(‘Location: ‘ . $clean_url);
}
// display affiliate details
echo ‘You got here through affiliate: ‘;
if (!isset($_SESSION[‘aff_id’]))
{
echo ‘(no affiliate)‘;
}
else
{
echo $_SESSION[‘aff_id’];
}
?>


session_set_save_handler

bool session_set_save_handler(string open, string close, string read, 
string write, string destroy, string gc) 
open
Session init function
close
Session shutdown function
read
Session read function
write
Session write function
destroy
Destroy session function
gc
Garbage collection function
Sets handlers for custom session functions.
Returns:
TRUE on success; FALSE on error
Description:
This function takes six arguments that describe the functions used when creating your own session-handling functions. Each function can have any name, but the names must be passed in the correct order. In addition, each function must return the correct information. Using this function, it's possible to write any session handler that you want, including those that store their information in a database, text files, DBM files, or shared memory.
bool open(string save_path, string session_name )
Executed when a session is initialized; can be used for various functions such as initializing variables. The save path and session name can come from the PHP initialization file or via the session_save_path() and session_name() functions. Should return TRUE on success, FALSE on error.
bool close()
Executed on shutdown of a session. Can be used to free memory or to destroy variables. Should return TRUE on success, FALSE on error.
mixed read(string session_ID)
Called whenever a session is started. If called with a session ID, the data associated with that session ID must be read and returned as a serialized string. If no session ID is passed, an empty string is returned. Should return FALSE on error.
bool write(string session_ID , string value )
Updates or adds new session data. The data to be written must be serialized. Should return TRUE on success, FALSE on error.
bool destroy(string session_ID )
Removes any session data from the data store. Must return TRUE on success, FALSE on error.
bool gc(string max_lifetime )
Called at session startup. Designed to remove any sessions with a lifetime greater than the maximum. Should return TRUE on success, FALSE on failure.
Version:
Existing since version 4.0
Example:
Create new session handler
session_set_save_handler("user_open","user_close","user_read","user_write", 
"user_destroy","user_gc") 

How to create a thumbnail-PHP code

To create a thumbnail, you pass the function PIPHP_MakeThumbnail()a GD image object
and the maximum value of the greater dimension for the thumbnail. For example, the
following code loads in the image in test.jpgusing the imagecreatefromjpeg()function,
and then passes it to the plug-in, along with a maximum dimension of 100. The function
then returns the new thumbnail to the string variable $thumb, which is then saved to the file
thumb.jpgusing the imagejpeg()function.

$image = imagecreatefromjpeg("test.jpg");
$thumb = PIPHP_MakeThumbnail($image, 100);
imagejpeg($thumb, "thumb.jpg");
You can also output the thumbnail straight to the browser by first sending the correct
header, like this:
$image = imagecreatefromjpeg("test.jpg");
header("Content-type: image/jpeg");
imagejpeg(PIPHP_MakeThumbnail($image, 100));

The PHP GD library is so powerful that it can perform a variety of image manipulations you
would normally only find in a graphics program. In fact, you could probably build quite an
advanced image editor using them.
<?php
function PIPHP_MakeThumbnail($image, $max)
{
$thumbw = $w = imagesx($image);
$thumbh = $h = imagesy($image);
if ($w > $h && $max < $w)
{
$thumbh = $max / $w * $h;
$thumbw = $max;
}
elseif ($h > $w && $max < $h)
{
$thumbw = $max / $h * $w;
$thumbh = $max;
}
elseif ($max < $w)
{
$thumbw = $thumbh = $max;
}
return PIPHP_ImageResize($image, $thumbw, $thumbh);
}
?>

To perform an Edge Detect transformation on a file called photo.jpg,
you could use the following code, which will load a GD image object using the
imagecreatefromjpeg()function, and save the transformed image with the function
imagejpeg()
<?php
function PIPHP_ImageAlter($image, $effect)
{
switch($effect)
{
case 1: imageconvolution($image, array(array(-1, -1, -1),
array(-1, 16, -1), array(-1, -1, -1)), 8, 0);
break;
case 2: imagefilter($image,
IMG_FILTER_GAUSSIAN_BLUR); break;
case 3: imagefilter($image,
IMG_FILTER_BRIGHTNESS, 20); break;
case 4: imagefilter($image,
IMG_FILTER_BRIGHTNESS, -20); break;
case 5: imagefilter($image,
IMG_FILTER_CONTRAST, -20); break;
case 6: imagefilter($image,
IMG_FILTER_CONTRAST, 20); break;
case 7: imagefilter($image,
IMG_FILTER_GRAYSCALE); break;
case 8: imagefilter($image,
IMG_FILTER_NEGATE); break;
case 9: imagefilter($image,
IMG_FILTER_COLORIZE, 128, 0, 0, 50); break;
C h a p t e r  4 :  I m a g e  H a n d l i n g  71   C h a p t e r  4 :  I m a g e  H a n d l i n g  71
case 10: imagefilter($image,
IMG_FILTER_COLORIZE, 0, 128, 0, 50); break;
case 11: imagefilter($image,
IMG_FILTER_COLORIZE, 0, 0, 128, 50); break;
case 12: imagefilter($image,
IMG_FILTER_EDGEDETECT); break;
case 13: imagefilter($image,
IMG_FILTER_EMBOSS); break;
case 14: imagefilter($image,
IMG_FILTER_MEAN_REMOVAL); break;
}
return $image;
}
?>

PHP Functions
Php tutorial - imagemagick
php.ini Basics
PHP Sessions
Cookies Versus Sessions
PHP Web-Related Variables
PHP ERRORS
maximum size of a file uploaded
Php Image upload
php file_get_contents
MySQL Data on the Web
What are GET and POST
php and pdf
$_ENV and $_SERVER
PEAR with php
SELECTING DATA PHP
prevent hijacking with PHP
LAMP
PHP MySQL Functions
PHP Zip File Functions
Substrings PHP
PHP Variable names
PHP magic methods
How to get current session id
Add variables into a session
$_GET , $_POST,$_COOKIE
different tables present in mysql
PHP CURL
php Sessions page
PHP-sorting an array
PHP-count the elements of array
Operators for If/Else Statements
PHP file uploading code
PHP global variables
Testing working using phpinfo
PHP Code for a Valid Number
PHP-Associative Arrays
PHP mvc tutorial
PHP get_meta_tags-Extracts
difference between print and echo
PHP best tutorial-PHP variables
Reading DOC file in PHP
PHP interview questions
convert time PHP
PHP implode array elements
header function-PHP
PHP-Renaming Files Directories
PHP Classes
in_array function in PHP
keep your session secure PHP
Web Application with PHP
What is SQL Injection
PHP-extract part of a string
PHP urlencode
PHP- know browser properties
PHP- Extracting Substrings
Checking Variable Values /Types
PHP-best 20 Open Source cms
IP AddressPHP
PHP-Scope Resolution Operator
how create new instance of object
how eliminate an object
PHP- ob_start
XML file using the DOM API
PHP- MVC
PHP- CAPTCHA
PHP- Position of a Value in an Array
PHP-Mail Functions
PHP-difference include vs require
calculate the sum of values in an array
PHP-total number of rows
Show unique records mysql
MySQL Triggers
MySQL data directory
MySQL Subqueries
PHP- Networking Functions
PHP- Operators
Restore database
Conditional Functions mysql
PHP-function overloading
Friend function
mysql_connect /mysql_pconnect
PHP-Error Control Operators
what is IMAP
Apache-Specific Functions
Send Email from a PHP Script
SQL inherently
WAMP, MAMP, LAMP
Php tutorial-SYMBOLS
Table Types-MySQL
PHP-Encryption data management
PHP Array
Running MySQL on Windows
Maximum Performance MySQL
XML-RPC
PHP-static variables
Advanced Database Techniques
FTP
Codeigniter
Apache Pool Size
Why NoSQL
MySQL Server Performance
Database software
SQL Interview Answers
PHP Redirect
PHP Interview Questions with Answers
Advanced PHP

PHP-Array Functions -list(),each(), and count().

list() is sort of an operator, forming an lvalue (a value that can be used on the left side of an expression) out of a set of variables, which represents itself as a new entity similar to an element of a multidimensional array. As arguments, it takes a list of variables. When something is being assigned to it (a list of variables or an array element), the list of variables given as arguments to the list() operator is parsed from left to right. These arguments are then assigned a corresponding value from the rvalue (a value that's used on the right side of an expression). This is best explained using a code example:

$result = mysql_db_query($mysql_handle, $mysql_db,
                         "SELECT car_type, car_color, car_speed
                          FROM cars WHERE car_id=$car_id);

list($car_type, $car_color, $car_speed) = mysql_fetch_row($result);
Note: This code is used here strictly for example. It's not a good idea to implement code like this in real-life programs, as it relies on the fields remaining in the same order. If you change the field ordering, you have to change the variable ordering in the list() statement as well. Using associative arrays and manual value extraction imposes an overhead in programming but results in better code stability. Code as shown above should only be implemented for optimization purposes.

$my_array = array("Element 1", "Element 2", "Element 3");

while(list($key, $value) = each($my_array))
    print("Key: $key, Value: $value<br>");
 
 
You can also use each() to show the elements that each() itself returns:

$my_array = array("Element 1", "Element 2", "Element 3");

while($four_element_array = each($my_array))
{
   while(list($key, $value) = each($four_element_array))
       print("Key $key, Value $value<br>");
}
Using a simple for() loop is not enough for arrays of this kind; it accesses indices that don't have a value assigned. If PHP provides a stricter environment, this would result in an exception and immediate termination of the script. Therefore, whenever you're unsure about the contents and consistency of arrays, you're doomed to using each().

my array = array(0 => "Landon", 3 => "Graeme", 4 => "Tobias", 10 => "Till"); 
 for($i = 0; $i < count($my_array); $i++) 
print("Element $i: $my_array[$i]<br>");

PHP-HTTP and Sessions-Maintaining State

HTTP has no mechanism to maintain state; thus HTTP is a context-free or stateless protocol. Individual requests aren't related to each other. The Web server and thus PHP can't easily distinguish between single users and doesn't know about user sessions. Therefore, we need to find our own way to identify a user and associate session data that is, all the data you want to store for a user with that user. We use the term session for an instance of a user visiting a site where one or more pages are viewed. For example, a typical online shopping session might include putting an item into the shopping cart, going to the checkout page, entering address and credit card data, submitting the order, and closing the browser window.
 
At first, the typical PHP programmer tries to ignore the problem and find a workaround for it. The obvious workaround is to store all data on the client instead of on the server. This leads to forms with a lot of hidden fields or very long URLs. It becomes impractical with more than two files and more than one variable to save. An only slightly more intelligent method is to use cookies to store all information on the client side.

  • You lose control over the data—as long as the user doesn't return to your site, you can't access the data. And worse, that data may be manipulated when you get it back. Ninety percent of all Web site defacing and breakings come from applications accepting tampered data from the client side and trusting that data. Do not keep data on the client. Do not trust data from the client.
  • If you use GET/POST, the storage isn't persistent across sessions.
  • If you rely exclusively on cookies, you have a problem because some users won't accept cookies—they simply disable cookies in their browsers.
  • The data is hard to maintain because you need to save all data on every page. Each variable needs to be URL-encoded, added to a form as a hidden field or added to the URL, or saved as a cookie. This is difficult for a single variable such as the session ID, let alone dozens of variables!
Thus, the data needs to be stored on the server. Where exactly you store it isn't all that important; it can be in a relational database management system RDBMS, plaintext file, dBASE file, etc. Because a Web application generally already uses a relational database such as MySQL, this should be the preferred storage medium.

The typical PHP programmer tries to ignore the problem and find a workaround for it. The obvious workaround is to store all data on the client instead of on the server. This leads to forms with a lot of hidden fields or very long URLs. It becomes impractical with more than two files and more than one variable to save. An only slightly more intelligent method is to use cookies to store all information on the client side.

PHP has a built-in uniqid() function, but because it's based on the system time, it's not secure enough to be used for a session ID. However, you can combine it with a hash function and rand() to
 construct a truly 

srand((double)microtime()*1000000); // Seed the random number generator
$session_id = md5(uniqid(rand())); // Construct the session ID
 
By the way, md5(uniqid())—the same construct from above without a 
rand() call—would not be sufficiently random; because uniqid() 
is based on the system time, it can be guessed if the hacker learns the local 
system time of the server.