Wednesday, December 19, 2007

PHP - File Upload

When the uploader.php file is executed, the uploaded file exists in a temporary storage area on the server. If the file is not moved to a different location it will be destroyed! To save our precious file we are going to need to make use of the $_FILES associative array.

The $_FILES array is where PHP stores all the information about files. There are two elements of this array that we will need to understand for this example.

  • uploadedfile - uploadedfile is the reference we assigned in our HTML form. We will need this to tell the $_FILES array which file we want to play around with.
  • $_FILES['uploadedfile']['name'] - name contains the original path of the user uploaded file.
  • $_FILES['uploadedfile']['tmp_name'] - tmp_name contains the path to the temporary file that resides on the server. The file should exist on the server in a temporary directory with a temporary name.

Now we can finally start to write a basic PHP upload manager script! Here is how we would get the temporary file name, choose a permanent name, and choose a place to store the file.

PHP Code:

// Where the file is going to be placed
$target_path = "uploads/";

/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

NOTE: You will need to create a new directory in the directory where uploader.php resides, called "uploads", as we are going to be saving files there.

We now have all we need to successfully save our file to the server. $target_path contains the path where we want to save our file to.

Monday, November 19, 2007

E-mail With PHP


One of the major uses of a server side scripting language is to provide a way of sending e-mail from the server and, in particular, to take form input and output it to an e-mail address. In this part I will show you how to send e-mail messages using PHP.

The Mail Command

Mail is extremely easy to send from PHP, unlike using scripting languages which require special setup (like CGI). There is actually just one command, mail() for sending mail. It is used as follows:


In this example I have used variables as they have descriptive names but you could also just place text in the mail command. Firstly, $to. This variable (or section of the command) contains the e-mail address to which the mail will be sent. $subject is the section for the subject of the e-mail and $body is the actual text of the e-mail.

The section $headers is used for any additional e-mail headers you may want to add. The most common use of this is for the From field of an e-mai but you can also include other headers like cc and bcc.

Sending An E-mail

Before sending your mail, if you are using variables, you must, of course, set up the variable content beforehand. Here is some simple code for sending a message:

$to = "";
$subject = "PHP Is Great";
$body = "PHP is one of the best scripting languages around";
$headers = "From:\n";
echo "Mail sent to $to";

This code will acutally do two things. Firstly it will send a message to with the subject 'PHP Is Great' and the text:

PHP is one of the best scripting languages around

and the e-mail will be from It will also output the text:

Mail sent to

to the browser.

Formatting E-mail

Something you may have noticed from the example is that the From line ended with \n. This is acutally a very important character when sending e-mail. It is the new line character and tells PHP to take a new line in an e-mail. It is very important that this is put in after each header you add so that your e-mail will follow the international standards and will be delivered.

The \n code can also be used in the body section of the e-mail to put line breaks in but should not be used in the subject or the To field.

Mail Without Variables

The e-mail above could have been sent using different variable names (it is the position of the variables in relation to the commas, not the name of them which decides on their use). It could also have been done on one line using text like this:

mail("","PHP Is Great","PHP is one of the best scripting languages around","From:\n");

But that would make your code slightly harder to read.

Error Control

As anyone who has been scripting for a while will know, it is extremely easy to make mistakes in your code and it is also very easy to input an invalid e-mail address (especially if you are using your script for form to mail). Because of this, you can add in a small piece of code which will check if the e-mail is sent:

if(mail($to,$subject,$body,$headers)) {
echo "An e-mail was sent to $to with the subject: $subject";
} else {
echo "There was a problem sending the mail. Check your code and make sure that the e-mail address $to is valid";

Testing For PHP and MySQL install successfully or not......

There is a simple test for both PHP and MySQL. Open a text editor and type in the following:


and save it as phpinfo.php

and run in the browser...display the all information about php version, mysql version and other apache setting.

mainly the display file is information about php.ini file....

The Include Function in PHP5

The include function takes a file name and simply inserts that file's contents into the script that calls used the include function.

Well, first of all, this means that you can type up a common header or menu file that you want all your web pages to include. When you add a new page to your site, instead of having to update the links on several web pages, you can simply change the Menu file.


The include command simply takes all the text that exists in the specified file and copies
it into the file that uses the include function. Include is quite useful when you want
to include the same PHP, HTML, or text segment on multiple pages of a website. The include
function is used widely by PHP web developers.

Wednesday, November 14, 2007

Connecting to ODBC and PHP

# connect to a DSN "mydb" with a user and password "marin"
$connect = odbc_connect("mydb", "marin", "marin");

# query the users table for name and surname
$query = "SELECT name, surname FROM users";

# perform the query
$result = odbc_exec($connect, $query);

# fetch the data from the database
$name = odbc_result($result, 1);
$surname = odbc_result($result, 2);
print("$name $surname\n");

# close the connection

What is ODBC?

Open DataBase Connectivity is an Application Programming Interface (API) that allows a programmer to abstract a program from a database. When writing code to interact with a database, you have to add code that talks to a particular database using a proprietary API. If you want your program to talk to an Access, FoxPro and Oracle databases you have to code your program with three different database API's. This can be quite the daunting task causing much grief. Now, enter ODBC...

When programming to interact with ODBC you only need to use the ODBC API (a combination of ODBC extension function calls and the SQL language) to talk to different database products. The ODBC Manager will figure out how to contend with the type of database you are targeting. Regardless of the database type you are using, all of your calls will be to the ODBC API. All that you need to do is have installed an ODBC driver that is specific to the type of database you will be using.

PHP Database ODBC Connection

ODBC is an Application Programming Interface (API) that allows you to connect to a data source (e.g. an MS Access database).

Create an ODBC Connection

With an ODBC connection, you can connect to any database, on any computer in your network, as long as an ODBC connection is available.

Here is how to create an ODBC connection to a MS Access Database:

  1. Open the Administrative Tools icon in your Control Panel.
  2. Double-click on the Data Sources (ODBC) icon inside.
  3. Choose the System DSN tab.
  4. Click on Add in the System DSN tab.
  5. Select the Microsoft Access Driver. Click Finish.
  6. In the next screen, click Select to locate the database.
  7. Give the database a Data Source Name (DSN).
  8. Click OK.

Monday, October 29, 2007

Connecting to a mySQL database using PHP

SHOW available tables in mySQL database

Similar to opening a file to write to it, you have to open a connection to mySQL before you can do anything. The syntax of this function is as follows:

mysql_connect("localhost OR hostname:port", "httpd OR username", "" or "password");

$mysql_access = mysql_connect("localhost", "username", "password");

The function mysql_close is unnecessary unless you are setting a persistent connection. To set a persistent mySQL connection use:

mysql_pconnect("localhost", "username", "password");

You would want to use persistent connections where you would have a lot of simulataneous connections from the same user through the script.

The following script below will open your mySQL database connection and show the tables available to you in your mySQL database. You must always open a connection to the mySQL database before doing anything else (you only need to open it at the beginning of a script, and then you can run multiple queries if you want). This is good for testing your ability to successfully access the mySQL database.

$mysql_access = mysql_connect("localhost", $user, $pw);
mysql_select_db($db, $mysql_access);

$result = mysql_query("SHOW tables", $mysql_access);
while($row = mysql_fetch_row($result))

in above script

$user is a mysql username.

$pw is mysql password.

$db is mysql database name

Friday, October 26, 2007

php programme first php script

The Most Basic Computer Program
So how do I do it in PHP? Well the two simplest ways are using Print or Echo.

PHP5 and mysql and apache in one pack-WAMP Server installation on windows

PHP5 and mysql and apache in one pack-WAMP Server installation on windows

You can install Apache Server, MySQL, and PHP in one step using WAMP. WAMP is a freeware package that bundles Apache, MySQL, and PHP into one executable. You can download WAMP from the project homepage. Once you download WAMP, double click the icon and begin the install process.
Click Next to begin:After agreeing to the WAMP license, select the destination location. Leave the default location as "c:\wamp" and click Next:Leave the default Start Menu shortcut as "WampServer" and click Next:Select automatically launch WAMP5 on startup. This will allow Vista to act as a server whenever it is started. Select the check box and click Next:WAMP will summarize your selections. Click Install and WAMP will begin the install process:WAMP will extract and install itself. The process should only take a few seconds, and WAMP will prompt you to choose a folder for your "DocumentRoot." Leave the default folder as "www" and click Ok:WAMP will prompt you to enter the SMTP server to be used by PHP to send emails. Leave the default value as "localhost" and click Next:WAMP will then prompt you to enter the default email address to be used by PHP to send emails. Put your email address in this field and click Next:If you have Firefox installed, WAMP will ask you if you would like to use Firefox as the default browser with WAMP. This is a personal preference, so feel free to choose "Yes" or "No." I will choose "Yes" and then click Next:You will likely be prompted by Vista whether the Windows Firewall should allow or block the features of WAMP. You want to allow all of the features of WAMP, so click Unblock:Congratulations, the installation process is complete, click Finish and Launch WAMP5 now:Open a browser and enter "localhost" as the URL, and you will see a summary of the installation process:now go to browser… and type in the address bar…..


and press inter..default wamp server page is open……
now u go to c:/wamp/www/myfolder

myfolder is ur web folder where u put on ur .php pages.

And now run ur php page like this…

Go to Browser address bar

http://localhost/myfolder/ index.php

now happy and enjoy… read the other post from my blog and enjoy…and expert in the php script…..

php on IIS 6 intallation

PHP is a really cool server side scripting interface with loads of options and modules and is relatively easier than ASP (the only other server side scripting language I've used). IIS 6 is also a cool web server with loads of new options. So here is how you configure php on IIS:(I'm assuming IIS is already installed on your box)
1. Download php from this location2. Unzip the package to some location(c:\php or whatever)3. Copy the php.ini-recommended file to your %systemroot% directory(usually C:\Windows) or to the %PHPRC% location, if %PHPRC% variable is set.4. Rename the file as php.ini5. Edit the file to make your config. I usually do the following(only minimal stuff):a. Open short tags ("" should work for me, I'm too lazy)b. Edit my extension_dir to the right location("c:\php\ext\" or whatever)** DO NOT FORGET TO PUT THE TRAILING BACKSLASH.**c. Enable my php_ldap etc...d. other stuff...error handling, session mgmt etc etc....please read the docs. :-)6. Open your IIS snap-in (inetmgr in "Run")7. Create your website/virtual directory.8. Enable php on the entire website or your virtual directory:a. Go to the directory tab, click configuration, click Add.b. Put in ".php" (without the quotes) in the extension box.c. Point the Executable file to "php5isapi.dll" (in your php directory)d. Give your verbs(usually GET,HEAD,POST,TRACE would do)e. Ensure "Check that file exists" is checked. (saves time and resources)9. Only for IIS 6:a. Click on "Web Service Extensions".b. Click "Add new web service extension"c. Give some name and add the php5isapi.dll file and select allow.10. Add the php directory to your path(sysdm.cpl in "Run",Environment Variables under the Advanced tab, under "System Variables", edit the Path variable and append the path to your php directory to it(like C:\php where C:\php is the location of your php source).11. Restart IIS and enjoy.
Update(thanks to 'anonymous' :-): One important point I forgot to mention - You need to give the user IIS is running as (usually IUSR_MACHINENAME) permissions on your php directory and files, other wise you will end up with 403 or 404 errors.
I've seen on a lot of posts where people mention that they need to copy some files to system32 directory, and I do not think that its required. Here is a filemon snapshot of the location my IIS is finding the extensions:

Each time you make any changes to the php.ini file, you need to restart your webserver.
UPDATE: If you get a prompt for username and password in Firefox even though you enabled just anonymous access, you need to enable the following:a. In your Firefox window,type in 'about:config' without the quotesb. You will find a text box called Filter, type in 'auth' without the quotesc. You'll find an entry called network-automatic-ntlm-auth.trusted-urisd. Double-click on it. It will open a small input window.e. Enter the name of the website (usually if you're having issues with http://localhost), enter localhost and click OK. (You can enter multiple sites by separating them with commas)

how to start php coding and setup and installation,

Install an Apache server on a Windows or Linux machine
Install PHP on a Windows or Linux machine
Install MySQL on a Windows or Linux machine


Why PHP?

PHP runs on different platforms (Windows, Linux, Unix, etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP is FREE to download from the official PHP resource:
PHP is easy to learn and runs efficiently on the server side

PHP scripting----------

PHP is now officially known as “PHP: HyperText Preprocessor”. It is a server-side scripting language usually written in an HTML context. Unlike an ordinary HTML page, a PHP script is not sent directly to a client by the server; instead, it is parsed by the PHP binary or module, which is server-side installed. HTML elements in the script are left alone, but PHP code is interpreted and executed. PHP code in a script can query databases, create images, read and write files, talk to remote servers - the possibilities are endless. The output from PHP code is combined with the HTML in the script and the result sent to the user?s web-browser, therefore it can never tell the user whether the web-server uses PHP or not, because all the browser sees is HTML.
PHP’s support for Apache and MySQL further increases its popularity. Apache is now the most-used web-server in the world, and PHP can be compiled as an Apache module. MySQL is a powerful free SQL database, and PHP provides a comprehensive set of functions for working with it. The combination of Apache, MySQL and PHP is all but unbeatable.
That doesn?t mean that PHP cannot work in other environments or with other tools. In fact, PHP supports an extensive list of databases and web-servers. The rise in popularity of PHP has coincided with a change of approach in web-publishing. While in the mid-1990s it was ok to build sites, even relatively large sites, with hundreds of individual hard-coded HTML pages, today?s webmasters are making the most of the power of databases to manage their content more effectively and to personalize their sites according to individual user preferences.

Reasons for using PHP

There are some indisputable great reasons to work with PHP. As an open source product, PHP is well supported by a talented production team and a committed user community. Furthermore, PHP can be run on all the major operating systems with most servers.
The speed of development is also important. Because PHP allows you to separate HTML code from scripted elements, you will notice a significant decrease in development time on many projects. In many instances, you will be able to separate the coding stage of a project from the design and build stages. Not only can this make life easier for you as a programmer, but it also can remove obstacles that stand in the way of effective and flexible design.
Well-maintained open source projects offer users additional benefits. You benefit from an accessible and committed community who offer a wealth of experience in the subject, as fast and as cheap as possible. Chances are that any problem you encounter in your coding can be answered swiftly and easily with a little research. If that fails, a question sent to a mailing list or forum can have an intelligent, authoritative response. You also can be sure that bugs will be addressed as they are found, and that new features will be made available as the need is defined. You will not have to wait for the next commercial release before taking advantage of improvements, and there is no hidden interest in a particular server product or operating system. You are free to make choices that suit your needs or those of your clients and incorporate whatever components you want.

Why MySQL?

Choosing a database system depends on three main factors; the platform on which you work, your finances and what you want to achieve. The reason I chose MySQL is because, I work mostly on the Linux system and MySQL is free for Linux. Also, I am an ardent supporter of Open Source Software movement and firmly believe that the combination of Linux, Apache, MySQL and PHP (LAMP) is hard to beat.

What is MySQL?

MySQL is a simple, yet powerful Open Source Software relational database management system that uses SQL.

MYSQL(pronounced "My ess cue el") is an open source Relational Database Management System that uses Structured Query Language. Information is stored in "Tables" which can be thought of as the equivalent of Excel spreadsheets. A single MySQL database can contain many tables at once and store thousands of individual records. It's fast, reliable and flexible.

What Is PHP?

PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML.

The endless possibilities of the PHP scripting language and a great community of users has made it one of the most popular open-source languages. For all you people living outside the UNIX world, Open Source means it doesn?t cost anything. You can use it as much as you want and where you want, and nobody will ever charge you thousands of dollars for licenses and support. Even though it was originally conceived as a set of macros to help coders maintain personal home pages, its name grew a lot more from its purpose. Since then, PHP?s capabilities have been extended, taking it beyond a set of utilities to a full-featured programming language, capable of managing huge database-driven online environments.

PHP stands for PHP: Hypertext Preprocessor
PHP is a server-side scripting language, like ASP
PHP scripts are executed on the server
PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
PHP is an open source software (OSS)
PHP is free to download and use

A PHP file may contain text, HTML tags and scripts. Scripts in a PHP file are executed on the server.

That's a mouthful, but if we break the definition down into smaller pieces, it is easier to understand.
server-side: This means that PHP scripts execute on the Web server, not within the browser on your local machine.
cross-platform: Cross-platform means that PHP scripts can run on many different operating systems and Web servers. PHP is available for the two most popular Web server configurations (IIS running on Windows NT and Apache running on UNIX).
HTML embedded scripting language: This means that PHP statements and commands are actually embedded in your HTML documents. When the Web server sees the PHP statements in the Web page, the server executes the statements and sends the resulting output along with the rest of the HTML. PHP commands are parsed by the server much like Active Server Pages or Cold Fusion tags.