FeedAgg.com Logo
Your Account | Sign In | Sign Up

Add Feed | Search | Home | Help | Contact | Blog

Feed: PHP and MySQL Tutorial - AggScore: 50.1



File Uploading in PHP


Hello Readers!
File Uploading is now a requirement of almost every web application. Uploading means tranferring a file from user computer (Client) to the server. While uploading a file, many aspects like file size,file type etc should be considered to make it a secure process.
Like other Server side scripting languages, PHP is also equipped with a very handy file uploading mechanism. The PHP File Uploading system is a combination of setting some directives in PHP.ini file, creating a web form and creating a PHP script.


File Uploading Directives in PHP

  • file_uploads should set to on
  • upload_max_filesize set this directive to an integer value followed by capital M
  • upload_tmp_dir set this directive to a string value for example c:/wamp/myTmpFolder

Creating the HTML Form




Nothing is special except the enctype attribute which is here to handle large binary data.

Creating the PHP Script to handle the Uploaded File

The dollarsignr_FILES superglobal array is responsible to hold all the information of the uploaded file wich is posted by an HTML form. So it is better to have a deep look at dollarsignr_FILES superglobal array.
  • dollarsignr_FILES['fileName']['tmp_name'] holds the temporary file name which is uploaded to the server but not moved.
  • dollarsignr_FILES['fileName']['name'] holds the name of the file along with it's extension as it was stored on user machine(client).
  • dollarsignr_FILES['fileName']['size'] holds the size of the file in bytes.
  • dollarsignr_FILES['fileName']['type'] holds the type of the file e.g. for image files it returns image/jpeg.
  • dollarsignr_FILES['fileName']['error'] returns a value from 0 to 4. 0 is returned if no error has occured during upload while number 1 to 4 represents different errors.
Remember "fileName" is the name of the file as assigned in HTML form. Now let's move to the example script.
    if( !is_uploaded_file(dollarsignr_FILES['myFile']['name']))
 {
    if (! move_uploaded_file(dollarsignr_FILES['myFile']['tmp_name'],"c:wampimagesimage1.jpg"))
  {
      echo "File has not moved to the desired directory.";
  }
    else
  {
       echo "File Uploaded successfully.";
  }
 }
    else
 {
  echo "File not uploaded.";
 }
?>
  • is_uploaded_file() function checks whether the file has been uploaded to the temporary directory, it returns true if the file is uploaded else it returns false.
  • move_uploaded_file moves the file to it's permanent location as desired by the developer.
Other information about the uploaded file exists in the dollarsignr_FILE supergloabal. There are other advance concepts such as restricting the type and size of the file being uploaded, but for basic understanding this article is good enough.
Your comments are welcome.
Date Published: Aug 24, 2011 - 12:53 pm



How to make a Hit Counter using PHP


Hello all! in this post i m going to show you how to make a web hit counter using PHP.It is a very easy and useful hit counter which can display the total number of visits made to your website.In this post you will also learn the file handling capabilities of PHP.Following is the complete code of counter.The file counter.dat is already created on the server, than this file is read and incremented everytime your webpage is requested by a browser.

dollarsignrfile= "counter.dat" ;
dollarsignrfileData = fopen (dollarsignrfile , "r") or exit("Unable to Open file") ;
dollarsignrvisits = fread (dollarsignrfileData , filesize (dollarsignrfile)) ;
echo "";
echo "";
echo "" ;
echo "
My Hit Counter
".dollarsignrvisits."
";
fclose(dollarsignrfileData) ;
dollarsignrfileData = fopen (dollarsignrfile , "w") or exit("Unable to Open file.") ;
dollarsignrincrementVisit = dollarsignrvisits + 1 ;
dollarsignrfsent= fwrite (dollarsignrfileData , dollarsignrincrementVisit ) ;
fclose(dollarsignrfileData) ;
?>

In the first line the dollarsignrfile variable is holding the filename.This file is than opened in read mode by the fopen() function along with "r" attribute.The data is read and later incremented by the fwrite() function.
Date Published: Dec 30, 2010 - 1:30 am



Simple PHP Gridview


If someone is migrating from ASP.Net to PHP than he must be searching for Gridview kind of funtionality in PHP.Basically this kind of job is accomplished in PHP by populating an HTML table at runtime i.e extracting each row from the database one by one and than build a table dynamically.Following code is doing the same...

dollarsignrhost="localhost";
dollarsignrusername="shoppincartUser";
dollarsignrpassword="12345";
if (!dollarsignrconnect=mysql_connect(dollarsignrhost,dollarsignrusername,dollarsignrpassword))
{
echo "Error connecting with the database";
}
if (!mysql_select_db("example",dollarsignrconnect))
{
echo "Error selecting database";
}
dollarsignrdataset = mysql_query("select * from students",dollarsignrconnect);
echo "";
while (dollarsignrrow = mysql_fetch_assoc(dollarsignrdataset))
{
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
}
echo "
".dollarsignrrow['id']."".dollarsignrrow['name']."".dollarsignrrow['surname']."".dollarsignrrow['class']."".dollarsignrrow['GPA']."
";
?>


The PHP mysql_fetch_assoc() funtion retrieves each row one by one from the dataset extracted by the mysql_query() funtion.The PHP mysql_fetch_assoc() funtion keeps returning true until all the rows are extracted.Hence, every time when a new row is retrieved the dollarsignrrow variable holds it and later it is used to populate the table.
Date Published: Dec 29, 2010 - 10:49 pm


Creating a Database from within PHP


Creating a database from the PHP code on runtime is very simple by using a combination of Structured Query Language and the PHP mysql_query() function.

CREATE DATABASE databaseName,

mysql_query("CREATE DATABASE databaseName");

for more clarification checkout the following complete example:

dollarsignrhostname = "localhost";
dollarsignrusername = "zohaib";
dollarsignrpassword = "12345";
dollarsignrconnection = mysql_connect(dollarsignrhostname,dollarsignrusername,dollarsignrpassword);
if (!dollarsignrconnection)
{
 echo "error :".mysql_error();
}
if (!mysql_query("CREATE DATABASE myNewDatabase"))
{
echo "Not done: ".mysql_error();
}
else
{
echo "New database created.";
}
?>


This will create the new database, After the creation of database you can also create table in this database in the similar way.
Date Published: Dec 19, 2010 - 11:14 am


Steps to communicate with MySql database using PHP


If your PHP web application is dealing with a database most commonly MySql,The knowledge about the following functions and their order as described is better.
  1. mysql_connect(hostname,databaseUserName,databasePassword):This is the first function which will establish a connection with the database.It returns false on connection failure.
  2. mysql_select_db("databaseName","connectionName"):This function selects the database.It takes database name and connection name as parameter, Note that connection name is optional.This function can also return false in case of any error.
  3. mysql_query("sql"):After the connection is established and the database is selected successfully now we can talk with the database by using structured query language via mysql_query() function.This function returns the dataset on success or it can return false if the query was not executed due to some error.
  4. mysql_fetch_assoc(datasetRetrieved):This function iterate through the dataset which is retrieved as a result of mysql_query() function and gets the record one by one in the form of array.The PHP mysql_fetch_assoc () function mostly used in a while loop where each record is required to be extracted.
  5. mysql_num_rows(datasetRetrieved)This function takes the mysql_query() resulted dataset and return the number of rows this dataset has.
Date Published: Dec 19, 2010 - 9:31 am


MySql Connect : The mysql_connect() function.


MySql is the database mostly paired with PHP to provide robust functionality of Interactive webpages.To establish any communication with database in MySql, it is necessary to connect with the database.

The PHP mysql_connect() function is used to open a connection with MySql database.The PHP mysql_connect() function takes three parameters i.e server name,database username and database user password.If the PHP mysql_connect() function fails to connect with the database it returns false.The reason of why the connection was unsuccessful, can be retrieve by the PHP mysql_error() function.The example below will be useful.

dollarsignrhostname = "localhost";
dollarsignrusername = "zohaib";
dollarsignrpassword = "12345";
dollarsignrconnection = mysql_connect(dollarsignrhostname,dollarsignrusername,dollarsignrpassword);
if (!dollarsignrconnection)
{
 echo "error :".mysql_error();
}
else
{
echo "Connection was successfull";
}
?>


In this example a connection to the MySql database is attempted if the connection is ok the page will display "Connection was successfull" otherwise it displays the error.The returned value by the function is stored in a variable dollarsignrconnection this variable is tested in the if statement.If dollarsignrconnection variable is false i.e connection fails, the negation operator ! invert it to true and the error is echoed.
Date Published: Dec 19, 2010 - 8:50 am


PHP inlude() Function


If some lines of code are to be included in every page of the website, The PHP include() funciotn works perfect.If you have been working in ASP.Net or in Dreamweaver than you must be familiar with the role of masterpages and frames in ASP.net and Dreamweaver respectively.Suppose if the look and feel of the website has to be kept similar than we can include the navigation and header files on every page using PHP include() function.

Consider these three files beneath.


Header.html







Navigation.html


Footer.html




All these three files above can be combined to form a single file with the help of PHP include() function.


Combined.php

include("header.html");
include("navigation.html");
include("footer.html");
?>


The purpose of PHP include() as explained in this example is not the only benefit of PHP include() function, large PHP scripts can be split up into many small PHP files than all these files may be included in a single file.This way the project is easy to understand and reusable.

Date Published: Dec 12, 2010 - 9:29 am


How to get the name of PHP script


To extract the name of the currently executed script from the URL, The PHP superglobal array dollarsignr_SERVER can be used.The example below describes the procedure.

dollarsignrcurrentscript = dollarsignr_SERVER["PHP_SELF"];
echo dollarsignrcurrentscript;
?>


The PHP code above will show the name of only the PHP script currently executed.Sometimes it is necessary only to get the name of the PHP script instead of complete URL.
Date Published: Dec 12, 2010 - 8:22 am


How to get IP address of visitor in PHP


Getting the IP address of the visitor is the simplest task in PHP.Look at the following example:

dollarsignruserIP = dollarsignr_SERVER["REMOTE_ADDR"];
echo dollarsignruserIP;
?>


This should print something like following if you are working in wamp server or any local environment.

127.0.0.1
All the magic is done by the PHP superglobal dollarsignr_SERVER.The REMOTE_ADDR is just another element of dollarsignr_SERVER superglobal whcich retrieves the IP of the user computer.Note that this IP sometimes may be the IP of the LAN, the user is connected with.
Date Published: Dec 12, 2010 - 8:08 am


PHP Cookies


A cookie is used to identify a user.Some information about the website's user are stored at the user's computer so whenever the same user sends the request through a browser software, the stored cookie can be utilized to identify that user.
Like every good web programming language, PHP also provides a very useful and easy mechanism to accomplish the concept of cookies.The setcookie() function will create a cookie in client computer, it is must that the setcookie() function should be called before the HTML beginning code.

The PHP setcookie Function
Have a look at the syntax of PHP setcookie() function below:


setcookie(dollarsignrkey,dollarsignrvalue,dollarsignrexpire);

where dollarsignrkey is the name of the cookie, dollarsignrvalue is it's value and dollarsignrexpire is the time the cookie should remain alive on the user's computer.

setcookie("name","zaibi",time()+3600);
?>


echo "Welcome ".dollarsignr_COOKIE["name"];
?>

Shown above is the complete example of how to set and retrieve a cookie in PHP.The setcookie function creates the cookie after the creation of a cookie it can be retrieved in any of the page of the website with array variable dollarsignr_COOKIE.Another optional parameter of the PHP setcookie() function is time()+3600 which is making the cookie to remain alive till the current time plus 3600 seconds.To kill a cookie the time of past can be used like time()-1 etc.
Date Published: Dec 11, 2010 - 7:43 am


PHP For Loop


In every programming languages loops are applied where the repeated execution of a particular code is required until condition to be tested remains true. PHP For loop is identical to the for loop in C.

for (expression1;expression2;expression3)
{
      //code to be executed
}


The basic syntax of a PHP for loop is shown above.Let's discuss it in detail...
Expression1 is executed unconditionally only once when the loop starts, normally we initialize a variable in expression1.
Expression2 generally contains a condition based on its true or false, the loop decides whether to continue or stop.Expression2 is evaluated on the beginning of each iteration.The PHP for loop becomes indefinite if the expression2 is empty.
Expression3 is executed at the end of each iteration.

Example:

for (dollarsignri=1 ; dollarsignri<=10 ; dollarsignri++)
{
echo "i is equal to ".dollarsignri."
";

}
Look at the code above,in expression1 the variable is initialized,in expression2
This will display some thing like...
i is equal to 1
i is equal to 2
i is equal to 3
i is equal to 4
i is equal to 5
i is equal to 6
i is equal to 7
i is equal to 8
i is equal to 9
i is equal to 10
Date Published: Nov 24, 2010 - 8:53 pm


PHP Switch


The PHP switch is another conditional statement which carries out multiple condition check and execute the appropriate task based on the condition testing.
The PHP switch statement is a decent replacement of PHP if-elseif-else structure.In switch case structure only exact values can be compared i.e greater than or less than comparison is not present.

Example:


switch (dollarsignrinput)
{
case 1:
echo "Your entered 1";
break;
case 2:
echo "You entered 2";
break;
case 3:
echo "You entered 3";
break;
default:
echo "Your value is not within the range";
}
?>


The code above is the basic syntax of a switch...case statement in PHP.The break;is used here to terminate the program when any condition is true.If no condition is true.If no condition is matched, the code in the default: code block is executed.
Date Published: Nov 24, 2010 - 1:57 pm


PHP if - else


Conditional statement is used where we have to take different decisions on different conditions.The PHP if-else conditional statement is very similar to the C.The PHP if-else conditional statement can be utilized in three ways.
  • Using Only if using only if statement performs a single task only if the condition is true and does nothing if the condition goes false.
  • Using if-else using if-else, if the condition is true the specified task is performed and if it is false the code in the else block will be executed.
  • Using if-elseif-elseThis is the complete form of PHP if-else conditional statement where different conditions are tested and the action is performed accordingly.



if (dollarsignrpercentage < 40)
{
echo "Sorry you didn't pass the course!!!";
}


In the above shown example only a single if statement is used.If the condition is true i.e dollarsignrpercentage variable is less than 40 than the message is echoed else nothing happens.


if (dollarsignrpercentage < 40)
{
echo "Sorry you didn't pass the course!!!";
}
else
{
echo "Congrats!!! You have passed the course.";
}


Now the else block is also added in the code, in this case if the condition goes false the execution will jump into the else block


if (dollarsignrpercentage < 40)
{
echo "Sorry you didn't pass the course!!!";
}
elseif (dollarsignrpercentage < 60)
{
echo "Congrats!!! You have passed in C grade.";
}
elseif (dollarsignrpercentage <80)
{
echo "Congrats !!! You have passed in B grade.";
}
else
{
echo "Great!!! You have acheived the A grade.";
}


Multiple condition check is performed in this code.If the first condition is false than the second condition is checked and so on.Finally if no condition is true,the code in the else block is executed.
Date Published: Nov 23, 2010 - 2:07 pm


PHP Sessions


Session is a way of keeping the user information on the server to recognize a particular user.The session information is a temporary arrangement of keeping the user data on the webserver which only lasts until the browser is not closed.
Sessions are implemented in a way that whenever a session is started a unique id (UID) is assigned to the user,this ID is than stored in a cookie or embedded in the URL.After that the dollarsignr_SESSION array is used to hold different information based on that UID which was assigned to the user.

session_start();//start the session
?>


The session_start(); function starts a session by setting up a unique ID.This function must appears before the html tag.



session_Start();
dollarsignr_SESSION['name']="zaibi shah";
dollarsignr_SESSION['customer_id']=1;
?>


In the code above we have saved user information in two variables exist in the dollarsignr_SESSION array.These two variables are saved on the server against the UID which was created by the session_start() function.



session_start();
echo "Your name is ".dollarsignr_SESSION['name'];
echo "your ID is ".dollarsignr_SESSION['customer_id'];
?>


The session information can later be retrieved with the help of the code shown above, this information will remain available for us until we don't close the browser.
Date Published: Nov 23, 2010 - 5:13 am


PHP $_POST


The PHP dollarsignr_Post function is another way of grabbing the user inputted information.When a HTML form is used with its method="post" than the data of different elements of this form can be retreived by the PHP dollarsignr_post function in the PHP page which is called on submission of the form.
The dollarsignr_Post function gets the data with reference to the name attribute of the form elements e.g Textbox,Checkbox and Radio buttons.Unlike the dollarsignr_GET function the PHP dollarsignr_POST function makes the information transfer secure.The data is not visible to the user and it is not embedded in the URL and the amount of data to be shifted is almost unlimited too.
For more clear illustration let's go through to the following example...add the following code in a html file...






PHP dollarsignr_POST demo


Who are you?


method="post" action="form1script.php">

Name: type="text" name="_name" size=10>


Nick: type="text" name="_nick" size=10>


type="submit" value="Enter">





Now we have created our form and on submission this form will transfer its _name and _nick element's data to the form1script.php file.So we have to create a php file named form1script.php to do so,open notepad and type the following code and save it as form1script.php in the same directory in which your form html file exists.

<</span>?php
dollarsignrname = dollarsignr_POST["_name"];
dollarsignrnick = dollarsignr_POST["_nick"];
echo "your name is ".dollarsignrname ."and your nick is ".dollarsignrnick;
?>
When the form sends information to the PHP page with its post method, the information becomes available to the dollarsignr_POST function of PHP.which can be used for any purpose, here we are just echoing out this info.
Date Published: Oct 20, 2010 - 2:08 am


 
Visitor Rating: 5 (1) (Rate)

Story Clicks: 4

Feed Views: 59

Lenses (Add|?)

Comments (Log in to add)

Feed Details
Date Added: 12/30/2010
Date Approved: 12/30/2010
By:
Search FeedAgg.com




3600 mp7766 serv 1.0567 seconds to generate.