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 :-

Monday, January 4, 2016

Python Basics 02 - Data Structures


How are you today?

Today we are going to see how to define and initialize python variables and other data structures like arrays, etc.

Before we talk about variables, I want to tell you some additional but vary basic things in python.

print("This is the First Line",end=' ')
print("This is the Second Line")

In the above code end='' will tell the compiler to print the line break.

\t is used to print the tab space and \n is used to print the line break.

To generate random numbers in Python you have to import an external library.

import random
random.random() - This function will return a random  number between 0 and 1
random.randint(1,30) -  This function will return a random values between two specified integer values

Ok now, Let's start with Python Variables.
It is not very hard to create a variable in Python. You just have to give the name of the variable and assign the value to the variable as you do in other programming languages. Python compiler will identify the variable type using the value which is stored.

str = "This is a String Variable"
number = 23 //This is a Integer Variable
floating = 34.78233 // This is a floating point number

Well the variable initialization and deceleration in Python is simple as that.

But you have to keep in mind that if you save an number as a String variable type you will not be able to do any arithmetic calculations without converting that variable value to Integer type.

num1 = "23" //This variable holds 23 as a String Type values
num2 = num1*2 //If you try to do arithmetic operation like this you will get an error
If you want to do this calculation you have to convert the string value to Integer value first as follows.
num2 = int(num1)*2  //This will print the correct value

Now let's look in to LIST data structure in Python.

List is similar to array in PHP or Java but can grow in the size.

[] - This will create an empty list
numbers = [1,2,3,4,5,6] - This is an Integer List

Python allows nested lists too.
nestedList = [1,2,3,4,["One",''Two","Three''],5,6]

len(nestedList) - To get the length of the List
nestedList[4] - Returns the value of the 4th index of the List
nestedList[1:4] - Returns the values between 1 and 4 indexes of the List
nestedList[:4] - Returns the values of the indexes which are less than 4
nestedList[4:] - Returns the values of the indexes which are greater than 4

Now let's look in to DICTIONARY data structure in Python.

Dictionary data structure in Python allows you to save a values with a reference key just as a phone book saves the numbers with the name which refers to the number.

empty = {}  // This is an empty dictionary
phoneList = {"Dulanjana":"12345","Bhagya":"67890","Fernando":"23986"}

phoneList.keys() - This will return all the keys in phoneList dictionary
phoneList.values() - This will return all the values in phoneList dictionary
phoneList["Dulanjana"] - This will return the value which refer by the given key // 12345

Well, Hope you got something from this.
See you from another tutorial.

Past Topics :-



Friday, December 25, 2015

Python Basics 01 - Hello World Application


Hello There!

Today we are going to develop a Hello World application using Python Programming Language.

Python is a widely used general purpose, high level programming language. Its syntax allows programmers to express concepts in fewer lines of code.

First of all to begin Python programming you should have to install Python to your computer. You will be able to download the Python Setup from the following link.
https://www.python.org/downloads/

After downloading and installing Python to your computer open your notepad or any text editor which you have installed in your computer.

Now lets write the "Hello World!" application using python.

print("Hello World!")

After typing the code you have to save the text file using ' .py 'extension. It is mandatory to save the file using .py extension.

After saving the file start your command prompt and go to the directory where you have saved the python file.
Then type:
python <filename>.py

Example : python helloWorld.py

Then Python compiler will compile and run the code. You will be able to see the output in the command prompt.

Let's meet with another tutorial.

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 :-

Sunday, October 25, 2015

Connecting Online Database to a Java Application



Today we are going to talk about connecting your java application to a online database.
It is very similar to connecting a offline database which is in your computer.

First of all you have to go to your control panel.

Then click on the Remote MySQL. Then you will be asked to add an access host. You  can enter the IP address of the computer that you are going to access the database. If you are accessing the database using a dynamic IP address, then you are allowed to enter percentage sign (%).
It will allow any IP address to access the database. (This is considered as a security risk)

Well, after you adding the access host, you can start connecting the java application to the database.


Now select the database driver and select connect using from the list.


Enter the correct data to the fields and click next and then finish.

Connecting to the online database is now completed. Retrieving and updating data is same as java offline databases.

Hope you got it correctly.
Please comment any questions.

Past Topics:-


Friday, September 25, 2015

Notice : Voila



How are you today?

Today this post is about to inform you about a new social media and online chatting website. Actually it was developed by me. So you are welcome to try it.

http://voilalk.com

Here is the link, experience the website and let me know what you think.

Thank You!

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.