For something I have been doing in a php project of late, I needed to weight an array of values and as I go round and select the values remove the value or -1 from the weight depending on how many of the value are left in the weight.
If you have any improvements or suggestions then id very much like to here them
$starttime = microtime();
$startarray = explode(" ", $starttime);
$starttime = $startarray[1] + $startarray[0];
/**
* weighted_random()
* Pick a random item based on weights.
*
* @param array $values Array of elements to choose from
* @param array $weights An array of weights. Weight must be a positive number.
* @return mixed Selected element.
*/
function weighted_random($values, $weights){
$count = count($values);
$i = 0;
$n = 0;
$num = mt_rand(0, array_sum($weights));
while($i < $count){
$n += $weights[$i];
if($n >= $num){
break;
}
$i++;
}
return $i;
}
function recalc($val,$values,$weight){
//two steps to consider here, -1 from the weight and if the weight is <=0 unset both the value and the weight.
if($weight[$val]-1<=0){
unset($weight[$val]);
unset($values[$val]);
$new_values = array();
$new_weight = array();
foreach($values as $k=>$v){
$new_values[]=$v;
$new_weight[]=$weight[$k];
}
return array($new_values,$new_weight);
}else{
$weight[$val]=$weight[$val]-1;
return array($values,$weight);
}
}
//in the context of what im doing lets get this right.
$values = array(0=>"164-2",1=>"164-1",2=>"2-2");
$weights = array(0=>1,1=>2,2=>1);
//now we wanna select 4 values but edit them as we go round.
$find = 3;
for($i=0;$i<$find;$i++){
$val = weighted_random($values,$weights);
echo $val.' | ';
echo $values[$val].'<br />';
list($values,$weights) = recalc($val,$values,$weights);
}
echo 'The new weights are ';
print_r($weights);
echo '<br />';
$endtime = microtime();
$endarray = explode(" ", $endtime);
$endtime = $endarray[1] + $endarray[0];
$totaltime = $endtime - $starttime;
$totaltime = $totaltime;
echo "This page loaded in $totaltime seconds.";
?>
Lately I have been considering PHP frameworks and using them to speed up development of small projects, whilst also considering the MVC (Model, View, Control) approach. Most people looking for a PHP framework seem to stick with CodeIgniter, Zend or Symfony. Each with there own advantages and disadvantages. Which one is best is all down to personal taste and its very difficult to make an educated selection of the framework thats best for you. Its baffled me infact, that I can’t put my finger on the framework that I think works for me the best.
So I plan to try and develop a small project in each of these frameworks and decide after that which one I think is the best for me.
For more complex sites, I will continue to use my own custom framework as it helps to keep down page load speeds and ease of understanding.
Check back here over the next month or so, to see what I get up too. As I will be posting all about my experiences with the frameworks.
For quite a long time now ive been seeing lots of image upload scripts which boast to be able to upload multiple images at a time! 90% dont work.
So heres one I created and I know works. Firstly the below code is the functions to handle the images, you do not need to touch anything here, just make sure its on your page.
/**
* Dave Hewards image script
*/
function resize($img, $thumb_width, $newfilename){
$max_width=$thumb_width;
//Check if GD extension is loaded
if (!extension_loaded('gd') && !extension_loaded('gd2'))
{
trigger_error("GD is not loaded", E_USER_WARNING);
return false;
}
//Get Image size info
list($width_orig, $height_orig, $image_type) = getimagesize($img);
switch ($image_type)
{
case 1: $im = imagecreatefromgif($img); break;
case 2: $im = imagecreatefromjpeg($img);Â break;
case 3: $im = imagecreatefrompng($img); break;
default:Â trigger_error('Unsupported filetype!', E_USER_WARNING);Â break;
}
/*** calculate the aspect ratio ***/
$aspect_ratio = (float) $height_orig / $width_orig;
/*** calculate the thumbnail width based on the height ***/
$thumb_height = round($thumb_width * $aspect_ratio);
while($thumb_height>$max_width)
{
$thumb_width-=10;
$thumb_height = round($thumb_width * $aspect_ratio);
}
$newImg = imagecreatetruecolor($thumb_width, $thumb_height);
/* Check if this image is PNG or GIF, then set if Transparent*/
if(($image_type == 1) OR ($image_type==3))
{
imagealphablending($newImg, false);
imagesavealpha($newImg,true);
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
imagefilledrectangle($newImg, 0, 0, $thumb_width, $thumb_height, $transparent);
}
imagecopyresampled($newImg, $im, 0, 0, 0, 0, $thumb_width, $thumb_height, $width_orig, $height_orig);
//Generate the file, and rename it to $newfilename
switch ($image_type)
{
case 1: imagegif($newImg,$newfilename); break;
case 2: imagejpeg($newImg,$newfilename);Â break;
case 3: imagepng($newImg,$newfilename); break;
default:Â trigger_error('Failed resize image!', E_USER_WARNING);Â break;
}
return $newfilename;
}
The next part is the important part which you will need to change some variables on to customise them for your own site.
//This stuff is outside of the function. It operates with our images
if(isset($_POST['submitimages']))
{
$success=0;
$imgNumb=1; //This the "pointer" to images
$DestinationDir="/sites/mysite.com/http/uploads/profiles/full/";Â //Place the destination dir here
$ThumbDir="/sites/mysite.com/http/uploads/profiles/thumbs/";Â //Place the thumb dir here
do{
if($_FILES["img$imgNumb"][tmp_name]!='')
{
$success++;
$Unique=microtime(); // We want unique names, right?
$destination=$DestinationDir.md5($Unique).".jpg";
$thumb=$ThumbDir.md5($Unique).".jpg";
$IMG=getimagesize($_FILES["img$imgNumb"][tmp_name]);
$finalimage = resize($_FILES["img$imgNumb"][tmp_name], 199, $destination);
//use the filename variable below to record the image name entered so that you can then use this variable to update your database if
$filename = md5($Unique).".jpg";
$field = 'img'.$imgNumb;
//mysql update your database fields
mysql_query("update profile set $field = '$filename' where playerid='$id'");
}
$imgNumb++;
} while($_FILES["img$imgNumb"][name]);
if($success>=1)
{
$message = "Images uploaded!";
}
}// end
Finally you will need a little bit of HTML code for your form for the user to submit his/her new images to the site.
To keep the browser from executing a script when the page loads, you can put your script into a function.
A function will be executed by a call to the function.
You may call a function from anywhere within a page.
Create a PHP Function
A function will only be executed when a subsidiary piece of code calls it.
function functionName()
{
// code to be executed;
}
Start by giving your function a name so in this case i will call my new function…findme();
function findme(){
echo 'i found you';
}
findme();
As you will see from testing this my call to the function underneath it will make the browser execute the code inside the function echoing i found you onto the page.
Passing parameters to the function
Okay so we now have our findme() function which as it stands just echos something onto the page. This brings us to the two fundamental reasons for using functions. Firstly because they stop the use of repetitive code, if you needed to do the same 10 line or piece of code very often then you would save yourself alot of time by using a function to do so.
Functions are standalone so if you want the function to receive some kind of input so lets say for instance you have a form and you want to test what name was entered by the user.
The function will now check the inputted name from the form in the function.
Returning Values From A Function
So at the moment our function will echo what it finds, but what if we want it to just pass a variable out of the function back to us? Well you simply use the return php function.
function findme($name){
if($name=='fred')
{
$nam = 'dave';
}
elseif($name=='Bungle')
{
$nam = 'Sesame';
}
//$nam now contains the variable that we want our function to return so simply just do
return $nam;
}
if(isset($_POST['name']))
{
$nam = findme($_POST['name']);
}
/* and thats it, now your $nam variable in your main php script will contain one of the names from above, providing someone enters one of the names i used in this example. */
This is the very basics of using and creating a php function! Check my other articles coming soon for more in depth articles!
An annoying problem when developing a messaging system or a forum is that users often decide to be childish.
Spamming it with the following sort of message.
Now you can set “overflow:auto;” in your css property of the element which will deal with it well enough if the string contains a space.
However it will not deal with the problem of the above style spam/childish message if it does not contain a space, or a string within a message which does contain spaces does not or is similar to the above message.
What youll find probably if your looking at this is that the message makes the element stretch and or exceeds the elements width and basically makes a right mess of your page layout.
if(isset($_POST['submit'])){
$msg = htmlentities($_POST['msg'], ENT_QUOTES);
//send the posted msg to the function to check for long strings.
//you must define a width suitable for the maximum width a string can be in your desired element.
$msg = one_wordwrap($msg,50);
//go on to do whatever you may wish with the wrapped $msg variable.
}
[/sourcecode]
Wallah you will now have a function which gets rid of annoying longs strings, by simply putting a space at the set width intervals you specified. You could change this so that it puts a new line in with either “br n”. The reason I put a space in it, is with the space it allows the containers css properties of “overflow:auto;” to adjust the lines which I find works really well for my in-game messaging system.
I created this the other day for one my websites and find it very handy. For instance if you want to creat your very own log file of all your php and mysql errors youll have a nice convenient text file which contains all of your logs.
You can even take it that little bit further and create access logs or logs for particuarly actions etc. Its simple enough to code so just follow the steps below.
Create a file called logfile.txt on your server (make sure you remember the path to that file).
Insert the below functions either directly into your page, or into your functions page.
[sourcecode=php]//File will be rewritten if already exists
function append_file($filename,$newdata) {
$f=fopen($filename,”a”);
fwrite($f,$newdata);
fclose($f);
}
[/sourcecode]
3. Then all thats left is to just call that function like so below, a new line of text will be added to the bottom of the new logfile.txt file.
[sourcecode=php] //add more data ot the existing file
append_file(“../logs/logfile.txt”,”New text addedn”);[/sourcecode]
You can take this further if you wish and add a read file module.
You can simply do that by adding the below function to your page.