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.

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.

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.

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.

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