Social Icons

Friday, August 29, 2014

php-11

Every company follows a different coding standard based on their best practices. Coding standard is required because there may be many developers working on different modules so if they will start inventing their own standards then source will become very un-manageable and it will become difficult to maintain that source code in future.
Here are several reasons why to use coding specifications:
  • Your peer programmers have to understand the code you produce. A coding standard acts as the blueprint for all the team to decipher the code.
  • Simplicity and clarity achieved by consistent coding saves you from common mistakes.
  • If you revise your code after some time then it becomes easy to understand that code.
  • Its industry standard to follow a particular standard to being more quality in software.
There are few guidelines which can be followed while coding in PHP.
  • Indenting and Line Length - Use an indent of 4 spaces and don't use any tab because different computers use different setting for tab. It is recommended to keep lines at approximately 75-85 characters long for better code readability.
  • Control Structures - These include if, for, while, switch, etc. Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls. You are strongly encouraged to always use curly braces even in situations where they are technically optional.
    Examples:
    if ((condition1) || (condition2)) {
        action1;
    } elseif ((condition3) && (condition4)) {
        action2;
    } else {
        default action;
    }
    
    You can write switch statements as follows:
    switch (condition) {
    case 1:
        action1;
        break;
    
    case 2:
        action2;
        break;
    
    default:
        defaultaction;
        break;
    }
    
  • Function Calls - Functions should be called with no spaces between the function name, the opening parenthesis, and the first parameter; spaces between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon. Here's an example:
    $var = foo($bar, $baz, $quux);
    
  • Function Definitions - Function declarations follow the "BSD/Allman style":
    function fooFunction($arg1, $arg2 = '')
    {
        if (condition) {
            statement;
        }
        return $val;
    }
    
  • Comments - C style comments (/* */) and standard C++ comments (//) are both fine. Use of Perl/shell style comments (#) is discouraged.
  • PHP Code Tags - Always use <?php ?> to delimit PHP code, not the <? ?> shorthand. This is required for PHP compliance and is also the most portable way to include PHP code on differing operating systems and setups.
  • Variable Names -
    • Use all lower case letters
    • Use '_' as the word separator.
    • Global variables should be prepended with a 'g'.
    • Global constants should be all caps with '_' separators.
    • Static variables may be prepended with 's'.
  • Make Functions Reentrant - Functions should not keep static variables that prevent a function from being reentrant.
  • Alignment of Declaration Blocks - Block of declarations should be aligned.
  • One Statement Per Line - There should be only one statement per line unless the statements are very closely related.
  • Short Methods or Functions - Methods should limit themselves to a single page of code.
There could be many more points which should be considered while writing your PHP program. Over all intension should be to be consistent throughout of the code programming and it will be possible only when you will follow any coding standard. YOu can device your own standard if you like something different.

PHP provides a large number of predefined variables to any script which it runs.PHP provides an additional set of predefined arrays containing variables from the web server the environment, and user input. These new arrays are called superglobals:
All the following variables are automatically available in every scope.

PHP Superglobals:

VariableDescription
$GLOBALS Contains a reference to every variable which is currently available within the global scope of the script. The keys of this array are the names of the global variables.
$_SERVER This is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these. See next section for a complete list of all the SERVER variables.
$_GET An associative array of variables passed to the current script via the HTTP GET method.
$_POST An associative array of variables passed to the current script via the HTTP POST method.
$_FILES An associative array of items uploaded to the current script via the HTTP POST method.
$_REQUEST An associative array consisting of the contents of $_GET, $_POST, and $_COOKIE.
$_COOKIE An associative array of variables passed to the current script via HTTP cookies.
$_SESSION An associative array containing session variables available to the current script.
$_PHP_SELF A string containing PHP script file name in which it is called.
$php_errormsg $php_errormsg is a variable containing the text of the last error message generated by PHP.

Server variables: $_SERVER

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these.
VariableDescription
$_SERVER['PHP_SELF'] The filename of the currently executing script, relative to the document root
$_SERVER['argv'] Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string.
$_SERVER['argc'] Contains the number of command line parameters passed to the script if run on the command line.
$_SERVER['GATEWAY_INTERFACE'] What revision of the CGI specification the server is using; i.e. 'CGI/1.1'.
$_SERVER['SERVER_ADDR'] The IP address of the server under which the current script is executing.
$_SERVER['SERVER_NAME'] The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.
$_SERVER['SERVER_SOFTWARE'] Server identification string, given in the headers when responding to requests.
$_SERVER['SERVER_PROTOCOL'] Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0';
$_SERVER['REQUEST_METHOD'] Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.
$_SERVER['REQUEST_TIME'] The timestamp of the start of the request. Available since PHP 5.1.0.
$_SERVER['QUERY_STRING'] The query string, if any, via which the page was accessed.
$_SERVER['DOCUMENT_ROOT'] The document root directory under which the current script is executing, as defined in the server's configuration file.
$_SERVER['HTTP_ACCEPT'] Contents of the Accept: header from the current request, if there is one.
$_SERVER['HTTP_ACCEPT_CHARSET'] Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso-8859-1,*,utf-8'.
$_SERVER['HTTP_ACCEPT_ENCODING'] Contents of the Accept-Encoding: header from the current request, if there is one. Example: 'gzip'.
$_SERVER['HTTP_ACCEPT_LANGUAGE'] Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'.
$_SERVER['HTTP_CONNECTION'] Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'.
$_SERVER['HTTP_HOST'] Contents of the Host: header from the current request, if there is one.
$_SERVER['HTTP_REFERER'] The address of the page (if any) which referred the user agent to the current page.
$_SERVER['HTTP_USER_AGENT'] This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586).
$_SERVER['HTTPS'] Set to a non-empty value if the script was queried through the HTTPS protocol.
$_SERVER['REMOTE_ADDR'] The IP address from which the user is viewing the current page.
$_SERVER['REMOTE_HOST'] The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user.
$_SERVER['REMOTE_PORT'] The port being used on the user's machine to communicate with the web server.
$_SERVER['SCRIPT_FILENAME'] The absolute pathname of the currently executing script.
$_SERVER['SERVER_ADMIN'] The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file.
$_SERVER['SERVER_PORT'] The port on the server machine being used by the web server for communication. For default setups, this will be '80'.
$_SERVER['SERVER_SIGNATURE'] String containing the server version and virtual host name which are added to server-generated pages, if enabled.
$_SERVER['PATH_TRANSLATED'] Filesystem based path to the current script.
$_SERVER['SCRIPT_NAME'] Contains the current script's path. This is useful for pages which need to point to themselves.
$_SERVER['REQUEST_URI'] The URI which was given in order to access this page; for instance, '/index.html'.
$_SERVER['PHP_AUTH_DIGEST'] When running under Apache as module doing Digest HTTP authentication this variable is set to the 'Authorization' header sent by the client.
$_SERVER['PHP_AUTH_USER'] When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the username provided by the user.
$_SERVER['PHP_AUTH_PW'] When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the password provided by the user.
$_SERVER['AUTH_TYPE'] When running under Apache as module doing HTTP authenticated this variable is set to the authentication type.



1  2   3      5      7      9   10   11   12    13    14      15      16

php-10

PHP must be configured correctly in the php.ini file with the details of how your system sends email. Open php.ini file available in /etc/ directory and find the section headed [mail function].
Windows users should ensure that two directives are supplied. The first is called SMTP that defines your email server address. The second is called sendmail_from which defines your own email address.
The configuration for Windows should look something like this:
[mail function]
; For Win32 only.
SMTP = smtp.secureserver.net

; For win32 only
sendmail_from = webmaster@tutorialspoint.com
Linux users simply need to let PHP know the location of their sendmail application. The path and any desired switches should be specified to the sendmail_path directive.
The configuration for Linux should look something like this:
[mail function]
; For Win32 only.
SMTP = 

; For win32 only
sendmail_from = 

; For Unix only
sendmail_path = /usr/sbin/sendmail -t -i
Now you are ready to go:

Sending plain text email:

PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient's email address, the subject of the the message and the actual message additionally there are other two optional parameters.
mail( to, subject, message, headers, parameters );
Here is the description for each parameters.
Parameter Description
to Required. Specifies the receiver / receivers of the email
subject Required. Specifies the subject of the email. This parameter cannot contain any newline characters
message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
parameters Optional. Specifies an additional parameter to the sendmail program
As soon as the mail function is called PHP will attempt to send the email then it will return true if successful or false if it is failed.
Multiple recipients can be specified as the first argument to the mail() function in a comma separated list.

Example:

Following example will send an HTML email message to xyz@somedomain.com. You can code this program in such a way that it should receive all content from the user and then it should send an email.
<html>
<head>
<title>Sending email using PHP</title>
</head>
<body>
<?php
   $to = "xyz@somedomain.com";
   $subject = "This is subject";
   $message = "This is simple text message.";
   $header = "From:abc@somedomain.com \r\n";
   $retval = mail ($to,$subject,$message,$header);
   if( $retval == true )  
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }
?>
</body>
</html>

Sending HTML email:

When you send a text message using PHP then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But PHP provides option to send an HTML message as actual HTML message.
While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example:

Following example will send an HTML email message to xyz@somedomain.com copying it to afgh@somedomain.com. You can code this program in such a way that it should recieve all content from the user and then it should send an email.
<html>
<head>
<title>Sending HTML email using PHP</title>
</head>
<body>
<?php
   $to = "xyz@somedomain.com";
   $subject = "This is subject";
   $message = "<b>This is HTML message.</b>";
   $message .= "<h1>This is headline.</h1>";
   $header = "From:abc@somedomain.com \r\n";
   $header = "Cc:afgh@somedomain.com \r\n";
   $header .= "MIME-Version: 1.0\r\n";
   $header .= "Content-type: text/html\r\n";
   $retval = mail ($to,$subject,$message,$header);
   if( $retval == true )
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }
?>
</body>
</html>

Sending attachments with email:

To send an email with mixed content requires to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries.
A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the email's final section must also end with two hyphens.
Attached files should be encoded with the base64_encode() function for safer transmission and are best split into chunks with the chunk_split() function. This adds \r\n inside the file at regular intervals, normally every 76 characters.
Following is the example which will send a file /tmp/test.txt as an attachment. you can code your program to receive an uploaded file and send it.
<html>
<head>
<title>Sending attachment using PHP</title>
</head>
<body>
<?php
  $to = "xyz@somedomain.com";
  $subject = "This is subject";
  $message = "This is test message.";
  # Open a file
  $file = fopen( "/tmp/test.txt", "r" );
  if( $file == false )
  {
     echo "Error in opening file";
     exit();
  }
  # Read the file into a variable
  $size = filesize("/tmp/test.txt");
  $content = fread( $file, $size);

  # encode the data for safe transit
  # and insert \r\n after every 76 chars.
  $encoded_content = chunk_split( base64_encode($content));
  
  # Get a random 32 bit number using time() as seed.
  $num = md5( time() );

  # Define the main headers.
  $header = "From:xyz@somedomain.com\r\n";
  $header .= "MIME-Version: 1.0\r\n";
  $header .= "Content-Type: multipart/mixed; ";
  $header .= "boundary=$num\r\n";
  $header .= "--$num\r\n";

  # Define the message section
  $header .= "Content-Type: text/plain\r\n";
  $header .= "Content-Transfer-Encoding:8bit\r\n\n";
  $header .= "$message\r\n";
  $header .= "--$num\r\n";

  # Define the attachment section
  $header .= "Content-Type:  multipart/mixed; ";
  $header .= "name=\"test.txt\"\r\n";
  $header .= "Content-Transfer-Encoding:base64\r\n";
  $header .= "Content-Disposition:attachment; ";
  $header .= "filename=\"test.txt\"\r\n\n";
  $header .= "$encoded_content\r\n";
  $header .= "--$num--";

  # Send email now
  $retval = mail ( $to, $subject, "", $header );
  if( $retval == true )
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }
?>
</body>
</html>
You try all the above examples. If you face any problem then you can post that problem in discussion forum.

A PHP script can be used with a HTML form to allow users to upload files to the server. Initially files are uploaded into a temporary directory and then relocated to a target destination by a PHP script.
Information in the phpinfo.php page describes the temporary directory that is used for file uploads as upload_tmp_dir and the maximum permitted size of files that can be uploaded is stated as upload_max_filesize. These parameters are set into PHP configuration file php.ini
The process of uploading a file follows these steps
  • The user opens the page containing a HTML form featuring a text files, a browse button and a submit button.
  • The user clicks the browse button and selects a file to upload from the local PC.
  • The full path to the selected file appears in the text filed then the user clicks the submit button.
  • The selected file is sent to the temporary directory on the server.
  • The PHP script that was specified as the form handler in the form's action attribute checks that the file has arrived and then copies the file into an intended directory.
  • The PHP script confirms the success to the user.
As usual when writing files it is necessary for both temporary and final locations to have permissions set that enable file writing. If either is set to be read-only then process will fail.
An uploaded file could be a text file or image file or any document.

Creating an upload form:

The following HTM code below creates an uploader form. This form is having method attribute set to post and enctype attribute is set to multipart/form-data
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="/php/file_uploader.php" method="post"
                        enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
This will display following result:
File Upload:
Select a file to upload: 







NOTE: This is just dummy form and would not work.

Creating an upload script:

There is one global PHP variable called $_FILES. This variable is an associate double dimension array and keeps all the information related to uploaded file. So if the value assigned to the input's name attribute in uploading form was file, then PHP would create following five variables:
  • $_FILES['file']['tmp_name']- the uploaded file in the temporary directory on the web server.
  • $_FILES['file']['name'] - the actual name of the uploaded file.
  • $_FILES['file']['size'] - the size in bytes of the uploaded file.
  • $_FILES['file']['type'] - the MIME type of the uploaded file.
  • $_FILES['file']['error'] - the error code associated with this file upload.
The following example below attempts to copy a file uploaded by the HTML Form listed in previous section page to /var/www/html directory which is document root of your PHP server and it will display all the file's detail upon completion. Please note that if you are going to display uploaded file then don't try with binary files like images or word document.
Here is the code of uploader.php script which will take care of uploading a file.
<?php
if( $_FILES['file']['name'] != "" )
{
   copy( $_FILES['file']['name'], "/var/www/html" ) or 
           die( "Could not copy file!");
}
else
{
    die("No file specified!");
}
?>
<html>
<head>
<title>Uploading Complete</title>
</head>
<body>
<h2>Uploaded File Info:</h2>
<ul>
<li>Sent file: <?php echo $_FILES['file']['name'];  ?>
<li>File size: <?php echo $_FILES['file']['size'];  ?> bytes
<li>File type: <?php echo $_FILES['file']['type'];  ?>
</ul>
</body>
</html>
When you will upload a file using upload form and upload script, it will display following result:
Uploaded File Info:
  • Sent file: uploadedfile.txt
  • File size: 2003 bytes
  • File type: image/jpg
You try out above example yourself on your webserver. If you have any problem then post it to Discussion Forums to get any further help.


1  2   3      5      7      9   10   11   12    13    14      15      16
 
Blogger Templates