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

Friday, 7 November 2014

PHP Function's - Simple way to understand its features

PHP functions are similar to other programming languages. A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.
You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.
There are two parts which should be clear to you:
  • Creating a PHP Function
  • Calling a PHP Function
In fact you hardly need to create your own PHP function because there are already more than 1000 of built-in library functions created for different area and you just need to call them according to your requirement.

Creating PHP Function:

Its very easy to create your own PHP function. Suppose you want to create a PHP function which will simply write a simple message on your browser when you will call it. Following example creates a function called writeMessage() and then calls it just after creating it.
Note that while creating a function its name should start with keyword function and all the PHP code should be put inside { and } braces as shown in the following example below:
<html>
<head>
<title> PHP Function</title>
</head>
<body>

<?php
/* Defining a PHP Function */
function writeMessage()
{
  echo "Let we learn it";
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
This will display following result:
Let we learn it

PHP Functions with Parameters:

PHP gives you option to pass your parameters inside a function. You can pass as many as parameters your like. These parameters work like variables inside your function. Following example takes two integer parameters and add them together and then print them.
<html>
<head>
<title>PHP Function</title>
</head>
<body>

<?php
function addFunction($num1, $num2)
{
  $sum = $num1 + $num2;
  echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
This will display following result:
Sum of the two number is : 30

Passing Arguments by Reference:

It is possible to pass arguments to functions by reference. This means that a reference to the variable is manipulated by the function rather than a copy of the variable's value.
Any changes made to an argument in these cases will change the value of the original variable. You can pass an argument by reference by adding an ampersand to the variable name in either the function call or the function definition.
Following example depicts both the cases.
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num)
{
   $num += 5;
}

function addSix(&$num)
{
   $num += 6;
}
$orignum = 10;
addFive( &$orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
This will display following result:
Original Value is 15
Original Value is 21 

PHP Functions retruning value:

A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code.
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then returns their sum to the calling program. Note that return keyword is used to return a value from a function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>

<?php
function addFunction($num1, $num2)
{
  $sum = $num1 + $num2;
  return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value";
?>
</body>
</html>
This will display following result:
Returned value from the function : 30

Setting Default Values for Function Parameters:

You can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
<html>
<head>
<title>PHP Function which returns value</title>
</head>
<body>

<?php
function printMe($param = NULL)
{
   print $param;
}
printMe("letwelearnit");
printMe();
?>

</body>
</html>
This will produce following result:
letwelearnit

Dynamic Function Calls:

It is possible to assign function names as strings to variables and then treat these variables exactly as you would the function name itself. Following example depicts this behaviour.
<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function sayHello()
{
   echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>
This will display following result:
Hello

Friday, 19 September 2014

Asynchronous file upload - PHP & AJAX

 Asynchronous file upload - PHP & AJAX

Asynchronous file uploads is quote popular feature in modern AJAX web-applications. However standard AJAX classes (XmlHttpRequest) does not have capabilities to process or send files selected with "file dialog" (input type="file"). This article contains example application (trivial file-sharing service, like rapidshare, megaupload or yousendit) which uses embedded frames (IFRAME) to upload file. While file is uploaded to hidden frame, user can still access web-page and fill "file description" field.

Compatible 

  1. Adequate versions of Opera, Firefox, Internet Explorer, Safari
  2. PHP 4.3.0 or higher
  3. PHP 5
  4. PHP option 'short_open_tag' switched on (parse errors otherwise)

How IFRAME file uploading works?


    There is a simple <form... which contains only <input type="file" ... > field. Target for this form is a hidden IFRAME (with "display: none;" CSS style) and OnChange event for the file field is set to JavaScript function which checks file extension (optional for this example, but very useful in general) and submits form.
    Special part of the script (marked FILEFRAME, see comments) saves file upload, checks for uploading errors and outputs JavaScript code to that hidden IFRAME. The javascript code uses parent.window.document object, which allows to modify parent document (visible page, which users is viewing). It sets filename value and enables submit button on the other form using getElementById method.
    The other form has 'description' text-field and hidden field 'filename'. User may fill 'description' field while file is uploading. When file uploading is finished, user press submit and "file information" page is generated (based on filename from hidden field and user's file description).

Possible drawback of this method is file garbage: files are uploaded even if user does not press submit button. You may need to write 'garbage file collector' which will delete any unused file.
This example stores all uploaded file in filesystem folder. You need to specify it at the beginning of script, see variables $upload_dir and $web_upload_dir. There is fail-checking which checks whether it is possible to write create files in upload directory.

We use following functions in this example: PHP


    move_uploaded_file - move file uploaded to web server
    fopen - open file
    fwrite - write to opened file
    fclose - close file
    str_replace - replace one substring by another
    filesize - returns file size in bytes
    filemtime - returns file modification time

source code: php


$upload_dir = "/var/www/xxx/yyy"; // Directory for file storing
                                            // filesystem path

$web_upload_dir = "/yyy"; // Directory for file storing
                          // Web-Server dir

/* upload_dir is filesystem path, something like
   /var/www/htdocs/files/upload or c:/www/files/upload

   web upload dir, is the webserver path of the same
   directory. If your upload-directory accessible under
   www.your-domain.com/files/upload/, then
   web_upload_dir is /files/upload
*/


// testing upload dir
// remove these lines if you're shure
// that your upload dir is really writable to PHP scripts$tf = $upload_dir.'/'.md5(rand()).".test";$f = @fopen($tf, "w");
if ($f == false)
    die("Fatal error! {$upload_dir} is not writable. Set 'chmod 777 {$upload_dir}'
        or something like this");fclose($f);unlink($tf);// end up upload dir testing



// FILEFRAME section of the scriptif (isset($_POST['fileframe']))
{
    $result = 'ERROR';
    $result_msg = 'No FILE field found';

    if (isset($_FILES['file']))  // file was send from browser
    {
        if ($_FILES['file']['error'] == UPLOAD_ERR_OK)  // no error
        {
            $filename = $_FILES['file']['name']; // file name
            move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir.'/'.$filename);
            // main action -- move uploaded file to $upload_dir
            $result = 'OK';
        }
        elseif ($_FILES['file']['error'] == UPLOAD_ERR_INI_SIZE)
            $result_msg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
        else
            $result_msg = 'Unknown error';

        // you may add more error checking
        // see http://www.php.net/manual/en/features.file-upload.errors.php
        // for details
    }

    // outputing trivial html with javascript code
    // (return data to document)

    // This is a PHP code outputing Javascript code.
    // Do not be so confused ;)
    echo '-';
    echo '';

    exit(); // do not go futher }// FILEFRAME section END



// just userful functions
// which 'quotes' all HTML-tags and special symbols
// from user input function safehtml($s)
{
    $s=str_replace("&", "&", $s);
    $s=str_replace("<", "<", $s);
    $s=str_replace(">", ">", $s);
    $s=str_replace("'", "'", $s);
    $s=str_replace("\"", """, $s);
    return $s;
}

if (isset($_POST['description']))
{
  
    // Let's generate file information page$html =<<{$filename} [uploaded by IFRAME Async file uploader]

{$filename}


This is a file information page for your uploaded file. Bookmark it, or send to anyone...

Date: {$date}

Size: {$size} bytes

Description:
{$description}


download file

back to file uploading

upload-log



Example by Developers Guide
END;
    // save HTML
    $f = fopen($upload_dir.'/'.$filename.'-desc.html', "w");
    fwrite($f, $html);
    fclose($f);
    $msg = "File {$filename} uploaded,
           see file information page";

    // Save to file upload-log
    $f = fopen($upload_dir."/upload-log.html", "a");
    fwrite($f, "
$msg
\n");
    fclose($f);

    // setting result message to cookie 
    setcookie('msg', $msg);
    // redirecting to the script main page
    // we're doing so, to avoid POST form reposting 
    // this method of outputting messages is called 'flash' in Ruby on Rails 
    header("Location: http://".$_SERVER['HTTP_HOST'].$PHP_SELF);
    exit();
    // redirect was send, so we're exiting now}
 // retrieving message from cookie if (isset($_COOKIE['msg']) && $_COOKIE['msg'] != '') 

    if (get_magic_quotes_gpc())
        $msg = stripslashes($_COOKIE['msg']);
    else
        $msg = $_COOKIE['msg'];

    // clearing cookie, we're not going to display same message several times
    setcookie('msg', '');
} ?>

 <!-- Beginning of main page -->
<html><head>
<title>IFRAME Async file uploader example</title>
</head>
<body>
<?php if (isset($msg)) // this is special section for outputing message
    echo '<p style="font-weight: bold;">'.$msg.'</p>';?>
<h1>Upload file:</h1>
<p>File will begin to upload just after selection. </p>
<p>You may write file description, while you file is being uploaded.</p>

<form action="<?=$PHP_SELF?>" target="upload_iframe" method="post" enctype="multipart/form-data">
<input type="hidden" name="fileframe" value="true">
<!-- Target of the form is set to hidden iframe -->
<!-- From will send its post data to fileframe section of
     this PHP script (see above) -->

<label for="file">text file uploader:</label><br>
<!-- JavaScript is called by OnChange attribute -->
<input type="file" name="file" id="file" onChange="jsUpload(this)">
</form>
<script type="text/javascript">
/* This function is called when user selects file in file dialog */
function jsUpload(upload_field)
{
    // this is just an example of checking file extensions
    // if you do not need extension checking, remove
    // everything down to line
    // upload_field.form.submit();

    var re_text = /\.txt|\.xml|\.zip/i;
    var filename = upload_field.value;

    /* Checking file type */
    if (filename.search(re_text) == -1)
    {
        alert("File does not have text(txt, xml, zip) extension");
        upload_field.form.reset();
        return false;
    }

    upload_field.form.submit();
    document.getElementById('upload_status').value = "uploading file...";
    upload_field.disabled = true;
    return true;
}
</script>
<iframe name="upload_iframe" style="width: 400px; height: 100px; display: none;">
</iframe>
<!-- For debugging purposes, it's often useful to remove
     "display: none" from style="" attribute -->

<br>
Upload status:<br>
<input type="text" name="upload_status" id="upload_status"
       value="not uploaded" size="64" disabled>
<br><br>

File name:<br>
<input type="text" name="filenamei" id="filenamei" value="none" disabled>

<form action="<?=$PHP_SELF?>" method="POST">
<!-- one field is "disabled" for displaying-only. Other, hidden one is for
    sending data -->
<input type="hidden" name="filename" id="filename">
<br><br>

<label for="photo">File description:</label><br>
<textarea rows="5" cols="50" name="description"></textarea>

<br><br>
<input type="submit" id="upload_button" value="save file" disabled>
</form>
<br><br>
<a href="<?=$web_upload_dir?>/upload-log.html">upload-log</a>
<br><br><br>

</body>
</html>

If any error or queries drop it in comment section.

Wednesday, 9 July 2014

How to Setup PHP Environment on our System ??

PHP Environment Setup

Hi friends in order to develop and run PHP, three vital components need to be installed on our computer system.
  • Web Server - PHP will work with virtually all Web Server software, including Microsoft's Internet Information Server (IIS) but then most often used is freely availble Apache Server. Download Apache for free here: http://http.apache.org/download.cgi
  • Database - PHP will work with virtually all database software, including Oracle , Microsoft Access and Sybase but most commonly used is freely available MySQL database. Download MySQL for free here: http://www.mysql.com/downloads/index.html
  • PHP Parser - In order to process PHP script instructions a parser must be installed to generate HTML output that can be sent to the Web Browser. Download PHP latest version for free  here:  php-5.5.14.tar.bz

PHP Parser Installation:

Before you proceed it is important to make sure that you have proper environment setup on your machine to develop your web programs using PHP.
Type the following address into your browser's address box.

 http://127.0.0.1/info.php 

If this displays a page showing your PHP installation related information then it means you have PHP and Webserver installed properly. Otherwise you have to follow some other procedure in addition to install PHP on your computer.


For both technical & non-technical doubts comment in the section given below.

Tuesday, 8 July 2014

Introduction to PHP

  • PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language. 
  • PHP is designed to fill the gap between SSI (Server Side Includes) and Perl, intended for the web environment. Its principal application is the implementation of web pages having dynamic content.
  • PHP was installed on more than 240 million websites (39% of those sampled) and 2.1 million web servers according to a survey.
  •  Originally created by Rasmus Lerdorf in 1994, the reference implementation of PHP is now produced by The PHP Group
  • PHP originally stood for Personal Home Page,it now stands for PHP: Hypertext Preprocessor as a recursive acronym.
  • Its popularity derives from its C-like syntax, and its simplicity. The newest version of PHP is 5.5 and it is heavily recommended to always use the newest version for better security, performance and of course features.
BASIC TAGS 

Syntax : -  
<?PHP
// Your  Coding
?>

  1. When PHP parses a file, it looks for opening and closing tags, which are <?php and ?> which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser.
  2. PHP also allows for short open tags <? and ?> (which are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option.
  3. If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.

<?php
       echo "Hello world";

// ... more code
echo "Last statement";
// the script ends here with no PHP closing tag

Any Doubts clarify it in the Comment Section.