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

Wednesday, September 23, 2009

"Header already sent" error and other use of Header function in PHP


Using the Header() function you can do the following things


1) Redirect your user to some other page.

2) Tell the browser not to cache your files

3) Content Disposition.


"Header already sent" error


Most of the PHP learner (including me) has spent hours in debugging this problem. This problem happens while using session variables. While using session variables you must initialize the session using the function session_start(), and the problem occurs here.

This problem has got an unbelievably simple solution, just start the PHP block (where you have written the session_start() at the very first line of the page.


To illustrate this

<?php
session_start();
?>

is OK. But

<HTML>
<?php
session_start();
?>

is wrong.

Again , you can not even leave a blank line above the PHP code as it is considered as HTML code


<?php
session_start();
?>
As you can see there is a blank line above the PHP block , this will raise error.


Another example ,

<?php
echo 'Hello';
session_start();
?>

will give error as the statement "echo 'Hello' output an HTML on the page before "session_start();" is executed .


So , the bottom line is do not output anything before the session_start() is executed.

1) Redirect your user to some other page.

You can redirect you user to some other page using the code "Location" parameter of header() function.


<?php
header ( "Location: http://www.koderguru.com/" ); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?>

This code will redirect your user to the page http://www.example.com.

Warning : The statement
"header ( "Location: http://www.example.com/" );"

does not generate 302 response, that mean the page will be redirected but it will not be counted as a hit to "www.koderguru.com", so the target page looses a hit count. To avoid this use the following code.

<?php
header ('HTTP/1.1 301 Moved Permanently');
header ('Location: http://www.koderguru.com');
?>

This code generates a 301 status and hit count of "www.koderguru.com" will increase.

Also , you can redirect after some interval , using the code


// Redirects the browser after $sec seconds
header("Refresh: $sec; http://www.koderguru.com" );
should be:
header("Refresh: $sec; url= http://www.koderguru.com" );


2) Force the browser not to cache the pages.

You can do this with the code

<?php
// Date in the past , tels your browser the cache has already expired
header ( "Expires: Wed, 06 Jul 2006 05:00:00 GMT" );
// Here the line tells the browser that the last modification date of this page is right now
//So it must reload the page
header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
// HTTP/1.1
header ( "Cache-Control: no-store, no-cache, must-revalidate" ); // do not cache/store this page
header ( "Cache-Control: post-check=0, pre-check=0" , false );
// HTTP/1.0
header ( "Pragma: no-cache" );
?>


3) Content Disposition.
You can also generate different type of content other than html , using Header() function

<?php
// We'll be outputting a PDF
header ( 'Content-type: application/pdf' );
// It will be called downloaded.pdf
header ( 'Content-Disposition: attachment; filename="downloaded.pdf"' );
// The PDF source is in original.pdf
readfile ( 'original.pdf' );
?>


The above code tells the browser the type of document is PDF.


So , that's all for now. I hope you find this tutorial useful. Thank You.

Hide .php extension with url rewriting using .htaccess

Using this technique you will see product.html in the address bar of the browser but the actual file name remains product.php and you don’t need to rename the file extension. Furthermore you can rewrite the URL like product.php?id=5 to product-5.html.

what is the benefits of rewriting URL?

When a search engine visits the dynamic url like product.php?id=5 it does not give much importance to that URL as search engine sees “?” sign treat it as a url which keeps on changing. so we’re converting the dynamic URL like the product.php?id=5 to static url format like product-5.html. We’ll rewrite the url in such a way that in browser’s address bar it will display as a product-5.html but it actually calls the file product.php?id=5. So that why these kind of URL also named as SEO friendly URL.

what is required for URL rewriting ??

To rewrite the URL you must have the mod_rewrite module must be loaded in apache server. And furthermore, FollowSymLinks options also need to be enabled otherwise you may encounter 500 Internal Sever Error. If you don’t know much about mod_rewrite module then please check this post to know how to check and enable mod_rewrite module in apache?
Examples of url rewriting for seo friendly URL

For rewriting the URL, you should create a .htaccess file in the root folder of your web directory. And have to put the following codes as your requirement.

1)Rewriting product.php?id=12 to product-12.html

It is a simple redirection in which .php extension is hidden from the browser’s address bar and dynamic url (containing “?” character) is converted into a static URL.

RewriteEngine on
RewriteRule ^product-([0-9]+)\.html$ product.php?id=$1

2) Rewriting product.php?id=12 to product/ipod-nano/12.html

SEO expert always suggest to display the main keyword in the URL. In the following URL rewriting technique you can display the name of the product in URL.

RewriteEngine on
RewriteRule ^product/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ product.php?id=$2

3) Redirecting non www URL to www URL

If you type yahoo.com in browser it will be redirected to www.yahoo.com. If you want to do same with your website then put the following code to .htaccess file. What is benefit of this kind of redirection?? Please check the post about SEO friendly redirect (301) redirect in php and .htaccess.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^optimaxwebsolutions\.com$
RewriteRule (.*) http://www.optimaxwebsolutions.com/$1 [R=301,L]

4) Rewriting yoursite.com/user.php?username=xyz to yoursite.com/xyz

Have you checked zorpia.com.If you type http://zorpia.com/roshanbh233 in browser you can see my profile over there. If you want to do the same kind of redirection i.e http://yoursite.com/xyz to http://yoursite.com/user.php?username=xyz then you can add the following code to the .htaccess file.

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1

5) Redirecting the domain to a new subfolder of inside public_html.

Suppose the you’ve redeveloped your site and all the new development reside inside the “new” folder of inside root folder.Then the new development of the website can be accessed like “test.com/new”. Now moving these files to the root folder can be a hectic process so you can create the following code inside the .htaccess file and place it under the root folder of the website. In result, www.test.com point out to the files inside “new” folder.

Saturday, August 15, 2009

A simple code to handle Time



$time="08:05:00"; //for sake of example .initial time
$curtime="01:05:00";//end time

$t=explode(':',$time);
$h=intval($t[0]);
$m=intval($t[1]);

$add=1;

while($ntime!=$curtime)
{
$h=intval($h);
$m=intval($m);
$m+=$add;

if($m>=60)
{
$h++;
$m=$m-60;
}
if($h>23)
$h=0;

if($h<10)
{
$h="0".$h;
}
if($m<10)
{
$m="0".$m;
}

$ntime=$h.":".$m.":00";
echo $ntime."
"; //it will echo each minute
}

Sunday, July 19, 2009

How To Use PHP to Interact with MySQL

1. Introduction. This article will discuss how to connect PHP and MySQL, to create a dynamic database-driven website. I will assume that you already have a PHP and MySQL copy installed on your system and they all work. I will also assume that you have basic knowledge about PHP including PHP syntax and how to run a PHP script.

2. PHP and MySQL. PHP already includes a MySQL module in its distribution, so you won't need to install an additional software module.

3. Create MySQL user.

To create a username and password for your script execute the MySQL console application. You must login as root, then execute this SQL statement:

CREATE DATABASE db_test;
USE db_test;
CREATE TABLE tbl_phonebook
(
phone_id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
phone_name VARCHAR(40),
phone_number VARCHAR(40),
INDEX phone_name_idx (phone_name),
INDEX phone_number_idx (phone_number)
);
GRANT SELECT,UPDATE,DELETE,INSERT TO db_test.*
TO 'test_user' IDENTIFIED BY 'test_user';

After you execute those SQL commands, MySQL will create a database called db_test which contains one table called tbl_phonebook. We will use this table for our sample web application.

4. Connecting to MySQL database.

To establish connection to a MySQL database, you need to call mysql_connect() or mysql_pconnect(). Basically they're all similar except the second one will create a persistent connection. A persistent connection is a connection that persists even if connection is closed.

$link=mysql_connect('localhost','test_user','test_user');
$persist_link=mysql_pconnect('localhost','test_user','test_user');
?>

mysql_pconnect() is faster than mysql_connect() because it eliminates overhead to establish a connection to the MySQL database. If mysql_pconnect() finds that a persistent connection is already available for a user, it will use it, otherwise it creates new connection.

Upon connection completion, mysql_connect() and mysql_pconnect() returns a handle to connection.


5. Selecting a database to use. To select database to use, use must call mysql_select_db(). This function requires a database name and optional handle of database connection. If you omit the handle of connection, it will use the currently open connection.

$link=mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test',$link);
?>

Selecting a database is an optional step, which you can skip. However, if you do skip it, you must include the database name and table name to access a table. For example, to access tbl_phonebook you must provide the complete name db_test.tbl_phonebook instead of tbl_phonebook. Please note, you must use a period to separate the database name and table name.

6. Execute SQL statement. After you have a valid connection and have selected an active database, you are ready to execute the SQL statement to do some data manipulation. To execute the SQL statement, use mysql_query() function.

This function requires at least one parameter, which is the SQL command you want to execute. The second paramater is the connection you want to use. This parameter is optional. If you omit it, the currently open connection is used. If there is no open connection, this function will try to establish a new connection.

mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test');
$sql="SELECT * FROM tbl_phonebook";
mysql_query($sql);
?>

7. Inserting new data into the database. To insert a new record into the database, you must execute the INSERT statement. For example:

mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test');
$sql="INSERT INTO tbl_phonebook
(
phone_name,
phone_number
)
VALUES
(
'Johny Greenwood' ,
'+6281455632112'
) ";
mysql_query($sql);
?>

For the INSERT operation, to know whether the execution succeeded or failed, we use value return by mysql_query(). It returns boolean value, i.e, TRUE if it succeeded or FALSE if it failed.

To know how what records were affected by the execution of this SQL command, we call mysql_affected_rows(). This function needs one optional connection parameter. If it is omitted then the curently open connection will be used. This function returns the number of rows affected.

mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test');
$sql="INSERT INTO tbl_phonebook
(
phone_name,
phone_number
)
VALUES
(
'Johny Greenwood' ,
'+6281455632112'
) ";
mysql_query($sql);
print('Number of rows affected : '.mysql_affected_rows());
?>

8. Retrieving data from a database. To retrieve data from a database, we use SELECT command. This example was displayed previously. Here, we show it again.

mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test');
$sql="SELECT * FROM tbl_phonebook";
mysql_query($sql);
?>

The above piece of code did nothing useful. To make data available for viewing, we must fetch rows. If we use mysql_query() for the SELECT operation, it will return resources to rows by the SELECT statement. To fetch data from this resource we use mysql_fetch_row(), mysql_fetch_assoc(), mysql_fetch_array() or mysql_fetch_object. Everytime mysql_fetch_***() is called, the database cursor is increment to the next data. If these return NULL, the cursor is at the end of file (EOF), so there is no more data to return.

mysql_fetch_rows() will fetch data and return data as a numeric array. For example:

Use of mysql_fetch_rows():

mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test');
$sql="SELECT * FROM tbl_phonebook";
$res=mysql_query($sql);
if ($res)
{
while ($data=mysql_fetch_row($res))
{
print("

Name : ".$data[1]);
print("Phone : ".$data[2]."

");
}
mysql_free_result($res);
}
?>

Data from the phone_name field is returned in index number 1, because we selected all fields. So index 0 will contain data of phone_id field whereas phone_number field will be returned in index 2.

mysql_free_result() frees resources returned by mysql_query(). PHP automatically frees all resources when the script is finished, so calling mysql_free_result() is optional, but surely a good programming habit.

mysql_fetch_row() will fetch data and return data as an associative array. For example:

Use of mysql_fetch_assoc():

mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test');
$sql="SELECT * FROM tbl_phonebook";
$res=mysql_query($sql);
if ($res)
{
while ($data=mysql_fetch_assoc($res))
{
print("

Name : ".$data['phone_name']);
print("Phone : ".$data['phone_number']."

");
}
mysql_free_result($res);
}
?>

Note that the name of the field is used to index the array.

mysql_fetch_array() is a combination of mysql_fetch_row() and mysql_fecth_assoc(). It returns a numeric array as well as an associative array.

mysql_fetch_object() fetches rows and returns data as an object. For example:

mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test');
$sql="SELECT * FROM tbl_phonebook";
$res=mysql_query($sql);
if ($res)
{
while ($data=mysql_fetch_object($res))
{
print("

Name : ".$data->phone_name);
print("Phone : ".$data->phone_number."

");
}
mysql_free_result($res);
}
?>

To know how many rows have been returned by mysql_query(), you call mysql_num_rows(). It requires one parameter, i.e, resource returned by mysql_query().

$tot_record=mysql_num_rows($res);

9. Updating data. To update data you execute the UPDATE command.

mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test');
$sql="UPDATE tbl_phonebook SET phone_number='0135928549' WHERE phone_id=1";
$res=mysql_query($sql);
if ($res)
{
print('Update succeed');
} else
print('Update failed');
?>

Similar to INSERT, the UPDATE command doesn't generate a result set but only the boolean value; TRUE if it succeeds of FALSE otherwise. To find out how many rows are affecteded by the UPDATE command, use mysql_affected_rows().


10. Removing data. To remove a record you can use the DELETE command:

mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test');
$sql="DELETE FROM tbl_phonebook WHERE phone_id=1";
$res=mysql_query($sql);
if ($res)
{
print('Phone ID =1 deleted');
} else
print('Unable to delete');
?>


11. Closing connection. To close what we have opened, we call mysql_close(). It requires an optional parameter, i.e. a connection to close. If we wanto to close the currently open connection, omit the optional parameter.

$link=mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test',$link);
$sql="SELECT * FROM tbl_phonebook";
$res=mysql_query($sql,$link);
if ($res)
{
while ($data=mysql_fetch_object($res))
{
print("

Name : ".$data->phone_name);
print("Phone : ".$data->phone_number."

");
}
mysql_free_result($res);
}
mysql_close($link);
?>


12. Conclusion. We have discussed basic steps to let PHP interact with MySQL, including how to establish a database connection, how to select an active database, and how to execute an SQL command.

Install a Free Message Board PHP Script

Having your own website is a good way to get your message or opinions out and share them with other people. You can market your own products through your website or offer services. For whatever reason you want to have a website, it is always good to have a way for people to communicate their thoughts and opinions with you and to others who may find their way to your website. In the old days offices, institutions, clubs or schools would have a bulletin board or a message board for people to post anything they want to share with other people. But now as we use the computer and the Internet more often, message boards take on a new venue, one where the whole world can join in. People on the Internet can post topics and get a discussion online when people reply to the topics. To put up a message board on your website you can install a free message board PHP script.

1. Download a free message board PHP script. Find websites offering free message boards to download. You will find numerous sites with free download-able message boards, pick the one you prefer and download the files to your desktop. Once it is downloaded to your computer, open the folder containing the files and search for the read me file. It will contain the instructions you need to install the message board to your website. Follow the instructions to set up the settings, like the administrative password, the title and URL of your website in your text editor.

2. Upload the message board through FTP. You’ll to open your FTP program to upload the message board files on to your server. Create a folder and name it board in your server
’s directory. Publish or transfer the message board files to the board folder you created on your server.

3. Create a directory called msg. Once you have all the files on your server, create another folder called “msg” then right click the folder to change the folder’s file attribute giving it a 777 numeric value. Locate the threads.txt and count.txt, give it a 666 numeric value in the file attributes for each.

You can now text the message board on your website. You can customize the message board through the CSS file in the mboard.php file.

Downloading and installing a free message board PHP script on your website is the best way to have a simple and effective message board on your website, and as a bonus it won’t take up too much space on your server.

Learn PHP on 15 Minutes

Step 1:

To be able to execute PHP scripts, you need at least a working PHP installation+ web server. Linux, Apache, MySQL and PHP are the best combinations. PHP also can run under Microsoft Windows, too.

PHP installation and configuration can be made easy with tools such as Apache2Triad or XAMPP which automate web server and PHP installation.

PHP script is stored in text format file so you need text editor. Notepad and Notepad++ are enough for your PHP development needs. However, you may opt to invest in more advanced tools such Dreamweaver or Eclipse.
Step 2:

PHP script is anything between pair. You can also use . The first is most widely used.




print '

Hello this is my first script

';
?>



Output of the following code will be same as the previous code:

print '


Hello this is my first script

';
?>

Step 3:

The power of PHP lies on the capability to change how HTML code will output. The following code will output different HTML codes when you change the name.




$aname=$_GET['name'];
print '

Hello '.$name.' this is my first script

'; ?>




Save this script as welcome.php in the document root directory (for Apache web server, this is usually htdocs directory). Open your web browser and type http://localhost/welcome.php?name=Zamrony

Step 4:

$_GET is a predefined variable which stores lists of parameters passed to the script. It is an array. If you change http://localhost/welcome.php?name=zamrony&country=Indonesia, $_GET will contain more items.




$aname=$_GET['name'];
$acountry=$_GET['country'];
print '

Hello '.$name.' from '.$acountry.' .
this is my first PHP script

';
?>



It will print Hello Zamrony from Indonesia. This is my first PHP script.

Step 5:

$aname, $acountry and $_GET are all variables in PHP. Any variables in PHP should be prefixed with dollar sign. Variable names must only contain alphanumeric and underscore characters where the first character in variable names should be alphabet characters or underscores.

This is invalid variable name:

$123
$1aname
$*jskk

This is valid variable name:

$k123
$j
$_
$_test
$k123k
$KK


PHP is case sensitive. Variable $kk is not $KK.

How to Create a Basic Login Script in PHP

Interested in creating your own forum page, blog, or even a shopping cart? A login area is the first step. Here is how to create a script for it in PHP.

Steps:

1. Create the login database and table. For the purposes of the code examples below, we will assume the database name to be "test" and the table name to be "members". The database and table can be created through the control panel of your webhost. The "members" table will store the username and the passwords of all the people would be allowed access via this login script. The table should have a unique id field as the primary key, a username field, and a password field.


2. Create the login interface. This is an html page containing a form, two text boxes for the user name and password, and a submit button. As long as you have these elements, you may design the layout however you wish.

Example:


Member Login
Username:
Password:


3. Create the php script that will check the login input against the database. This script will connect to the database, send a query and retrieve the result, check to see if the username and password is correct and send you to the next page depending on the result of the comparison.

Example (connecting to the database):

$host="localhost"; // Host name
$username=""; // username
$password=""; // password
$db_name="test"; // Database name
$tbl_name="members"; // Table name

// Replace database connect functions depending on database you are using.
mysql_connect("$host", "$username", "$password");
mysql_select_db("$db_name");


Example (submitting query and retrieving results):

// username and password sent from form
//NEVER Remove the mysql_real_escape_string. Else there could be an Sql-Injection!
$myusername=mysql_real_escape_string($_POST['myusername']);
$mypassword=mysql_real_escape_string($_POST['mypassword']);

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);


Example (checking results):

// Replace counting function based on database you are using.
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row


Example (direct user based on result):

if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
header("location:login_success.php");
} else {
echo "Wrong Username or Password";
}

4. Create the page that will display after login success. This script will start your session and display an html message of your choosing.

Example:

// Check if session is not registered , redirect back to main page.
session_start();

if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>



Login Successful



5. Create logout script. This step is optional as sessions can time out. If you wish to create one, you will need a button or link to initiate the script and a message to confirm the success of logging out.

Example:

session_start();
session_destroy();
?>


Tips

* Replace the database functions in your script with the appropriate functions for the database you are using (e.g. SQLITE, Microsoft SQL, etc.)

* Depending on your requirements, add security checks to your script.

* Try using CSS and various HTML elements to create an interesting look for your login and message pages.