Featured Post Today
print this page
Latest Post

PHP Tutorials

0 comments

Chat Daemon Written In PHP

<?php
/* PHP Word Cloud Generator Example/* --- BEGIN PHP CODE --- */
$stopwords "able,about,above,according,accordingly,
a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
$stopwords explode(","$stopwords);
/* Builds an array of words with all stop words filtered out. (case-insensitive) */
function filter_stopwords($words$stopwords) {
foreach ($words as $pos => $word) {
if (!in_array(strtolower($word), $stopwordsTRUE)) {
$filtered_words[$pos] = $word;
}
}
return $filtered_words;
}
/* Builds an array of words as keys and their frequency as the value. (case-insensitive) */
function word_freq($words) {
$frequency_list = array();
foreach ($words as $pos => $word) {
$word strtolower($word);
if (array_key_exists($word$frequency_list)) {
++$frequency_list[$word];
}
else {
$frequency_list[$word] = 1;
}
}
return $frequency_list;
}
/* Optional function to filter out words below a specific frequency. */
function freq_filter($words$filter) {
return array_filter(
$words,
function($v) use($filter) {
if ($v >= $filter) return $v;
}
);
}
/* Builds the word cloud and returns a string containing a div of the word cloud. */
function word_cloud($words$div_size 400) {
$tags 0;
$cloud "<div style=\"width: {$div_size}px\">";
/* This word cloud generation algorithm was taken from the Wikipedia page on "word cloud"
with some minor modifications to the implementation */
/* Initialize some variables */
$fmax 96/* Maximum font size */
$fmin 8/* Minimum font size */
$tmin min($words); /* Frequency lower-bound */
$tmax max($words); /* Frequency upper-bound */
foreach ($words as $word => $frequency) {
if ($frequency $tmin) {
$font_size floor(  ( $fmax * ($frequency $tmin) ) / ( $tmax $tmin )  );
/* Define a color index based on the frequency of the word */
$r $g 0$b floor255 * ($frequency $tmax) );
$color '#' sprintf('%02s'dechex($r)) . sprintf('%02s'dechex($g)) . sprintf('%02s'dechex($b));
}
else {
$font_size 0;
}
if ($font_size >= $fmin) {
$cloud .= "<span style=\"font-size: {$font_size}px; color: $color;\">$word</span> ";
$tags++;
}
}
$cloud .= "</div>";
return array($cloud$tags);
}
if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST' && $_POST['text'] != '') {
/* If the request verb is POST and the appropriate field is supplied and isn't
empty, we will attempt to generate the word cloud. */
$text $_POST['text']; /* Get the posted text */
$words str_word_count($text1); /* Generate list of words */
$word_count count($words); /* Word count */
$unique_words countarray_unique($words) ); /* Unique word count */
$words_filtered filter_stopwords($words$stopwords); /* Filter out stop words from the word list */
$word_frequency word_freq($words_filtered); /* Build a word frequency list */
/* Optionally, you can filter out words below a specific frequency... Uncomment the line below to do so */
/* $word_frequency = freq_filter($word_frequency, 3); */
$word_c word_cloud($word_frequency); /* Generate a word cloud and get number of tags */
$word_cloud $word_c[0]; /* The word cloud */
$tags $word_c[1]; /* The number of tags in the word cloud*/
}
else {
/* Otherwise there is nothing to do... */
$text "";
$word_count $unique_words $tags 0;
$word_cloud null;
}
/* --- END PHP CODE --- */
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>PHP Word Cloud Generator Example - By Sherif Ramadan - sheriframadan.com</title>
</head>
<body>
<form method="post" action="">
<textarea cols="100" rows="15" name="text"></textarea>
<br />
<input type="submit" value="Generate Word Cloud" />
</form>
<p><b>Number of words found:</b> <?php echo $word_count?></p>
<p><b>Number of unique words:</b> <?php echo $unique_words?></p>
<p><b>Number of words tagged:</b> <?php echo $tags?></p>
<?php echo $word_cloud?>
</body>
</html>
0 comments

PHP Word Cloud Generator


Code

<?php
/*
* PHP relay chat daemon -
* To run the daemon in the background from the command line
use `/usr/bin/php server.php > /dev/null 2>&1 & disown` (or similar)
*/
if (strtolower(PHP_SAPI) !== 'cli') exit;    // The daemon must only be allowed to run in CLI
set_time_limit(0);        // Prevent time limit
echo "Daemon starting...\r\n";
/*
* Initialize global variables
*/
$master = array();
$users = array();
$connections NULL;
$serveraddress 'sheriframadan.com'# Enter server address or IP here
$serverport 10000# Port to listen on
$serveruri 'tcp://' $serveraddress ':' $serverport;
$tv_sec 0;
$tv_usec 200000# 200,000 microseconds is the time out on each stream (200ms or 0.2s)
$write = array();
$exceptions = array();
$blocking_mode 0# 0 for non-blocking streams and 1 for blocking streams
$usertimeout 60*15# default user stream timeout in seconds [default should be 15 minutes]
$peername NULL# This will be passed by reference so only use to assign upon new connections
$packetsize 1024# Default packet size is set to 1024 bytes
/*
* Initialize listening socket
*/
if (!$socket stream_socket_server($serveruri$errno$errstr)) {
// Catch startup errors here
echo "Error! Unable to start the daemon on [$serveraddress] using port ($serverport).\r\nError #: $errno\r\nError: $errstr\r\n";
exit;
}
stream_set_blocking($socket$blocking_mode); # Set the stream to non-blocking
echo "Server connected on [$serveraddress] using port ($serverport)!\r\n\r\n";
/*
* Main loop
*/
$master[] = $socket// Add the servers connection to the listening socket in the master array
$connections $master;// We copy the master array for now to avoid modifying it 
//with stream_select as it's arrays are passed by reference
while (true) {
$connections $master# Make sure we have a fresh copy of the master array in each loop
$numconnections stream_select($connections$write$exceptions$tv_sec$tv_usec);
// If an error has been returned by the call to stream_select() we must catch it here
if ($numconnections === FALSE) {
echo "An error occurred capturing the streams.\r\nUnbale to continue work: shutting down...\r\n\r\n";
break;
}
// This is where we read/write to all existing streams and accept new connections
for ($i 0$i $numconnections$i ++) {
// The connection is made to the listening socket
if ($connections[$i] === $socket) {
$newconnection stream_socket_accept($socket$usertimeout$peername);
$master[] = $newconnection# Add the new connection to the master array
$users[$peername] = $newconnection# Define the users peername in the users array
echo "- New connection detected from [$peername]\r\n\r\n";
stream_set_blocking($newconnection$blocking_mode); 
# define the blocking mode for this new connection
if ($socket_data fread($newconnection$packetsize)) { // Connection sent data...
$socket_data_bytes strlen($socket_data);
echo "* Read $socket_data_bytes bytes from [{$peername}]\r\n--- BEGIN MESSAGE --
-\r\n$socket_data\r\n--- END MESSAGE ---\r\n\r\n";
unset($socket_data,$socket_data_bytes,$newconnection);
}
// Write welcome message here
list($ip$port) = explode(':'$peername);
fwrite($newconnection"Welcome to the PHP server!\r\nI see you are connecting to me using 
$serveraddress on port $serverport from IP address $ip on port $port.\r\n");
unset($ip$port);
}
else { // Continue reading from sockets here.
$socket_data fread($connections[$i], $packetsize);
$socket_data_bytes strlen($socket_data);
$peer array_search($connections[$i], $usersTRUE);
$stream array_search($connections[$i], $masterTRUE);
if ($socket_data_bytes === 0) { // The client probably closed the connection
echo "* Client on [$peer] closed the connection.\r\n- Terminating stream...\r\n\r\n";
fclose($connections[$i]); # Close the client connection
unset($master[$stream],$users[$peer]); # unset variables and continue
}
elseif ($socket_data === FALSE) { // Tere's a problem reading from the socket
echo "- There was a problem reading from [$peer]...\r\n* Closing client connection!\r\n\r\n";
fclose($connections[$i]); # Close the client connection
unset($master[$stream],$users[$peer]); # unset variables and continue
}
else {
$numusers count($users);
echo "* Read $socket_data_bytes bytes from [$peer]\r\n--- BEGIN MESSAGE --
-\r\n$socket_data\r\n--- END MESSAGE ---\r\n\r\n";
// Send the message to all users still connected to the server
foreach ($users as $user) {
fwrite($user"* [$peer] said: $socket_data\r\n");
}
echo "* Relayed message to $numusers user(s).\r\n\r\n";
unset($user,$numusers);
}
unset($peer$stream$socket_data$socket_data_bytes);
}
}
}
/*
* Handle anything after main loop breaks here
*/
echo "The daemon has been stopped!\r\n\r\n";
?>

Example Usage

To start the daemon from the command line use nohop or disown to background the proccess. Also don't forget to send STDOUT to /dev/null or some designated logging file along with redirecting STDERR to STDOUT.
You can use something like `php server.php > /dev/null 2>&1 & disown` or similarly `nohup php server.php > /dev/null 2>&1 &`
You can test connecting to the server by opening a terminal and using telnet. Example: `telnet <server address> <server port>`
Once you telnet in you should see the welcome message and anything you type after that will be relayed to anyone else connected after you hit enter.
Please consider that this code is meant for demonstration purposes only. There are no constraints in place to limit the number of connections the server will accept or any mechanisms in place to prevent any form of Direct denial of Services attack. So do implement your own methods and security considerations as this code is not production ready. There is also no protocol in place for a handshake or user sign-on. The server will accept any connection it receives on the designated port and continue relaying messages.
0 comments
 
Support : Creating Website | Johny Template | Mas Template
Copyright © 2011. PHP MySQL Online Training - All Rights Reserved
Template Created by Creating Website Published by Mas Template
Proudly powered by Blogger