Archive for PHP

PHP Test Fest

Title: PHP Test Fest
Location: MadLab
Link out: Click here
Description: Come Test PHP!
Start Time: 12:00
Date: 2010-09-11

I came, I saw and a I tested.
A good test fest for PHP and my 1st. I managed to get two tests complete.. mainly because of my inability to follow instructions :D

anyway was all good and great to see so many people there.

Don’t use IsValid in your Doctrine Models – a warning

Recently for a project i’ve been making heavy use of Doctrine. In one of the models I had a method to check to see if the object was valid under a certain set of conditions. I named this function isValid .. and it had 2 params. Little did I know that this was actually overriding an existing deep rooted isValid which gets fired on saving the object to the DB. Bummer.

So this is a quick warning to all you Doctrine users. Unless you want to actually override the isValid method for saving, call your check method function something else!

PHP – Chmod-ed to Windows hell and back

Today has not been a good day.

With various things going wrong, I was please that I had got the file upload code done for a site i’m working on. All I needed to do was make sure that the file had the right permissions and then edit it via GD (via an image editor class i have). Here’s where the trouble started..

I started off by chmoding the file to 777 and then trying to do the resize.. this threw an error with permissions.. so i looked at the file.. Read Only.. strange I thought.

Then I checked the folder and that had a weird green square instead of the checkmark in the checkbox. I tried to remove the read only attribute off of this and hte file.. and it kept coming back.. I went all around hte houses, trying all sorts of techniques .. to no avail.

@auroraeosrose in the PHPWomen IRC channel helped a lot as did Dreis.. (thanks muchly)..

After backing up the files and formatting the drive, to reinstalling the Apache/PHP/MySql stack I was no clearer to the answer as to why the file was always ending up with read only permissions..

Finally it came down to the 1 thing that I had overlooked.. the chmod in the code .. the second parameter was 777. I thought this was correct. Aparrantly not. The second parameter of the chmod function requires an octal code.. thus prefixing the 777 with a 0 (zero) fixed the whole issue.

Boy did i really feel dumb today.

So to wrap up, remember to always pass a FOUR digit code through to chmod or face the annoyance and headache I got today.

php: processing raw Post / Get Values

I just added a jquery plugin to call head requests, but because you are not doing a get or post request php won’t convert the values that are sent back to their form.
To get around this we have to use the php://input stream ( is that the right word?) which is handy for a lot of things.

$data = file_get_contents("php://input");
$lines = explode("&",$data);
foreach($lines as $line) {
    list($key,$value) = explode("=",$line,2);
    $_REQUEST[$key] = $value;
}

basically this grabs the data from the php://input and then splits it up into it’s component parts and then stores that within the $_REQUEST superglobal array.
Why $_REQUEST well we’re calling a head request and not a post or get request, so where else should it go.

The php://input is handy when doing stuff like xmlRPC or jsonRPC etc ..

Hopefully this will benefit someone out there

<edit>
Thanks to Mortal of #php on OFTC (irc) for pointing out the unlimited explode

php: smarty assign content plugin

I needed to assign a block of content to a variable instead of just a value.. so i set about creating this plugin

function smarty_block_assign_content($params, $content, &$smarty)
{
        $smarty = clone($smarty); //Copy the original class, so there's no garbage variables after we finish
        if(!isset($content))
                return;
        if (!isset($params['var'])) {
                $smarty->trigger_error("assign_content: missing 'var' parameter", E_USER_WARNING);
                return;
        }

        //Compile content to ensure all smarty tags get processed
        $smarty->assign($params['var'], $content);
                $smarty->assign($k, $v);
        return ;
}

example of usage:

{assign_content var='menu'}
  {foreach from=$menus.cats->children item='cat'}
  <div class="item{if $cat->active || $cat->expanded}_select{/if}">
    <div class="arrow"></div>
    {if !$cat->active}<a href="{$cat->link}">{/if}{$cat->text}{if !$cat->active}</a>
    {/if}
  </div>
  {if $cat->children|@count ne 0 || $cat->expanded}
    {foreach from=$cat->children item='subCat'}
      <div class="subitem{if $subCat->active}_select{/if}">
        <div class="arrow"></div>
      {if !$subCat->active}<a href="{$subCat->link}">{/if}{$subCat->text}{if !$subCat->active}</a>{/if}
      </div>
    {/foreach}
  {/if}
  {/foreach}
{/assign_content}

This will set the code we used to generate the menu and assign it to $menu for later use.
Hope you find as usefull

php: Menu Classes

Recently I’ve been working on my own framework (we’ve all done it i’m sure) and part of this was a menu handling system.

The basis really is simple, we have a menu item which really is just link and text. That menu item could have children, could be active and/or be selected.

In this case Selected is the currently menu item, which is also Active, and all it’s parents in the chain upwards are also active.

We also have a menu controller which makes it easier to add to the menus.

class menuHandler {
    public $menus=array();
    public function NewMenu() {
        $k = time();
        $this->menus[$k] = new menu_class();
        return $k;
    }
    public function AddMenu($key,menu_class $menu) {
        if (!isset($this->menus[$key])) {
            $this->menus[$key] = $menu;
        }
        return $this;
    }
    public function ItemCount($menuKey) {
        $menu = $this->menus[$menuKey];
        if (!($menu instanceof menu_class)) {
            return -1;
        }
        else {
            return count($menu->children);
        }
    }
    public function AddItem($menuKey,$itemKey=null,menu_class $item) {
        if (isset($this->menus[$menuKey])) {
            $menu = $this->menus[$menuKey];
            if (!isset($itemKey) or (is_numeric($itemKey) &amp;amp;amp;&amp;amp;amp; $itemKey <0)) {
                $itemKey = count($menu->children);
            }
            $menu->AddSubItem($item,$itemKey,$menuKey);
        }
        return $this;
    }
    public function SetActive($id,$from=null) {
        $menu = new menu_class();
        if ($from == null) {
            $from = $this->menus;
        }
        elseif($from instanceof menu_class) {
            $from = $from->children;
        }
        foreach ($from as $key=>&amp;amp;amp;$menu) {
            if ($key==$id) {
                $menu->active=true;
                return true;
            }
            elseif(count($menu->children) !=0) {
                $r = $this->SetActive($id,$menu->children);
                if ($r) {
                    $menu->expanded = true;
                    return $r;
                }
            }
        }
    }
}
class menu_class {
    public $children = array();
    public $myParent=null;
    public $active = false;
    public $expanded = false;
    public $link ='';
    public $text = '';
    public $additional = array();

    public function AddSubItem($item,$ID=null,$parentID=null) {
        if ($item instanceof menu_class) {
        }
        elseif(is_array($item)) {
            $item = new menu_class();
            $item->text = $details[0];
            $item->link = $details[1];
        }
        if (isset($ID)) {
            if (isset($this->children[$ID])) {
                if (is_numeric($ID)) {
                    $this->children = array_insert($this->children,$item,$ID);
                }
            }
            else {
                $this->children[$ID] = $item;
            }
        }
        else {
            $this->children[] = $item;
        }
        if (!isset($parentID)) {
            $parentID = "main";
        }
        $this->myParent = $parentID;
        ksort($this->children);
    }

    public function __construct($text=null,$link=null) {
        if(isset($text) &amp;amp;amp;&amp;amp;amp; !is_null($text)) {
            $this->text = $text;
        }
        if(isset($link) &amp;amp;amp;&amp;amp;amp; !is_null($link)) {
            $this->link = $link;
        }
    } 

    public function Format($text) {
        if (!empty($this->link)) {
            $text= str_replace("%href%",$this->link);
        }
        if (!empty($this->text)) {
            $text = str_replace("%text%",$this->text);
        }
        return $text;
    }
}

You will notice that i’ve used the array_insert function from my previous posting. This was why it was created, so that i could insert without worry that i would overwrite the code

here’s an example of using the code

$menus = new menuHandler();
$menus->AddMenu("main",new menu_class());
 $menus->AddItem("main",-1,new menu_class("TEXT","link.php"));
 $menus->AddItem("main",-1,new menu_class("TEXT2","link2.php"));
//we want this item to be 1st!
 $menus->AddItem("main",0,new menu_class("1st Link","homelink.php"));

So far I pass the $menus out to smarty in the usual assignment method and process like as follows

 {foreach from=$menus.main->children item="mItem"}
  <div class="mainbutton"><a href="{$mItem->link}">{$mItem->text}</a></div>
 {/foreach}

For a cascaded menu i’ve used the following

{foreach from=$menus.cats->children item='cat'}
  <div class="item{if $cat->active || $cat->expanded}_select{/if}">
    <div class="arrow"></div>
    {if !$cat->active}<a href="{$cat->link}">{/if}{$cat->text}{if !$cat->active}</a>
    {/if}
  </div>
  {if $cat->children|@count ne 0 || $cat->expanded}
    {foreach from=$cat->children item='subCat'}
      <div class="subitem{if $subCat->active}_select{/if}">
        <div class="arrow"></div>
      {if !$subCat->active}<a href="{$subCat->link}">{/if}{$subCat->text}{if !$subCat->active}</a>{/if}
      </div>
    {/foreach}
  {/if}
  {/foreach}

As usual any comments gratefully recieved

php: Insert element at specific Index of Array.

In a recent project I’ve been undertaking I’ve made a menu class set and sometimes i just wanted to say to add this to an array, but in a certain position. PHP does this easily via

$array[position] = "newdata";

But unfortunately this is not so good if you only wanted to insert the newdata into that position and move the others the out of the way. So with a little help from Derick Rethans and Tetraboy I came up with this little solution.

Any comments gratefully recieved.

function array_insert(&$array,$element,$position=null) {
  if (count($array) == 0) {
    $array[] = $element;
  }
  elseif (is_numeric($position) && $position < 0) {
    if((count($array)+position) < 0) {
      $array = array_insert($array,$element,0);
    }
    else {
      $array[count($array)+$position] = $element;
    }
  }
  elseif (is_numeric($position) && isset($array[$position])) {
    $part1 = array_slice($array,0,$position,true);
    $part2 = array_slice($array,$position,null,true);
    $array = array_merge($part1,array($position=>$element),$part2);
    foreach($array as $key=>$item) {
      if (is_null($item)) {
        unset($array[$key]);
      }
    }
  }
  elseif (is_null($position)) {
    $array[] = $element;
  }
  elseif (!isset($array[$position])) {
    $array[$position] = $element;
  }
  $array = array_merge($array);
  return $array;
}

and no code would be without it’s example:

// create the array
$x = array("apples","bananas","pears");
//insert "oranges" at position 1
array_insert($x,"oranges",1);
var_dump($x);
//insert "pineapples" 2 from the end
array_insert($x,"pineapples",-2);
var_dump($x);
//insert "strawberries" at the end
array_insert($x,"strawberries");
var_dump($x);
//insert "plums" at position 0 - (because the negative position goes beyond 0)
array_insert($x,"pineapples",-10);
var_dump($x);

or alternatively

// create the array
$x = array("apples","bananas","pears");
//insert "oranges" at position 1
$x = array_insert($x,"oranges",1);
var_dump($x);
//insert "pineapples" 2 from the end
$x = array_insert($x,"pineapples",-2);
var_dump($x);
//insert "strawberries" at the end
$x = array_insert($x,"strawberries");
var_dump($x);
//insert "plums" at position 0 - (because the negative position goes beyond 0)
$x = array_insert($x,"plums",-10);
var_dump($x);

Long Night of Editing

Recently it seems that i’ve been suffering with a distinct lack of enthusiasm for any sort of coding.

I’ve been trundling through the latest site (http://www.gamers.uk.net) which is been working well for the most part..

Over the last few days I’ve not really wanted to do any sort of work on it at all or anything else really. Friday is the deadline and so the next few nights I’m going to have to put in some late nights to get it all complete.

Things that are bugging me:

  1. Why couldn’t the client tell me about the postage when I asked them before?
  2. Why is it so difficult to get the energy to work when you work from home?

Oh well, suppose I best put myself back to work

BK