PHP scripts and programs for Beginner to Master

php programs, php ready to use scripts & functions, css tutorials, html, javascripts, ajax examples for Beginner to Master

Now you have learnt to set a cookie in php. Now the next thing is to retrieve the value stored in cookie.

With the following code you can retrieve the value stored in cookie.
To get the value stored in cookie we are using global variable $_COOKIE.

Here we are getting the value stored in cookie to the variable $mycookie.


Here is full code to check & print the value of the cookie.

Hi,

Are you getting this kind of error when creating a cookie or setting a cookie -

Warning: Cannot modify header information - headers already sent by (output started at e:\wamp\www\mysite\test.php:3) in e:\wamp\www\mysite\test.php on line 4

This error comes when some data is sent to the browser before setting the cookie.
So setcookie or setrawcookie function should be the first to be called means,

setcookie or setrawcookie function should be the first line on your page.


So if you use code like this








so the above code will give error.

So you should do following thing.





You might be searching for how to set a raw cookie in php. So here is a simple example which shows how to set a raw cookie.

To set a cookie use the function "setrawcookie"

setrawcookie() is exactly the same as setcookie() except that the cookie value will not be automatically urlencoded when sent to the browser.

This function accepts different number of arguments or parameters as setcookie. You can see the php reference manual of setcookie function here for more details.

In the following example we are passing 3 parameters
1) cookie name - its the name by which cookie will be identified.
2) cookie value - its the value stored in cookie.
3) expiration time - the time till the cookie will be available, after that it will be destroyed.



You can set the cookie by using above function.
more details can be found here.

You might be searching for how to set a cookie in php. So here is a simple example which shows how to set a cookie.

To set a cookie use the function "setcookie"

Note that the value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name.

This function accepts different number of arguments or parameters. You can see the php reference manual of setcookie function here for more details.

In the following example we are passing 3 parameters
1) cookie name - its the name by which cookie will be identified.
2) cookie value - its the value stored in cookie.
3) expiration time - the time till the cookie will be available, after that it will be destroyed.



You can set the cookie by using above function.
more details can be found here for more details.

Hi,

You might require this code which lists all files from a specific directory in php. It shows the files from a folder you want.
Even you can specify which files to ignore eg. when showing image you dont want to show thumbs.db file, so you can specify in the code neglect thumbs.db file.
So your code will show all files except thumbs.db 

This is a very basic program, you can extend it to a level you want as per your requirement. If you need some help ask me, if possible definitely i will help.


In the below code there is one array $exclude, in this array you specify the files which you want to ignore in your final output, so it will not be shown. And just modify the if loop.





If you know any other way to do the same then comments are always welcome.
Dont forget to tell your friends about http://programming-in-php.blogspot.com

Hi,

Do you want your visitors to go to a particular page when they select any option from the dropdown list or from select box ?
Then here is the select element which will redirect users to the particular url when the select any option from it.










Now whenever a user selects any option from the dropdown at that time we are calling our javascript function gotourl which will process the current request and redirects users to that particular page.

Here is our Javascript function gotourl to do processing









Here is full code







If you know any other way to do the same then comments are always welcome.
Dont forget to tell your friends about http://programming-in-php.blogspot.com

How can we know the number of days between two given dates using MySQL ? or find the difference between dates using MySQL ?

Do you ever faced this question in technical interview or technical test?

I know many of you have faced this....... :)

Here is a simple function which can be used to find the number of days between two given dates in MySQL.

Syntax - DATEDIFF(firstdate,seconddate)

so internally it will calculate the difference in MySQL by doing "firstdate minus seconddate", so if firstdate is greater than sencoddate then output will be positive and if firstdate is less than seconddate then output will be negative.

eg. if you use this function as

SELECT DATEDIFF('2009-11-19', '2009-10-15');

in MySQL
then you will get output as 35.

And if you pass parameters as

SELECT DATEDIFF('2009-10-15','2009-11-19')

then you will get output as -35.


If you know any other way to find the difference between dates then comments are always welcome.
Dont forget to tell your friends about http://programming-in-php.blogspot.com

Many times when you go for an interview or technical test you may find this question 

"What is the difference between the sort() and asort() function in php ?"

Basically sort() and asort() functions are used to sort the array in php.

* sort() function syntax - sort(array,sorttype)


sorttype is Optional. Specifies how to sort the array values.

* SORT_REGULAR - Default. Treat values as they are (dont change types)
* SORT_NUMERIC - Treat values numerically
* SORT_STRING - Treat values as strings
* SORT_LOCALE_STRING - Treat values as strings, based on local settings



This function assigns new keys for the elements in the array. Existing keys will be deleted.

eg. See the code below when we create array $myarray we have assigned keys as a b & c.
Now we are applying sort function and printing the array.





so the output of the above code will be -
initial array contents -

Array ( [a] => chaprak [b] => programming [c] => dexter )

and after applying sort function -

Array ( [0] => chaprak [1] => dexter [2] => programming )

its keys are changed to numeric values and sorting is done.

View php manual for the array sort function


* asort() function syntax - asort(array,sorttype)

The asort() function sorts an array by the values. The values keep their original keys (index).


sorttype is Optional. Specifies how to sort the array values.

* SORT_REGULAR - Default. Treat values as they are (don't change types)
* SORT_NUMERIC - Treat values numerically
* SORT_STRING - Treat values as strings
* SORT_LOCALE_STRING - Treat values as strings, based on local settings






when we execute above code then it will produce the following output

initially array contents are - Array ( [a] => chaprak [b] => programming [c] => dexter )

after applying asort() function the contents are -

Array ( [a] => chaprak [c] => dexter [b] => programming )


see here sorting is done and even index is maintained.

View php manual for the array sort function

Whenever it is required to get some input url from user then the first things comes is check whether that url is working and valid or it is not working.

Here is a simple function which can be used to verify the liveness of the url.
Just pass the url to this function and it will tell you whether the url is working and valid or invalid.

In the function "check_url" we are going to open the given url with "fopen".
If its opened then return true else return false.



Now we are going to use this function.
you can pass the url from the GET or POST method to the function.
Here we are going to specify it directly in the code.
So we are asking our code to open the url http://www.chaprak.com with our function.



so after execution it will show the message as

http://www.chaprak.com is a valid URL.

See its very simple to check the validity of the url in php.

Full source code to try is here -




If you have any ideas and suggestions to improve this function then comments are always welcome.
Dont forget to tell your friends about http://programming-in-php.blogspot.com

Here is a simple function which can be used to count the total number of words present in a string in php.

For this function we are going to use inbuilt functions in php like count, explode, trim.

Function is very simple, it accepts the text.
Then we are checking if there are any extra spaces before and after the string, if it is there then removing that with trim function.

Then we are using count and explode function.

Explode will divide the text into array. (for more information on how explode works visit our post Split string with php explode function and print array)

Then we are counting the total number of array elements by using count function.



Now we are actually going to use this function.



Here is a full source code to try it out.



If you have any ideas and suggestions to improve this function then comments are always welcome.

Have you ever came across a situation where you need to truncate the large text and show the "read more.." link to redirect user to read the full post ?
I know you might be searching for a function to show read more link in php.

Here is our simple function which can be used to show the "Read more.." links dynamically.



The above function can be used anywhere to show read more links with dynamic mysql queries.

How to use this function ???
Here is a simple example to do this
First you will need to create the connection with the database.
Connection settings are stored in "connect.php" file




This will output your article text with proper linking to original post with read more link.

Even you can customize the truncate function for more security check and customizing your display.

Share with friends if you liked it.

So you installed WampServer on Windows.

Now how to create and execute or run you php file on windows ???

First START WampServer by clicking your START MENU and then selecting WampServer and then click start WampServer.

Once Server is started then you will see a WampServer icon in the right corner of your taskbar where your clock is present.

Now open the drive where you installed your wampserver.(ex. C:/wamp/)
Then open the www folder. (ex. C:/wamp/www/)
This is your Base directory, your all projects will come here.

Now create a directory here named mytest.
Now open notepad or any other text editor you have. Type the following in it.





Save the file to the directory mytest as index.php


Now click on the icon present in the right hand side of your taskbar and then click on localhost
Now you will see the list of projects, then click on mytest, you can see that your program is executed.
It will show you all the details of the php version you have installed.

Many of us use windows operating system and want to know how to use php on Windows operating system ?

For this there is a very simple and useful solution. Even you don't have to setup & configure many things.

Following things are required for using php on windows


  • Apache Server
  • Mysql
  • PHP
WampServer is a Windows web development environment. With this we can create web applications with Apache, PHP and the MySQL database. Even PHPMyAdmin is provided to manage your databases.

Just Download WampServer and install it and you are done. WampServer is an open source project, free to use.

Hi Friends, programming-in-php.blogspot.com is a place to share experience and knowledge.

You can Help us to spread the word either by forwarding this URL or putting this on your blog or website.
Even I am thinking of putting a section which will list the useful resources for programming, so if you have a blog or website which is related to php, php codes, php scripts, ajax, css, html,open source or if its technical blog then please contact me by writing a comment here about your blog, i will definitely like to add your link here on my blog.
Because to share our knowledge it has to be accessible to other many people. So lets help each other to share knowledge.


We all can have a section on our blog or website to share some useful resources which also helps in link building & SEO(Search Engine Optimization) and promotion.

Your comments are always welcome about this idea, whether is good or bad.
I am waiting for your reply.

Thank you.

At many places we require the contact us or feedback form to get some input from the user or to get some feedback from the user.
Today i will be showing you how to create a very simple feedback form or contact us form in php with the mail function and without any database.

1) First we will be creating a simple form to accept the user input like name, email and their message or feedback or query.





















Name : "/>
Email : "/>
Message :
 





2) In the form tag we have not specified any action part and we kept action="" in the form tag, so when the form is submitted at that time it will call itself.
So on submit we will execute our code to send the mail.





3) some css for the form and good look.

.textbox,.textarea {
width:300px;
border:solid 2px #00CCFF;
padding:3px;
margin:10px;
}
.error {
background: #FBBFDC;
color:#EF013D;
border:solid 1px;
padding:5px;
margin:5px;
}


4) After the page is submitted we will process the form data.



5) When the form is filled then we will be calling a function sendmail.



Finally, merge all the code to create a simple contact us form or feedback form.
Full source code is here for your reference



.textbox,.textarea {
width:300px;
border:solid 2px #00CCFF;
padding:3px;
margin:10px;
}
.error {
background: #FBBFDC;
color:#EF013D;
border:solid 1px;
padding:5px;
margin:5px;
}




















Name : "/>
Email : "/>
Message :
 



if(isset($_POST["Submit"]))
{
$email = $_POST["email"];
$msg = $_POST["message"];
$username = $_POST["name"];
if($username!="" and $email!="" and $msg!="")
{
sendmail($username,$email,"",$msg,"");
}
else
{
echo "
Fill all the fields ! Thank you.
";
}
}
function sendmail($username,$email,$data,$msg,$footer)
{
$to="youremailidhere";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
//$headers .= "From: ".$from."\r\n";
$headers .= "From: $username <$email>\r\n";
$headers .= "Reply-To: youremailidhere\r\n";

$body="

Dear Admin,

";
$body.="

Message from : $username

";
$body.="

Email id : $email

";
$body.="

Message : $msg

";

$body.="Feedback end

";

if(@mail($to,'feedback from http://programming-in-php.blogspot.com',$body,$headers))
{
echo "Thank you for your valuable feedback !";
}
else
{
echo "
Can't send email ! ! !
";
}
}
?>

sometimes it is required to get the current working directory of the script.
so to get the current working directory in php this is a small function.

This code can be used to show some random quotes or random links every time the page is loaded or refreshed.




$quote = array(
1 => "Random Quote 1",
2 => "This is sample quote 2",
3 => "check http://programming-in-php.blogspot.com",
4 => "it really works",
5 => "wooooooooooooooooooooow",
6 => "I am on twitter"
);
$randnum = rand(1,6);
echo "
Random Quote - $quote[$randnum]
";
?>


If it is needed to Split string in php and then use those splitted values for some processing in that case you can use this script which Splits string with php explode function and prints array.


$string = "Contents of the string can be splitted by explode function.";
$splitted = explode(" ",$string);
$cnt = count($splitted);
$i=0;
while($cnt > $i)
{
echo "$splitted[$i]";
echo "\n";
$i++;
}
?>

Caution: While using Javascript and an alert message is fired using a timer, then keep the timer for atleast 10 seconds, i.e. 10000. Else, the system will hang. I experienced it recently.

Please note.

Run this program, and watch the color change accelerate.

This part is for Horizontal Menu using CSS.

The below one will come under the Head Tag.


The below one will come under Body Tag.



This code was taken from http://www.w3schools.com/css/tryit.asp?filename=trycss_float5

This is very simple and useful php script if you want to display some random quotes each time a page is visited or refreshed.


$quote = array(
1 => "Random Quote 1",
2 => "This is sample quote 2",
3 => "check http://programming-in-php.blogspot.com",
4 => "it really works",
5 => "wooooooooooooooooooooow",
6 => "I am on twitter"
);
$randnum = rand(1,6);
echo "
Random Quote - $quote[$randnum]
";
?>


This is a very basic version of the script.

Soon you can see the modified version of this script with database support to show random quotes from the database.

Sometimes it is required to show the contents of some text file to the web page. So we can change those contents easily without any problem.

First we will create a simple text file, with some contents.
name it as "test.txt"


These contents are saved in test.txt file.
I am showing you the contents of some text file.

Its very useful to show the contents of the text file in a browser.


Now we will create our php file which will show the contents of the test.txt file to the webpage.


$file1="test.txt";
if (file_exists($file1))
{
$file = fopen("test.txt", "r");
while (!feof($file))
{
$display = fgets($file, filesize("test.txt"));
echo $display . "
";
}
fclose($file);
}
else
{
echo "Error occured ! ! ! Try again or report it to us";
}
?>
?>


Now when we execute this script, it will show the contents of the test.txt to our page.
In this script we are checking whether file exists or not, it it doesnt exists then we will show the error message.

This is a small program which generates a factorial of a number in php.


function doFactorial ($x) {
if ($x <= 1)
return 1;
else
return ($x * doFactorial ($x-1));
}

while($i<100)
{
print $i." --> ".(doFactorial ($i)) . "
";
$i++;
}
?>



Its a very basic program which generates a factorial of small numbers.

sometimes it is required to restrict the length of the textarea so that user should not enter characters beyond a certain limit.
For this we can make use of this simple javascript.

First we will create a 2 textarea.












Here we have created 2 textboxes "mytextarea" and "mytextarea1".
and onkeyup event of the mytextarea we will call our javascript function "restrict(textareaname)", means whenever any key is pressed we will call our javascript function.
and onchange event of the mytextarea we will call our javascript function "restrict(textareaname)", means whenever we will move out of this textbox javascript function will be called.

Here is our javascript function


function restrict(mytextarea) {

var maxlength = 15; // specify the maximum length

if (mytextarea.value.length > maxlength)

mytextarea.value = mytextarea.value.substring(0,maxlength);

} // -->



Include this function either in the head section or at the end before body tag.

Here is full source code to try this


























Today we will be seeing a small easy function to generate a password of specified length.

For this we will be creating a function called "genpwd()"



Now this function is ready, now we want to display the generated password of our specified length.
For this we will print the function value, specifying the length of the password to be generated.



The full working sample example is here, you can copy and paste this code to try it out. It will generate a random string everytime you refresh the page.



function genpwd($cnt)
{
// characters to be included for randomization, here you can add or delete the characters


$pwd = str_shuffle('abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890@#%$*');


// here specify the 2nd parameter as start position, it can be anything, default 0
return substr($pwd,0,$cnt);
}

echo genpwd(10); // specify the length of the generated password



UPDATE : 12th September 2009 Hey thanks Filip. Here is one more function to generate a random password suggested by Filip in comments below.


function passwordGenerator($length = null)
{
$pass = md5(time());
if($length != null) {
$pass = substr($pass, 0, $length);
}
return $pass;
}
echo passwordGenerator(6);


UPDATE : 17th December 2009. Hey thanks Fredrik Karlström. Here is one more function to generate a random password suggested by Fredrik Karlström in comments below



function generate_password($len = 8) {
$chars = str_split('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#');
$pwd = '';

for($i=0; $i < $len; $i++)
$pwd .= $chars[rand(1, $sizeof($chars)) -1];
return $pwd;
}

Sometimes we require that when the users click on a textarea at that time all the text should get selected.
This can be done with a small javascript.







When a user clicks on a textarea then all the contents will get selected.

Hi guys,

Generally we require that all the contents of our website should be centered to display the website properly.
For this we can make use of this code so that your website will be in the center of the browser, doesnt matter what is the resolution.

We will create a div with id "outer-div" in the body tag of our webpage.




Now we will apply a CSS styling to the "outer-div" div.




The full code to test is here

Hello,
Today we will be seeing a javascript which will help us to show how many characters are remaining for a textbox or textarea,As soon as the user starts typing in a textbox or textarea, then we will show how many characters are remaining for entering into the textbox.

Here we are creating a simple textbox, and we are specifying the "maxlength" of the textbox to 20.





And "onKeyUp" event of the textbox we are calling a javascript function "countCharacters()".

we will be writing a standard function which accepts only some parameters and rest of the processing will be done in the function.

To this function we have to pass 3 parameters
1) id of the span - where counter will be shown when user types something
2) max_chars - length of the textarea which we specified in maxlength="20"
3) myelement - the id of the textbox where user types text

The function is as below





Now you can use this function anywhere, without a need to modify this function.

The full code to try out is here



Put a link back to our site, if you like this !

Here is a way to convert numbers to words (upto one lakh). It can be extended as per your requirement as well. This is useful for billing etc. Note that only one parameter should be input, and not both. The second parameter is used only for some internal recursive calling.

Hi,

Today i will be showing you how to create a simple 1 level vertical navigation menu with the help of css.
It is very easy and same like the 1 level horizontal navigation menu.

So lets start,

For this we will be using one image


first we will create a simple code to display "unordered list" with ul and li 





So now our display of the ul will be like this



Now we will apply our css to this ul



After applying this css our menu will look like this



Full code of the vertical menu with css is as, just copy and paste it, and modify links and its over.



Hi friends,

here is a simple example of 1 level horizontal navigation menu.
for this i am using 2 images - one is orange and another is blue

you can copy these images from here 


For creating a "1 level horizontal navigation menu" we are going to use "unordered list"




Now this will create an unordered list.





Now we will apply a CSS to this unordered list to make it a horizontal navigation menu.




Hey ! Its ready ! See it !





Completed ready use script and code is here

We always require some kind of login box for any system which has members.

Here i will be showing a simple example with the help of CSS and HTML to create a attractive login box.

To begin with We will create a login box first and then apply the CSS to it

Replace "youfilename.php" with your script which has the logic to check the login.





When you will add this code to your login file then display will be like this - fully stretched on the page with a simple look.

Now we will add a css to this login box to make it look nice.





Now after applying this css see at our login box.



Now combining all together we have created a very simple nice looking login box without using any other images.
Full source code is given below. Just copy and paste it in your project, if necessary just modify the css.




Hi,
Here you will find lots of useful and ready to use free php scripts and codes in php, css, ajax, javascript and many more.....
keep visiting this blog.

Whenever you are working on a project you might need to create a database connection and select a database.

Here i am going to show you a simple way to create your connection file "connect.php"
First create a file and save it as "connect.php"






Now save this file.
Now just include this file on top of your any other php script.
No need to write code each time.
ex. create a new file called "data.php" and include "connect.php" in that file on top as



Have nice time.

How to get IP in php ?

While working on a project you might need a dynamic select box to be generated from the values present in the database.
So this example gives you a simple way to populate a select box with the values present in the database.

Consider a example - there is a table "article" in your database "mydb"

So for this first we need to create a connection with the database and we need to select the database.

For this we will create a file called "connect.php"

replace the values with your actual values as per directed in code



After that we will write our main code in a file called "myselect.php"



And its over. Its very simple.
Try it out, if you face any problem then comment here, i will help you.

Show a-z links on a page for pagination




You can replace $PHP_SELF with the filename for which you want to generate this pagination.
Ofcourse this code doesnt shows the logic to display actually pagination, but instead of taking characters from a-z in a array this is the simple way to show a-z characters for processing.

Soon even i will publish the code to do actual pagination.

[Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in]


Hi,
when you are doing programming in php you might be getting a error like

[Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in] 

this in your php script.

Most of the times if there is mistake in spelling then many errors occurs.

Just check out following things if you encounter this kind of Warning in your php program

  1. First check your query.
  2. If you are using different connection file for creating connection then check whether it is included in your script or not.
  3. If query is correct then check your Database Connection.

If you are user of the Firefox web browser then this is the useful place for you.

Here i am listing down some of the common shortcuts.

1) Open new Tab                       ctrl + t
2) Close current Tab                 ctrl + w
3) Fullscreen ON / OFF           F11
4) Refresh                                  F5
5) Increase Font Size               ctrl + + 
6) Decrease Font Size              ctrl + -
7) Normal Font Size                 ctrl + 0
8) Find                                       ctrl + F
9) Scroll Down                          space
10) Scroll Up                            shift + space

A Great addon for the Firefox ! ! !


If you are want to understand how the page is displayed in firefox browser, how it is divided and showed then you can use the firebug addons for better understanding of the code.

Install this addon from the following URL.


https://addons.mozilla.org/en-US/firefox/collection/firebug_addons


After installation it will ask to restart the firefox.
Restart the firefox and you are done.


After that just right click on any part of the page and click "Inspect Element".








A window will be opened showing the code of the element.




You can alter the code there to see the temporary changes caused by modifying the code or css.
Its very useful for web developers.


<?php
//comments
?>



PHP (Hypertext Pre-Processor)


PHP is a scripting language used for producing dynamic webpages.
PHP is a free open-source server-side scripting language. 
PHP code can be embedded in HTML.

You can find the more information about php on the following Wiki link.

If you are a beginner to php then there are some useful resources available on the net to start with.

You can go through following sites to get information.

1) http://www.w3schools.com/PHP/ - This is a very useful website explaining many functions with examples.

more links will be here........

Hi everyone,


Here you will find a collection of php scripts and programs.

keep visiting blog for more updates.

Here we are trying to build a large and very helpful database of links, codes, scripts and programs related to php and other technologies.