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

Sunday, February 7, 2016

File Upload in PHP


Hello, How are you today?

Today we are going to upload a file using PHP and save it in the server.

When we upload a file it will be uploaded as a temporary file to the server. If we do not save this uploaded file in another directory in the server it will get deleted after the session is over.

First of all let's create the HTML form that helps us to upload the file.

<form action="" method="POST" enctype="multipart/form-data">
         <input type="file" name="uploadedFile" />
         <input type="submit"/>
      </form>

When creating the HTML form you have to keep two things in your mind.

  • Type of the input field should be file.
  • Form must have an enctype attribute set as enctype="multipart/form-data".
Now we have created the HTML form. Let's see how upload the file and save it using PHP.

PHP has a global variable called $_FILE to access the information of the uploaded file. This global variable has a two dimensional array which stores all the information about the uploaded file.
$_FILE has following variables:-
  • $_FILE['uploadedFile'][temp_name''] - This gives the name of the temporary file which has been created in the server.
  • $_FILE['uploadedFile']['error'] - This returns the error codes which occurred and associated with the file.
  • $_FILE['uploadedFile']['name'] - This returns the actual name of the uploaded file.
  • $_FILE['uploadedFile']['size'] - This returns the size of the uploaded file.
  • $_FILE['uploadedFile']['type'] - This returns the MIME type of the uploaded file.
Now let's upload and save the file in the server.


if(isset($_FILES['uploadedFile'])){
    
    $file_name = $_FILES['uploadedFile']['name'];
    $file_size = $_FILES['uploadedFile']['size'];
    $file_tmp = $_FILES['uploadedFile']['tmp_name'];
    $file_type = $_FILES['uploadedFile']['type'];
    
//getting the actual file extention
    $file_ext=strtolower(end(explode('.',$_FILES['uploadedFile']['name'])));
    
//checking whether the file is an excel file
    if(!($file_ext=="xlsx" || $file_ext=="xls")){
   
        $newName = "CTNS.".$file_ext;

//saving the file in new location called upload
         move_uploaded_file($file_tmp,'upload/'.$newName);
     }
}
 

Well now we have uploaded the file and saved in a new location in the server. Hope you can understand!

See you from another tutorial.

Comment box is open for Questions, Suggestions, Complaints and Comments.

Past Topics :-

Friday, November 6, 2015

GZIP with PHP



Hello there!

Today we are going to talk about GZIP compression with PHP.

GZIP is a compression method used by web servers to compress the content of a web page and send it to the client(web browser). Using this more bandwidth will be saved and the web pages are loaded faster.
But the problem is most of the web developers are not aware about it.
Google, Yahoo and Facebook are some examples for websites that use GZIP to compress web page contents.

First of all you should know that GZIP is an compression method, not an encryption method.
Most of the web servers and browsers support GZIP.
GZIP is actually a file format which is used for file compression and decompression. When a web server receive an page request from a client web server will send the page details as in the actual size of the page. (sometimes this page will be 100 KB large)
When a web server which uses GZIP receive an page request web server will use GZIP and compress the web page so that the web page size will be reduced. This will help user to load the web pages faster and save the bandwidth.

Adding GZIP to your web page is very simple and easy., you all have to do is add some simple line of code to your web pages.

Copy and paste the following code snippet to the very beginning of your web page.


<?php ob_start("ob_gzhandler"); ?>

Now your web page will be served to the user faster.


Comment for any questions, suggestions, compliments or complaints.

Past Topics :-

Wednesday, September 23, 2015

Creating Online Real-Time Chat Application in PHP and JavaScript




Hey guys, how are you today?
Today we are going to create a Simple Real-Time chat application using PHP and JavaScript.

Let's assume that we have created a suitable database. Following are the details of the database that i have created for the demo application.
Database Name - DemoChat
Table Name - ChatTbl
Column 1 - User
Column 2 - Message

Now we are good to go.

First we have to create the user interface for the chat application.
Here is the sample code:-


<html>
<head><title>Chat Application</title></head>
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script>
function submitChat(){
if(form1.uname.value==""||form1.msg.value==""){
alert("Fill all fields!!");
return;
}



var uname = form1.uname.value;
var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById('chatLog').innerHTML = xmlhttp.responseText;

}
}
xmlhttp.open('GET','insert.php?uname='+uname+'&msg='+msg,true);
xmlhttp.send();
}

//jquey lines 
$(document).ready(function (e){
$.ajaxSetup({cache:false});
setInterval(function(){$('#chatLog').load('logs.php');},2000);
}
)

</script>

<body>
<form name="form1">
Enter chat name : <input type="text" name="uname"/>
Your Message : <textarea name="msg"></textarea><br/>
<a href="#" onclick="submitChat()">Send</a><br/><br/>



<div id="chatLog">
This is the Chat LOG
</div>
</form>
</body>
</html>

Well let's see the code in detail.
In the first script tag we have added a jQuery file which will be needed in the code.
Then the function submitChat() is created. In this function first it checks whether the user name and the message fields are filled by the user. If not it will create an alert.

If these fields are not empty, the contents of these fields are assigned to JavaScript variables.
Then XML and HTTP object is created as follows.
var xmlhttp = new XMLHttpRequest();
This will allow us to load a PHP code without reloading the page.

Later,
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById('chatLog').innerHTML = xmlhttp.responseText;

}
}
xmlhttp.open('GET','insert.php?uname='+uname+'&msg='+msg,true);
xmlhttp.send();
}

In this code it sends the user name and message content to a PHP page named insert.php.

Then,
$(document).ready(function (e){
$.ajaxSetup({cache:false});
setInterval(function(){$('#chatLog').load('logs.php');},2000);
}
)

In this code it runs the code in logs.php and prints the content inside the div tag where the id is equal to chatLog. And refreshes only the content of that particular div tag in every 2000 mili-seconds.

Code after the <body> tag is plain HTML, so I hope you will understand it.


Now let's look at the insert.php file.
Here is the sample code:-

<?php
$uname = $_REQUEST['uname'];
$msg = $_REQUEST['msg'];

//create DB connection and select DB
#Hope you know how to connect to a database and select the database in PHP
#If not please refer Connecting Database in PHP

mysql_query("INSERT INTO ChatTbl VALUES('$uname','$msg');");

?>

In this code it will insert or save the values what the user enters to the database. This code will run when the user hits the SEND link in the user interface.

Now let's look at the logs.php file.
Here is the sample code:-

<?php

//create DB connection and select DB
#Hope you know how to connect to a database and select the database in PHP
#If not please refer Connecting Database in PHP

$result = mysql_query("SELECT * FROM ChatTbl");//order by ACSC

while($row = mysql_fetch_array($result)){
echo($row['User'].":".$row['Message']);
}
?>

In this code it selects the content of the table ChatTbl and prints to the user interface.

Hope you got it correctly. Please comment for the questions.

Past Topics:-


Like Us on Facebook:-


Comment Box is open for your Ideas, Complaints, Questions, Suggestions and Comments.

Sunday, June 21, 2015

File Read and Write in PHP


Hello guys, how are you?

Today we will look in to the File Operations in PHP.

Whether to read or a write to a file, first of all we must open the file using PHP. The function that we use to open a file in PHP is fopen() function. This function accepts two parameters:-

  • file path
  • the mode that the file should be opened
$fp = fopen("input.txt", "r");

Here file is opened and assigned to a variable. This variable is usually called as file pointer. This will make our operations easy.



Modes that we can open a file :-
  • r - read only
  • w - write only(existing data will be re-written)
  • a - write only(new text will be added to the end of the existing text)
  • x - creates a new file for write only
  • r+ - opens a file for read and write
  • w+ - opens a file for read and write
  • a+ - opens a file for read and write
  • x+ - creates a new file for read and write

After opening the file in read  mode we can read the text which is existing in the file and assign it to a PHP variable. To do that we can use fread()  function. This function accepts two parameters.
  • file path
  • maximum bytes to read
$content = fread("input.txt",1024);

Or else we can use the file pointer variable as parameter. If we use that as a parameter it will read the file till it reach the end of the file.

$content = fread($fp);

If we want to read a single line of the file we can do it using fgets() function. This function also accepts two parameters. 
  • file path
  • file open mode
$content = fgets("input.txt","r");
$content = fread($fp);

In some context we maybe want to check whether the file pointer has reached the end of the file. So we can do it using feof() function. This function accepts one parameter which is the file pointer variable.

if(feof($fp)){
     echo("End of the file has reached!");
}

After opening a file for reading or writing purpose we have to close the file. Otherwise the file pointer will keep the file open and that will lead for errors and unexpected problems. To close a file we can use fclose() function. This function accepts one parameter which is also the file pointer variable.

fclose($fp);

These are the basic and most used file handling functions in PHP and there are plenty of more functions available to do various tasks.
Below link will show some more functions :-


Past Topics :-
Like us on Facebook:



Comment box is open for your comments, ideas and suggestions!

Friday, May 8, 2015

Creating PDF Reports and Files in PHP


Hello everyone, how are you guys??
Sorry for my silence in past few days, had some projects and assignments to complete!

Well this article will focus on creating a PDF report or a PDF file using PHP.

So first of all we have to download the FPDF support library to generate PDF files. Visit  http://www.fpdf.org/ and go to downloads and download the latest version.

Well now we are ready to go.

Step 1 :- Import the library to our PHP file.
              include("includes/fpdf/fpdf.php");

Step 2 :- In order to use the functions in FPDF library we have to create a object of fpdf class.
                         $pdf = new FPDF('P','pt','A4');
 In here $pdf is our object name and P is for the page orientation, A4 is for page size.

Step 3 :- Now we have created the object and we have to open the pdf file.
                        //opening the pdf file
              $pdf->Open();

Step 4 :- Then add the first page of the PDF file.
                       //add the first page
             $pdf->AddPage("P","A4");

Step 5 :- Set the X and Y axis for the content in the PDF file
             //setting y axis through a variable
             $Yax = 30;
             $pdf->SetY($Yax);
             //setting X axis directly
             $pdf->SetX(40);



Well now, we have created our pdf file. Remember not to add PHP closing tag in the PDF generating code.

Lets see some functions that we can use to add some text and decorate them.

//setting title
$pdf->SetFillColor(234,44,234);
Above lines will add background color to the text.

//setting font $pdf->SetFont('Arial','B',25);
Above lines will define the font that we want our text to be printed in the PDF file

//adding the text to the pdf file $pdf->Cell(0,30,"Book Catalogue",0,1,"C",1);
Above lines will add the text or the line of text to the PDF file. 
$pdf->Cell(a,b,c,d,e,f,g);
a - X value of the position
b - Y value of the position
c - text that we want to print
d - border value of the text cell
e - line number
f - alignment of the text
g - indicates if the line cell background is filled(true,1) or not(false,0). Default value is false.

//adding more text to the pdf file(paragraphs)
$pdf->Write(0,"Error selecting values from database! ".mysql_error());
$pdf->Write(0,"your paragraph here");
Above lines will add text to pdf file.


At the end of the PHP code we have to add $pdf->Output(); function to make our PDF file visible. Without this function our PDF file will not be generated and printed to the screen.
Well hope you guys got some basic knowledge about generating a PDF file using PHP.
Comment box is open for your ideas, suggestions..
Thank You!

See you guys.. :)


Monday, January 19, 2015

Connecting Database in PHP

කොහොමද කට්ටිය ගොඩ කාලෙකට පස්සෙ?


අපි අද බලමු කොහොමද MySQL database එකක් අපේ PHP page එකට connect කරගන්නෙ කියලා!


First of all  we have to start our Apache Server in WAMP or XAMP. මම හිතනව ඔයලා ඒක නම් දනටමත් දන්නවා ඇති කියලා. ;)

Now we have to create our basic PHP file and save it in the WAMP or XAMP.

In WAMP you have to save your PHP file in the "www" folder in WAMP folder in "C" directory.
In XAMP you have to save your PHP file in the "htdocs" folder in XAMP folder in "C" directory.

Now we have to create our database in MySQL, so you have to start the MySQL server in XAMP.



දැන් අපි අපේ database එක create කරමු. First of all we have to login to MySQL.

දැන් අපි බලමු කොහොමද command prompt එකෙන් MySQL login වෙන්නෙ කියල.



After typing and pressing Enter button in the command prompt you will be asked to enter a password. Just don't type anything! Just Press Enter Button.

දැන් ඔයලා MySQL වලට login වෙලා ඉන්නෙ.

-u root = root is the default user in MySQL.
-p = password for the user, but root does not have any password so we keep it blank.
-h = this is the host where the database is located. We use localhost because our database is located in our local machine.


We create database with the command:- CREATE DATABASE test123;

test123 කියන්නෙ අපි create කරන database එකේ name එක.

හරි දැන් අපේ database එක create වෙලා ඉවරයි.

Now we have to select our database using:- USE DATABASE test123;

හරි,දැන් අපි PHP පැත්තට හැරෙමු.

First of all we have to establish the connection with the database server. 

$host = "localhost";
$user = "root";
$password = "";

$conn = mysql_connect('$host','$user',$password');    //This will select and establish the connection to the database server
if(!$conn){ die("Could not connect :".mysql_error());}
else { echo "Connection established to the Server!"}

දැන් database server එකට connection එක establish වෙලා තියෙන්නේ.

Now we have to select our database to use.

$dbName = "test123";

mysql_select_db('$dbName','$conn') or die ("Can not select Database".mysql_error());

දැන් අපේ database එකට අපි connect වෙලා ඉවරය.


Die is a PHP function which we use to handle exceptions such as database unavailability. It will terminate the attempt and returns an error if the database in unavailable.


ඊළඟ post එකෙන් අපි database එකෙන් data retrieve කරන හැටි බලමු.


ගැටලු සඳහා පහතින් comment කරන්න.