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

PHP has nice support for Mathematical processing. And for doing rounding off we generally need functions like ceil() and floor().

Lets see how to use these functions...

PHP ceil() Function

The ceil() function rounds the value "UPWARDS" to the nearest integer.

Check the code below


The output of the above code will be 1.

PHP floor() Function

The floor() function rounds off the value "DOWNWARDS" to the nearest integer.
Check the code below

The output of the above code will be 0.

This is a small script which will help you find the number of rows from a mysql database for your query.

First connect to your database, just create a database connection file.



so now you can use this $num_rows variable throughout your program for any manipulation.

Hi everyone,
Today i am going to show you how to Create Guestbook / Shoutbox in php mysql, in a very easy way and with simple code.
First thing that you might be thinking is what is a Guestbook or Shoutbox ?
These are the places where your website visitors or users can type their views or some information in a simple box.
In this program we are going to create a simple shoutbox / Guestbook which will allow your website visitor to enter some simple data about your website.

So lets start,
First we need to create the table which will store our data into database.
Create the table structure in your MySQL database as follows



After creating database and table you need to create a database connection file.
If you don't know how to create a database connection file then you should check this.
Specify the settings in database connection file.

Now we will be creating a form which will accept user's name and their shout or opinion.
So lets design it.
If the form is not posted then we will display the form and show the existing records from the database.



if (!isset($_POST["submit"]))
{
$query = "SELECT id, name, message, DATE_FORMAT(date, '%D %M, %Y') as newdate FROM guests ORDER BY id DESC LIMIT 0, 8";
$result = mysql_query($query);
?>

Post a message

















while ($row = mysql_fetch_object($result))
{
?>

message; ?>


Posted by name; ?> on newdate; ?>

}
?>

}
?>



So now you will see a form which will show you a textbox and a textarea for entering name and some shout. Just enter name and shout and click submit.

Now is the actual part of entering shout into database and come back to entry page.
So now we will be checking if the form is submitted then we will process the form.

For security we will be adding a simple spam comment prevention logic, we will not allow one ip to enter more than 5 shouts, comments to our form on same day.



$name = stripslashes($_POST['name']);
$message = stripslashes($_POST['msg']);


if(isset($_POST["submit"]))
{
// Add new entry to the database
$ip = $_SERVER['REMOTE_ADDR'];
$now = date("Y-m-d");

$query1 = "SELECT * FROM guests WHERE guestip='$ip' and date ='$now'";
$result1 = mysql_query($query1);
$cnt = mysql_num_rows($result1);

if($cnt<5)
{
$now = date("Y-m-d");
$query = "INSERT INTO guests (name, message, date, guestip) VALUES ('$name','$message','$now','$ip')";
$result = mysql_query($query) or die(mysql_error());
// go back to entry page
$referer = $_SERVER['HTTP_REFERER'];
header ("Location: $referer");
}
else
{
echo "Thank you for your comments. But you cannot submit more comments today as its a spam prevention mechanism to avoid spammers.";
echo "
If you are a spammer then just GO away.";
}
}



And you are done. Our shoutbox is ready to accept your website viewers shouts.

Now some interesting part to design your form and display with css






So you are ready with a nice looking shoutbox.
See here is the full source code for your testing


//code
<?php

// Database Settings

include "connect.php";

//connecting to databae and selecting database
mysql_connect($host, $user, $pass) OR die ("Error connecting to the server.");
mysql_select_db($db) OR die("Error selecting the database.");

$name = stripslashes($_POST['name']);
$message = stripslashes($_POST['msg']);


if(isset($_POST["submit"]))
{
// Add new entry to the database
$ip = $_SERVER['REMOTE_ADDR'];
$now = date("Y-m-d");

$query1 = "SELECT * FROM guests WHERE guestip='$ip' and date ='$now'";
$result1 = mysql_query($query1);
$cnt = mysql_num_rows($result1);

if($cnt<5)
{
$now = date("Y-m-d");
$query = "INSERT INTO guests (name, message, date, guestip) VALUES ('$name','$message','$now','$ip')";
$result = mysql_query($query) or die(mysql_error());
// go back to entry page
$referer = $_SERVER['HTTP_REFERER'];
header ("Location: $referer");
}
else
{
echo "Thank you for your comments. But you cannot submit more comments today as its a spam prevention mechanism to avoid spammers.";
echo "
If you are a spammer then just GO away.";
}
}

if (!isset($_POST["submit"]))
{
$query = "SELECT id, name, message, DATE_FORMAT(date, '%D %M, %Y') as newdate FROM guests ORDER BY id DESC LIMIT 0, 8";
$result = mysql_query($query);
?>

Post a message

















<?php
while ($row = mysql_fetch_object($result))
{
?>

<?php echo $row->message; ?>


Posted by <?php echo $row->name; ?> on <?php echo $row->newdate; ?>

<?php
}
?>

<?php
}
?>




Let us know whether you liked it or not. This is just a basic sample example for you.
Its not fully secure. If you know some simple function to prevent bots using this for data entry then let me know.

Hi,

Here is a simple function which can be used to parse the URL.

parse_url is a built in php function which can be used to parse url and get the type of request like whether its http or https or ftp, gives the domain name like www.google.com and path and the query.


In http://www.chaprak.com/articles.php?cat_id=6 this url if you execute parse_url function then it will show the following result.

scheme - http
url - www.chaprak.com
path - /articles.php
query - cat_id=6






For more information click here.

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

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.

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++;
}
?>