Monday 16 June 2014

How can we upload files in php.

If you want to upload any files in php.So first create the form by using <form></form> tag in php.

<html>
<body>
<form action="upload.php" method="post"
        enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html>









Now,for uploading we have to create script for "upload.php" file.


<?php
if ($_FILES["file"]["error"] > 0) {
  echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else {
  echo "Upload: " . $_FILES["file"]["name"] . "<br>";
  echo "Type: " . $_FILES["file"]["type"] . "<br>";
  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
  echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>


Using of PHP $_FILES array you can upload files from a client computer to the remote server.

The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this:

$_FILES["file"]["name"]       // the name of the uploaded file.
$_FILES["file"]["type"]       // the type of the uploaded file.
$_FILES["file"]["size"]       //  the size in bytes of the uploaded file.
$_FILES["file"]["tmp_name"]   //the name of the temporary copy of the file stored on the server.
$_FILES["file"]["error"]      // the error code resulting from the file upload.

You can also put restrictions on Upload-

In this script we add some restrictions to the file upload. The user may upload .gif, .jpeg, and .png files; and the file size must be under 40 kB:

<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 40000)
&& in_array($extension, $allowedExts)) {
  if ($_FILES["file"]["error"] > 0) {
    echo "Error: " . $_FILES["file"]["error"] . "<br>";
  } else {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Stored in: " . $_FILES["file"]["tmp_name"];
  }
} else {
  echo "Invalid file";
}
?>

Saving the Uploaded File-


<?php
             $allowedExts = array("gif", "jpeg", "jpg", "png");
             $temp = explode(".", $_FILES["file"]["name"]);
             $extension = end($temp);

if ((($_FILES["file"]["type"] == "image/gif")
            || ($_FILES["file"]["type"] == "image/jpeg")
            || ($_FILES["file"]["type"] == "image/jpg")
            || ($_FILES["file"]["type"] == "image/pjpeg")
            || ($_FILES["file"]["type"] == "image/x-png")
            || ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 40000)
&& in_array($extension, $allowedExts)) {
  if ($_FILES["file"]["error"] > 0) {
              echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
  } else {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
    if (file_exists("upload/" . $_FILES["file"]["name"])) {
      echo $_FILES["file"]["name"] . " already exists. ";
    } else {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
    }
  }
} else {
  echo "Invalid file";
}
?>

The above script first checks if the file already exists, if it does not, it copies the file to a folder called "upload".


Posted by Amit Tiwari

Difference between include() & require()

Hello friend ..today i am going to teach you about the both { Include() & Require() } main functions in php.Both has same meaning but in a different manner.

Include() function

Syntax=include('main.php');

For this we have to create the file with extention of  ".php",

<?php
<body>
<a href="http://www.example.com/index.php">Home</a> <br />
<a href="http://www.example.com/about.php">About Us</a> <br />
<a href="http://www.example.com/services.php">Services</a> <br />
<a href="http://www.example.com/portfolio.php">Portfolio</a> <br />
<a href="http://www.example.com/Contact.php">Contact Us</a>
</body>
?>

Now ,save this file as main.php.for including this file we have to create new file called index.php. Here we know about the importance or we can say that how to use a include function,

<?php include("main.php"); ?>
<p>Hello this is my first php website</p>
</html>

Require() function-

Try the same example ,by using the function require() in the place of include().The only different is that require() function gives fatal error if there is no file found.

<?php include("nofile.php"); ?>
<p>Hello this is my first website</p>


Output=It gives fatal error and stop the script.








Posted by Amit Tiwari

Thankyou,

If you have any doubt related to post and want to know more about this so just comment in the below comment box,I ll response asap.


Friday 13 June 2014

PHP end() Function

Basically End function sets the pointer of an array to the last element of array.

Syntax-end(array)










For Example-



<?php
                $arr            =  array('name'=>'amit','age'=>'22','city'=>'bhopal','profession'=>'php developer');
                $lastValue   = end($arr);
?>

OUTPUT :  php developer

Posted Amit Tiwari

What is .htaccess?

.HTACCESS define as -

"It's a configuration file for use on web servers running the Apache Web Server software. When a .htaccess file is placed in a directory which is in turn 'loaded via the Apache Web Server', then the .htaccess file is detected and executed by the Apache Web Server software."


Use of .htaccess-

1) .htaccess file is basically used for url rewriting.
2) .htaccess file used to make the site password protected.


Below example show how we can use the htaccess file.

.htaccess
















Posted by Amit Tiwari


Tuesday 10 June 2014

Difference between strstr and stristr in php.

Functions strstr() and stristr, these are used to find the first occurence of the string (case-sensitive) but stristr() is case insensitive.

strstr() - Find first occurrence of a string.

Syntax:
                   strstr ($string, string) 

Example:

<?php
                  $email = 'makersofweb@rAls.com';
                  $domain_name = strstr($email, 'A);
                 echo $domain_name;

?>

Output:

Als.com



stristr() - Find first occurrence of a string (Case-insensitive)




















stristr ($string, string) 

Example:

<?php
                     $email = 'makersofwb@rAls.com';
                     $domain_name = stristr($email, 'A');
                     echo $domain_name;
 ?>


Output-
              akersofwb@rAls.com

Posted by Amit Tiwari



str_split() function

PHP : str_split() function-

"The str_split() function is define as it's splits a string into an array"

Syntax-

str_split(string_name, split_length)











For example-























Output-


Array ( [0] => W [1] => e [2] => l [3] => c [4] => o [5] => m [6] => e [7] => [8] => t [9] => o [10] => [11] => m [12] => a [13] => k [14] => e [15] => r [16] => s [17] => o [18] => f [19] => w [20] => e [21] => b [22] => . [23] => c [24] => o [25] => m) Array ( [0] => Welc [1] => ome [2] => to m [3] => aker [4] => sofw [5] => eb.c [6] => om )


Posted by Amit Tiwari




Sunday 8 June 2014

What is str_replace()

Definition-This function replace some characters with some other characters in a string , this function is case sensitive.

Syntax:- str_replace(find,replace,string);
                             find:-required,specifies the value to find.
                             replace:-required,specifies the value to replace the value in find.
                             string:-required,specifies the string to searched.
for examlpe:-
               <?php
                                 echo str_replace("amit","daniel","hello  amit");
                 ?>
 
Output:-     hello daniel












Posted by Amit Tiwari

Use of var_dump

This function called var_dump is basically used for displaying the value and type of one or more variables.

In my definition i simply define as "Var_dump=(value+type)"

Now,let see the syntax of var_dump.

Syntax-var_dump(variable1,variable2,.....nntimes);

For Example--In this i am using one float value and one boolean value ..

/* Float=2.5 & Boolean=True */

<?php
                $a=2.5;
               $b=true;
               var_dump($a,$b);
?>

 Output :     float(2.5)
                   bool(true)


Second Example-

Var_dump

























Posted by Amit Tiwari

@Facebook

What is array_flip ?

Hello friends today i am going to teach you about the Array_flip...It define as "The array_flip() function flips/exchanges all keys with their associated values in an array."

Now,we know about syntax of array_flip-

Syntax="array_flip(array);"

For example-

<?php
                         $arrayName    = array("course1"=>"Java","course2"=>"Android");
                         $new_array    = array_flip($arrayName);
                             print_r($new_array);
?>

OUTPUT :

Array
(
[Java]          => course1
[Android]    => course2
)

Posted by Amit Tiwari

@Facebook


Thursday 5 June 2014

Session & Cookies in php.


Session in php-

A “session” is set for maintaining the user data as the person is browsing through the site. A session is very useful in e-commerce websites, social networking sites etc. In PHP, session variables are used to set the sessions. Anything can be set / stored in a session like the user’s id, username, some encrypted password string etc.

A session is always stored in the server. You lose all the session data once you close your browser, as every time you re-open your browser, a new session starts for any website.

Example: $_SESSION[‘customer_name’] = ‘Amit’;


Cookies in php-



A “cookie” is however different from a session. It stores some information like the username, last visited pages etc. So that when the customer visits the site again, he may have the same environment set for him. You can store almost anything in a browser cookie.

A cookie is stored in the client’s browser.

Like, when you check the ‘Remember Password’ link on any website, a cookie is set in your browser, which exists there in the browser until manually deleted. So, when you visit the same website again, you don’t have to re-login.

But, it can also be problematic at times, if the user has blocked cookies in his browser and you have a shopping site that utilizes cookies to store the data. Then, that person will never be able to shop from your website.

setcookie("username", "John", time()+2400);

There are some basic points in  session and cookies that are following:-

1) Session are temporary and Cookies are parmanent.
2)  Session data is store on server while Cookies are store on user's computer.
3) Cookies contents can be easily modify but to modify Session contents is very hard.
4 ) Cookies could be save for future reference but Session couldn't when user close the browser Session data also lost.

Posted by Amit Tiwari


Array_multisort function in php.

Definition of "PHP array_multisort() Function"-

The array_multisort() function returns a sorted array. You can assign one or more arrays. The function sorts the first array, and the other arrays follow, then, if two or more values are the same, it sorts the next array, and so on.
String keys will be maintained, but numeric keys will be re-indexed, starting at 0 and increase by 1.

You can assign the sorting order and the sorting type parameters after each array. If not specified, each array parameter uses the default values.

Syntax of array_multisort-

array_multisort(array1,sorting order,sorting type,array2,array3...)

First Example -

<html>
<body>

<?php
                  $a=array("Dog","Cat","Horse","Bear","Zebra");
                 array_multisort($a);
                 print_r($a);
?>

</body>
</html>

Output-

Array ( [0] => Bear [1] => Cat [2] => Dog [3] => Horse [4] => Zebra )


 Second Example-


array_multisort

















Output-











Posted by Amit Tiwari (Facebook)



Why we use array_slice.

array_slice - ( ) Cut a specified slice of elements from an array-

Use of array_slice is basically returns the selected part of an array.The array_slice() array function in PHP will cut a specified slice of elements from an array. It can take up to four parameters, but only requires two parameters to operate at a basic level. Parameter one is the array you wish to manipulate. Parameter two is the offset(where you want the array to begin to be sliced from). Parameter three is the length into the array you wish to slice. Parameter four is set to "true" to preserve keys, or "false" to not preserve keys.

Syntax-

array_slice(array,start,length,preserve)

For Example-

<html>
<body>

<?php
                  $a=array("Html","Css","Php","Java","C++");
                   print_r(array_slice($a,2));
?>

</body>
</html>

Output-
Array ( [0] => Php[1] => Java[2] => C++)


Posted by Amit Tiwari (Facebook)

Difference Between array_merge & array_combine.

Posted by Amit Tiwari

Hello friends !!! Here i am going to teach you about the ( PHP: array_merge) & (PHP: array_combine).

PHP: array_merge-


array_merge merges the elements of one or more than one array such that the value of one array appended at the end of first array. If the arrays have same strings  key  then the later value overrides the previous value for that key .

<?php
             $array1 = array("course1" => "Amit","course2" => "Tiwari");
             $array2 = array(("course1" => "Amit","course3" => "Makersofweb");
             $result = array_merge($array1, $array2);
         print_r($result);
?>

Output :  

Array
(
[course1] => Amit
[course2] => Tiwari
[course3] => Makersofweb
)

PHP: array_combine-


<?php
                     $array1    = array("course1","course2");
                     $array2    = array(("Amit ","Tiwari");
                     $new_array = array_combine($array1, $array2);
print_r($new_array);
?>

Output :

Array
(
[course1]    => Amit
[course2]    => Tiwari
)

Note-If you like the above post like and share your views with me & have any doubt then comment in below comment box... Thanks !!!Facebook, Gplus

Difference Between UNSET & UNLINK.

Posted By Amit Tiwari

Hello friends there are two main functions used for deleting the file and destroy the variable.Namely UNLINK & UNSET.

Example for Unlink function:-

-The unlink() function deletes a file.
-This function returns TRUE on success, or FALSE on failure.

Syntax-

unlink(filename,context)








Code for this,



<?php
                    $file = "test.txt";
       if (!unlink($file))
            {
                                 echo ("Error deleting $file");
             }
else
             {
                                 echo ("Deleted $file");
             }
?>

Now,before starting to know about Unset we need to know about what is Php Session Variables.

PHP Session Variables-


When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.

A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.

Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

Now..you can destroy the session means use of Unset function.
Follow the steps,

1)Start the session.
2)Storing a session variable.
3)Destroying a session.

Starting the Php session-


The "session_start() function" is placed before the <html> tag ..or we can say that this code is placed on the top of the file where you start coding for the website.

For Example,

<?php session_start(); ?>

<html>
<body>

</body>
</html>

Storing a Session Variable:-

<?php
              session_start();
// store session data
              $_SESSION['follower']=1;
?>

<html>
       <body>

<?php
//retrieve session data
                 echo "Facebook=". $_SESSION['follower'];
?>

</body>
</html>

Output-

Facebook=1

Destroying a Session:-

If you wish to delete some session data, you can use the unset() or the session_destroy() function.

<?php
session_start();
if(isset($_SESSION['follower']))
  unset($_SESSION['follower']);
?>

Or you can use directly the session destroy function..

<?php
session_destroy();
?>

Note: session_destroy() will reset your session and you will lose all your stored session data.

Posted by Amit Tiwari


WHo Is The Father Of PHP?

Posted By Amit Tiwari

Hello, Today I am going to inform you about the father of php ..who developed the server scripting language and in which year this is organized.

Rasmus Lerdford-Php was created by Rasmus Lerdorf In 1995.

-He was born in 22 November 1968,Qeqertarsuaq,Greenland.

-He created the PHP scripting language, authoring the first two versions of the language and participating in the development of later versions led by a group of developers including Jim Winstead (who later created blo.gs), Stig Bakken, Shane Caraveo, Andi Gutmans and Zeev Suraski. He continues to contribute to the project.


Education:-

He graduated from King City Secondary School in 1988, and in 1993 he graduated from the University of Waterloo with a Bachelor of Applied Science in Systems Design Engineering. He contributed to the Apache HTTP Server and he added the LIMIT clause to the MSQL DBMS. The LIMIT clause was later adapted by several other DBMS.

Awards:-

In 2003, he was named to the MIT Technology Review TR100 as one of the top 100 innovators in the world under the age of 35.

-Rasmus Lerdorf  @Twitter








Monday 2 June 2014

How php works?

Hello friends !!! Below image define as how the php works..


















Posted By Amit Tiwari