Laravel .htaccess localhost MAMP and Mac OS X

I was, like anyone, excited about the release of Laravel 4 and quickly set about following the initial installation instructions on a vanilla vhost locally to have a play around with. I quickly found that the default suggested .htaccess file was causing a server error in MAMP on OS X.

I got around it with a little trial and error and can confirm the below contents in your .htaccess file – works great for me.

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . /index.php [L]

The offending line from the suggested .htaccess contents was

RewriteRule ^ index.php [L]

Best installation guidelines for MAMP and PHPUnit

These are the best guidelines I have found and mashed together recently for installing and configuring PEAR and PHPUnit for use with MAMP.

Firstly tell PEAR to auto discover:

sudo /Applications/MAMP/bin/php/php5.4.4/bin/pear config-set auto_discover 1

Secondly install the PHPUnit PEAR package:

sudo /Applications/MAMP/bin/php/php5.4.4/bin/pear install pear.phpunit.de/PHPUnit

Thirdly link it to your profile:

sudo ln -s /Applications/MAMP/bin/php/php5.4.4/bin/phpunit /usr/local/bin/phpunit

Lastly test it:

phpunit --version

Should output:
PHPUnit 3.7.10 by Sebastian Bergmann.

All done!

PHP Curl URL which has redirects to obtain the final URL

Been doing some toying around lately with various ways of scraping hidden URL’s from a website that deliberately tries to hide them.

I have been using PHP and the CURL library ascertain the final URL after redirects whilst also picking up on javascript redirects etc.

This is what i’ve come up with so far, and it’s working a dream.

function get_final_url( $url, $timeout = 5 ){
    $url = str_replace( "&", "&", urldecode(trim($url)) );
   	$cookie = tempnam ("/tmp", "CURLCOOKIE");
	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
	curl_setopt( $ch, CURLOPT_HEADER, true);
	curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
	curl_setopt( $ch, CURLOPT_ENCODING, "" );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
	curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
	curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
	curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
	$content = curl_exec( $ch );
	$response = curl_getinfo( $ch );
	curl_close ( $ch );
	if ($response['http_code'] == 301 || $response['http_code'] == 302):
	    ini_set("user_agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1");
	    $headers = get_headers($response['url']);
	    $location = "";
	    foreach( $headers as $value ):
	        if ( substr( strtolower($value), 0, 9 ) == "location:" )
	            return get_final_url( trim( substr( $value, 9, strlen($value) ) ) );
	    endforeach;
	endif;
	if (preg_match("/window.location.replace('(.*)')/i", $content, $value) ||
	        preg_match("/window.location="(.*)"/i", $content, $value) ||
	        preg_match("/location.href="(.*)"/i", $content, $value) ):
	    	return get_final_url ( $value[1] );
	else:
	    return $response['url'];
	endif;
}
// Simply called like so
$my_final_url = get_final_url('http://originalurl.com',10);

PHP Weighted Random Choice & Selection Remove / Replacement

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 icon smile PHP Weighted Random Choice & Selection Remove / Replacement

$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].'
';
		list($values,$weights) = recalc($val,$values,$weights);
	}
	echo 'The new weights are ';
	print_r($weights);
	echo '
';
	$endtime = microtime();
	$endarray = explode(" ", $endtime);
	$endtime = $endarray[1] + $endarray[0];
	$totaltime = $endtime - $starttime;
	$totaltime = $totaltime;
	echo "This page loaded in $totaltime seconds.";
?>

PHP frameworks CodeIgniter, Zend & Symfony

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.

PHP Multiple Image Upload Script / User Image Upload – That actually works!

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.

<form action="" method="post" enctype="multipart/form-data" >
<table width="300px"><tr><th colspan="3">Change Profile Images: </th></tr>
<tr><td>Image 1:</td><td><input type="file" name="img1"></td></tr>
<tr><td>Image 2:</td><td><input type="file" name="img2"></td></tr>
<tr><td>Image 3:</td><td><input type="file" name="img3"></td></tr>
<tr><td colspan="2" align="right"><input type="submit" name="submitimages" class="submitlarge" value="Upload profile images"></td></tr></table>
</form>

This code is tried and tested and it works so please enjoy and comment if you have some suggestions for ways to improve it further.

PHP Functions – How to make your own function

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.

function findme($name){
    if($name=='fred')
    {
        echo 'dave';
    }
    elseif($name=='Bungle')
    {
        echo 'Sesame';
    }
}
if(isset($_POST['submit']))
{
    $name = $_POST['name'];
    findme($name);
}

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!

How to deal with long continuous strings with a PHP function

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.

“pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp”

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.

I have developed a work around for it below:

function one_wordwrap($string,$width){
  $s=explode(" ", $string);
  foreach ($s as $k=>$v) {
    $cnt=strlen($v);
    if($cnt>$width) $v=wordwrap($v, $width, " ", true);
      $new_string.="$v ";
  }
  return $new_string;
}
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.
}

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.

Hopefully this is useful to someone else

One line unzip and mysql dump to database

After some advice on my last post I thought id make another post with a revised version of my other post about the same topic.

unzip -p mydb.zip | mysql -u USER -pPASS -D dbname

This one line will do the job of unzipping a db.zip file on your remote server to the database of your choice.

Hope this is helpful!