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

Wednesday, March 3, 2010

Benchmark or time script

Here is a little example of how to benchmark or time something with php


<?php

// a function to get microtime
function getmicrotime(){
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}

// start time
$time_start = getmicrotime();

// a little loop to time
for ($i=0; $i < 10000; $i++)
{
// print the loop number
echo $i.'<br />';
}

// the end time
$time_end = getmicrotime();

// subtract the start time from the end time to get the time taken
$time = $time_end - $time_start;


// echo a little message
echo '<br />Script ran for ' . round($time,2) .' seconds.';

?>



This will produce a list of numbers from 0 to 9999 in your browser and tell you how long it took too complete the iterations.

Read More...

PHP Function Number to Roman and Roman to Number


class konversi{
function roman2number($roman){
$conv = array(
array("letter" => 'I', "number" => 1),
array("letter" => 'V', "number" => 5),
array("letter" => 'X', "number" => 10),
array("letter" => 'L', "number" => 50),
array("letter" => 'C', "number" => 100),
array("letter" => 'D', "number" => 500),
array("letter" => 'M', "number" => 1000),
array("letter" => 0, "number" => 0)
);
$arabic = 0;
$state = 0;
$sidx = 0;
$len = strlen($roman);

while ($len >= 0) {
$i = 0;
$sidx = $len;

while ($conv[$i]['number'] > 0) {
if (strtoupper($roman[$sidx]) == $conv[$i]['letter']) {
if ($state > $conv[$i]['number']) {
$arabic -= $conv[$i]['number'];
} else {
$arabic += $conv[$i]['number'];
$state = $conv[$i]['number'];
}
}
$i++;
}

$len--;
}

return($arabic);
}


function number2roman($num,$isUpper=true) {
$n = intval($num);
$res = '';

/*** roman_numerals array ***/
$roman_numerals = array(
'M' => 1000,
'CM' => 900,
'D' => 500,
'CD' => 400,
'C' => 100,
'XC' => 90,
'L' => 50,
'XL' => 40,
'X' => 10,
'IX' => 9,
'V' => 5,
'IV' => 4,
'I' => 1);

foreach ($roman_numerals as $roman => $number)
{
/*** divide to get matches ***/
$matches = intval($n / $number);

/*** assign the roman char * $matches ***/
$res .= str_repeat($roman, $matches);

/*** substract from the number ***/
$n = $n % $number;
}

/*** return the res ***/
if($isUpper) return $res;
else return strtolower($res);
}
}

Read More...

PHP Substr In Array

To find if a value exists in an array, the PHP in_array() function works quite nicely. But there are times when only a partial match is required to check in the array. This substr_in_array() function checks will search the values of an array for a substring. The $needl can be a string or an array of strings to search for.


<?php
/**
*
* @Search for substring in an array
*
* @param string $neele
*
* @param mixed $haystack
*
* @return bool
*
*/
function substr_in_array($needle, $haystack)
{
/*** cast to array ***/
$needle = (array) $needle;

/*** map with preg_quote ***/
$needle = array_map('preg_quote', $needle);

/*** loop of the array to get the search pattern ***/
foreach ($needle as $pattern)
{
if (count(preg_grep("/$pattern/", $haystack)) > 0)
return true;
}
/*** if it is not found ***/
return false;
}
?>


Example Usage


<?php

/*** an arrray to search through ***/
$array = array('dingo', 'wombat', 'kangaroo', 'platypus');


/*** an array of values to search for ***/
$strings = array('foo', 'bar', 'kang');

/*** check for true or false with ternary ***/
echo substr_in_array( $strings, $array ) ? 'found' : 'not found';

/*** a single string to search for ***/
$string = 'plat';

/*** check for true or false with ternary ***/
echo substr_in_array( $string, $array ) ? 'found' : 'not found';
?>

Read More...

Wednesday, April 29, 2009

Check username availability in ajax and php using jquery’s

Now let’s check it how to do check the username avaiability in ajax and php using jQuery.

Html Code :


<div>
User Name : <input name="username" id="username" value="" maxlength="15" type="text">
<span id="msgbox" style="display: none;"></span>
</div>

As you can see the above the “span” with id “msgbox” will show you the username availability message from ajax.

Css code :

.messagebox{
position:absolute;
width:100px;
margin-left:30px;
border:1px solid #c93;
background:#ffc;
padding:3px;
}
.messageboxok{
position:absolute;
width:auto;
margin-left:30px;
border:1px solid #349534;
background:#C9FFCA;
padding:3px;
font-weight:bold;
color:#008000;
}
.messageboxerror{
position:absolute;
width:auto;
margin-left:30px;
border:1px solid #CC0000;
background:#F7CBCA;
padding:3px;
font-weight:bold;
color:#CC0000;
}

I’ve defined three different class for three type of different message class “messagebox” for “checking….” message, “messageboxok” and “messageboxerror” class for displaying username available and not available messages.

As you know you can change the attriubutes of the css of the above code but keep in mind that “position” property should be “absolute”.

Javascript code :

First of all, the jQuery library is used,

<script src="jquery.js" type="text/javascript" language="javascript"></script>

As you can see in the first line, “all” css class is removed from the div displaying the message and then “messagebox” class is added to that that element with adding the text “checking” within the element and displaying with fading effect.


$("#username").blur(function()
{
//remove all the class add the messagebox classes and start fading
$("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
//check the username exists or not from ajax
$.post("user_availability.php",{ user_name:$(this).val() } ,function(data)
{
if(data=='no') //if username not avaiable
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
});
}
else
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);
});
}
});
});

After that, ajax is used to call the PHP file, and when response is received through Ajax then jQuery is used to show the respective message-box with fading effects.

Php Code:

//this varible contains the array of existing users
$existing_users=array('roshan','mike','jason');
//value got from the get metho
$user_name=$_POST['user_name'];
//checking weather user exists or not in $existing_users array
if (in_array($user_name, $existing_users))
{
//user name is not available
echo "no";
}
else
{
//username available i.e. user name doesn't exists in array
echo "yes";
}

In the above PHP code, I’ve added three usernames in a array and then check weather that user exists or not in that array and print “yes” or “no” accordingly. The response taken from ajax is used within JavaScript function to display the appropriate message.But, you can use database connection to check the the availability of username in your code.


View Live Demo
Download full source

Source : http://roshanbh.com.np/2008/04/check-username-available-ajax-php-jquery.html

Read More...

Sunday, December 21, 2008

PHP > Sample Class Login with secure session

This class can be used to prevent security attacks known as session hijacking and session fixation.

When a session is initialized the class computes a fingerprint string that takes in account the browser user agent string, the user agent IP address or part of it and a secret word. If the fingerprint value changes, it is very likely that the session was hijacked and it should no longer be accepted.

To prevent session fixation attacks the calls the PHP session_regenerate_id() function so the session identifier changes everytime the session is checked.

Download : secureSession.zip [ mirror ]

Reference : www.phpclasses.org

Read More...

PHP > Sample Guest Book With Spam Filter

This class can automatically classify text messages to determine whether or not their are considered to be spam.

It can build a knowledge base of known text expressions that can be looked up later to evaluate a factor that expresses the probability of a given text to be spam.

This class could be used in Web mail applications or even in less obvious applications like forums and guest books, acting like an semi-automatic moderator.

Download : SpamFilter.zip [ mirror ]

Other Popular Guestbooks
This method takes all of the POST content, creates a single string, and runs it through SLV. It also removes your host name from the input in case you are passing on a variable such as a thank you page. I have implemented it on several popular guestbooks. I have not tested the code though, it may need some tweaks.

Reference :
- www.phpclasses.org
- www.linksleeve.org

Read More...

Sunday, November 9, 2008

Using PHP scripts to send an email

What is PHP?
PHP, which stands for "Hypertext Preprocessor", is a server-side, HTML embedded scripting language used to create dynamic Web pages. Much of its syntax is borrowed from C, Java and Perl with some unique features thrown in. The goal of the language is to allow Web developers to write dynamically generated pages quickly.

In an HTML page, PHP code is enclosed within special PHP tags. When a visitor opens the page, the server processes the PHP code and then sends the output (not the PHP code itself) to the visitor's browser. It means that, unlike JavaScript, you don't have to worry that someone can steal your PHP script.

PHP offers excellent connectivity to many databases including MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, and Generic ODBC. The popular PHP-MySQL combination (both are open-source products) is available on almost every UNIX host. Being web-oriented, PHP also contains all the functions to do things on the Internet - connecting to remote servers, checking email via POP3 or IMAP, url encoding, setting cookies, redirecting, etc.

Basic Syntax

* File name:
You should save your file with the extension .php (earlier versions used the extensions .php3 and .phtml).
* Comments:
// This comment extends to the end of the line.
/* This is a
multi-line
comment */
* Escaping from HTML:
A PHP code block starts with <?php" and ends with "?>. A PHP code block can be placed anywhere in the HTML document.
* Instruction separation:
Each separate instruction must end with a semicolon. The PHP closing tag (?>) also implies the end of the instruction.

This tip provides information on use of utility Command line email client in PHP script. Use of standard PHP mail() function which allows you to send mail, is very complicated. By using febooti Command line email you can:

  • Send email message using plain text or HTML message with embedded pictures.
  • Send unlimited number of attachments.
  • Use return codes to check success or failure.
  • Works on Microsoft Windows (98 / Me / NT / 2000 / 2003 / XP / Vista) including all server versions.
  • And many more options...
Sample PHP script:

/**** febootimail PHP email ****/
<?php
// Send e-mail from PHP and output the result.
// (On a MS Window operating system with
// the "febootimail.exe" executable in the path).

$server=' -SMTP smtp.sender.com -PORT 25';

$body='"This is <I>HTML / MIME</I> e-mail message"';
$body.='" sent with <B>febooti Command line email</B>"';

$subj='PHP mail';

$command='febootimail.exe -HTML -MIME -FROM web@sender.com ';
$command.='-TO john@sender.com '.$body.$server;
$command.='-SUBJ '.$subj.' -BODY '.$body.$server;

$result=0;

exec($command,$output,$result);
echo 'Output: ';
print_r($output);
echo '<BR>';
echo 'Result: '.$result;

// For detailed information about result codes, see:
// Utility Command line email client with MS-DOS batch files - returned errorlevels
?>

Reference : http://expertsadvice.in

Read More...

Latest Comments

About Me

My photo
Makassar, Sulawesi Selatan, Indonesia

Guest Book


ShoutMix chat widget

Script Sense ©Template Blogger Green by Dicas Blogger.

TOPO