Personal notes on software development.
For Java technologies check my dedicated site

Pages

Arrays


//array
$team = array('Bill', 'Joe', 'Mike', 'Chris', 'Jim');
echo $team[3]; // Displays the name Chris

//Two-dimensional arrays
$oxo = array(array('x', '', 'o'),
        array('o', 'o', 'x'),
        array('x', 'o', '' ));
echo $oxo[1][2];

Casts

There's no need for casts in PHP. PHP is a very loosely typed language. This means that variables do not have to be declared before they are used, and that PHP always converts variables to the type required by their context when they are accessed.

For example, you can create a multiple-digit number and extract the nth digit from it simply by assuming it to be a string:
<?php
    $number = 12345 * 67890;
    echo substr($number, 3, 1);
?>
At the point of the assignment, $number is a numeric variable. But on the second line, a call is placed to the PHP function substr, which asks for one character to be returned from $number, starting at the fourth position. To do this, PHP turns $number into a nine-character string, so that substr can access it and return the character, which in this case is 1.

Classes/Objects

Example:
<?php
class Produto
{
    public $codigo;
    public $nome;
    public $quantidade;

    /**
        * Construtor
        */
    public function __construct( $codigo, $nome, $quantidade )
    {
        $this->codigo = $codigo;
        $this->nome = $nome;
        $this->quantidade = $quantidade;
    }
}

$produto1 = new Produto( 1, "CD Nine Inch Nails – With Teeth", 4 );
$produto2 = new Produto( 2, "CD A Perfect Circle – Mer De Noms", 3 );
//access properties outside the object like this:
$temp = $produto1->codigo;
?>
Other info/examples here.

Constants

Set a constant:
define("ROOT_LOCATION", "/usr/local/www/");
To read the contents of the constant just refer to it like a regular variable (but
it isn’t preceded by a dollar sign):
$directory = ROOT_LOCATION;

Note: It is generally agreed to be good practice to use only uppercase for constans.
names

Database

If you use inline SQL on you PHP, it may be a good ideia to encapsulate some functionality like:
function db_connect() {
//NOTA: a @ antes de uma função impede que sejam mostrados os erros 
//ou warnigs que podem advir da sua chamada
    $pgsql_conn = @pg_connect("dbname=name port=5432 host=localhost user=postgres password=xxxx");
    if($pgsql_conn) return $pgsql_conn;
    
    setMsgErro("Erro de comunicação.");
    return 0;
}

function executaSQL($sql) {
    $link = db_connect();
    if($link) {
        return pg_query($link, $sql ); //pg_query returns FALSE if an error occurs
    }
    
    setMsgErro("Erro de comunicação.");
    return 0;
}

PHP functions for postgres.
  •  pg_affected_rows() returns the number of tuples (instances/records/rows) affected by INSERT, UPDATE, and DELETE queries;
    Exemplo:
    function deleteColeccao($id) {
        $id = sanitizePostgres($id);
        $sql="delete from coleccao where id_coleccao='".$id."';";
        $res = executaSQL($sql);
        if(pg_affected_rows($res) > 0) {
            setMsgSucesso("Colecção eliminada.");
            return 1;
        }
    
        setMsgErro("Erro ao eliminar colecção.");
        return 0;
    }



Documentation

PHPDoc is an adaptation of Javadoc for the PHP programming language. It is a formal standard for commenting PHP code. It allows external document generators like phpDocumentor to generate documentation of APIs and helps some IDEs such as Zend Studio, NetBeans, ActiveState Komodo Edit and IDE and Aptana Studio to interpret variable types and other ambiguities in the loosely typed language and to provide improved code completion, type hinting and debugging.

Tag Information:
Start it with /**
  • @var [type]
    type is the type of a class variable. Default is "mixed" if not included. Use this tag to document variables with type restrictions.
  • @return [type] [description]
    type is the type of a value returned from a method or function.
    description a brief description of the value returned
  • @param [type] [$varname] [description]
Example:
/**
* return the day of the week
*
* @param string $month 3-letter Month abbreviation
* @param integer $day day of the month
* @param integer $year year
* @return integer 0 = Sunday, value returned is from 0 (Sunday) to 6 (Saturday)
*/
function day_week($month, $day, $year)
{
...
}
More info/examples here or here.

echo Vs print

The two commands are quite similar to each other, but print is an actual function that takes a single parameter, whereas echo is a PHP language construct.

The echo command will be a tad faster than print in general text output, because, not being a function, it doesn’t set a return value.

On the other hand, because it isn’t a function, echo cannot be used as part of a more
complex expression, whereas print can, example:
$b ? print "TRUE" : print "FALSE";

Form handling

Post Request

The $_POST associative array contains an element for each field in an HTML form. In the next example the input name used was name and the form method was post, so element name of the $_POST array contains the value in $_POST['name']:
<?php
  if (isset($_POST['name'])) $name = $_POST['name'];
  else $name = "(Not entered)";
  echo <<<_END
    <html>
    <head>
      <title>Form Test</title>
    </head>
    <body>
      Your name is: $name<br />
      <form method="post" action="">
        What is your name?
        <input type="text" name="name" />
        <input type="submit" />
      </form>
    </body>
  </html>
  _END;
?> 
Note: has a security measure you shouldn't use only$variable = $_POST['user_input']; but combine this with some functions to remove potential treats (like mysql_real_escape_string(); stripslashes(); htmlentities(); etc.). See security section for more information about this.

Get Requests

Accessing the Get Request key and values (source)
<?php
 $j = "";
 print("Lets retrieve all the variables submitted to this ");
 print("script via a GET request:<br>");
 foreach($_GET as $key => $i){
     print("$key=$i<br>");
 }
 if($_GET['Submit'] == "Send GET Request")
     $j = "done!<br>";
?>
<form method="GET">
     Name: <input name="name"><br>
     Email: <input name="email" size="25"><br>
     <input name="Submit" type="submit" value="Send GET Request">
</form>

Checking whether a form has already been submitted

You can achieve this by adding some HTML in your PHP code, such as the following:
echo '<input type="hidden" name="submitted" value="yes" />'
This is a simple PHP echo statement that adds an input field to the HTML form. Let’s assume the form was created outside the program and displayed to the user. The first time the PHP program receives the input, this line of code has not run, so there will be no field named submitted. The PHP program recreates the form, adding the input field.
So when the visitor resubmits the form, the PHP program receives it with the submitted field set to “yes”. The code can simply check whether the field is present:
if (isset($_POST['submitted']))
{...


Loops

foreach (source)

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).

The second form does the same thing (the value of the current element is assigned to $value )  and the current element's key is also assigned to the variable $key on each loop.

Security

Regardless of what constraints you have placed in an HTML form to limit the types and sizes of inputs, it is a trivial matter for a hacker to use their browser’s View Source feature to extract the form and modify it to provide malicious input to your website.

Therefore you must never trust any variable that you fetch from either the $_GET or $_POST arrays until you have processed it. If you don’t, users may try to inject JavaScript into the data to interfere with your site’s operation, or even attempt to add MySQL commands to compromise your database.

Therefore, instead of just using code such as the following when reading in user input:
$variable = $_POST['user_input'];
you should also use one or more of the following lines of code:
//prevent escape characters being injected into a string that will be presented 
//to MySQL 
$variable = mysql_real_escape_string($variable);

//get rid of unwanted slashes, use:
$variable = stripslashes($variable);

//remove any HTML from a string, use the following:
$variable = htmlentities($variable);
(HTML code like <b>hi</b> is converted into &lt;b&gt;hi&lt;/b&gt;, which displays 
as text, and won’t be interpreted as HTML tags.)

//strip HTML entirely from an input, use the following:
$variable = strip_tags($variable);

Use the right combination of the above functions depending on you application. A general template is:
<?php
  function sanitizeString($var)
  {
    $var = stripslashes($var);
    $var = htmlentities($var);
    $var = strip_tags($var);
    return $var;
  }
  function sanitizeMySQL($var)
  {    //For postgres use pg_escape_string instead:
    $var = mysql_real_escape_string($var);
    $var = sanitizeString($var);
    return $var;
  }
?> 
<?php
  $variable = sanitizeString($_POST['user_input']);
  //Or, when you have an open MySQL connection:
  $variable = sanitizeMySQL($_POST['user_input']);
?>

Properly encode and decode query strings (source):
<?php
  $query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
  echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?> 
Note:
A reminder: if you are considering using urldecode() on a $_GET variable, DON'T! The webserver will arrange for $_GET to have been urldecoded once already by the time it reaches you!
//BAD CODE! DO NOT USE!
$term = urldecode($_GET['sterm']);

//Good PHP:
$term = $_GET['sterm'];

The next 2 functions do the exact same thing, remove extra spaces from a string:
  #remove extra spaces
  function removeExtraSpaces($str){
    // use two spaces for the seperator
    $str = trim($str);
    while (sizeof ($array=explode ("  ",$str)) != 1){
        // use one space for the glue
        $str = implode (" ",$array);        
    }
    return $str;
}

function removeExtraSpaces2($str){  $str preg_replace('/\s\s+/'' '$str);
}


Strings

String concatenation

echo "You have " . $msgs . " messages.";
$bulletin .= $newsflash;

String types

PHP supports two types of strings that are denoted by the type of quotation mark: '' or "".
If you wish to assign a literal string, preserving the exact contents, you should use the single quotation mark (apostrophe) like this:
$info = 'Preface variables with a $ like this: $variable';

In this case, every character within the single-quoted string is assigned to $info. If you had used double quotes, PHP would have attempted to evaluate $variable as a variable.
On the other hand, when you want to include the value of a variable inside a string, you do so by using double-quoted strings:
echo "There have been $count presidents of the US";

This syntax also offers a simpler form of concatenation in which you don’t need to use a period, or close and reopen quotes, to append one string to another. This is called variable substitution.

Escaping characters

Insert a backslash directly before the offending quotation mark to tell PHP to treat the character literally and not to interpret it:
$text = "My Mother always said \"Eat your greens\".";

Additionally you can use escape characters to insert various special characters into
strings such as tabs, new lines, and carriage returns. These are represented, as you might
guess, by \t, \n, and \r.
Alternatively the code above code be replaced with:
$text = 'My Mother always said "Eat your greens".";

These special backslash-preceded characters work only in double-quoted strings. Within single-quoted strings, only the escaped apostrophe (\') and escaped backslash itself (\\) are recognized as escaped characters.

Output Multiple-Line Commands

There are times when you need to output quite a lot of text from PHP and using severalecho (or print) statements would be time-consuming and messy. To overcome this, PHP offers two conveniences:
  • put multiple lines between quotes:
    <?php
        $author = "Alfred E Newman";
        $text = "This is a Headline
            This is the first line.
            This is the second.
            Written by $author.";
    ?>
  • PHP also offers a multiline sequence using the <<< operator, commonly referred to as here-document or heredoc for short, and is a way of specifying a string literal, preserving the line breaks and other whitespace (including indentation) in the text:
    <?php
        $author = "Alfred E Newman";
        echo <<<_END
            This is a Headline
            This is the first line.
            This is the second.
            Written by $author.
        _END;
    ?>
    What this code does is tell PHP to output everything between the two _END tags as if it were a double-quoted string. This means it’s possible, for example, for a developer to write entire sections of HTML directly into PHP code and then just replace specific dynamic parts with PHP variables.
    It is important to remember that the closing _END; tag must appear right at the start of a new line and it must be the only thing on that line—not even a comment is allowed to be added after it (nor even a single space). Once you have closed a multiline block, you are free to use the same tag name again.

    The same syntax can also be used  to assign multiple lines to a variable:
    <?php
        $author = "Alfred E Newman";
        $out = <<<_END        This is a Headline
            This is the first line.
            This is the second.
           Written by $author.
    _END;?>
    

    Note: the _END tag is simply one I chose for these examples because it is unlikely to be used anywhere else in PHP code and is therefore unique. But you can use any tag you like such as _SECTION1 or _OUTPUT and so on. Also, to help differentiate tags such as this from variables or functions, the general practice is to preface them with an underscore, but you don’t have to use one if you choose not to.

This Vs Self

parent::member() is used to call a base class member function. Consequently, you could also use self::member() to call a non-static member function, though in most cases it would be better to use $this->member() so that polymorphism will work. As such, unless you specifically do not want a derived class member function override to work, use $this->member() for non-static member functions, reserving self::member() for static member functions.
Here is an example of correct usage of $this and self for non-static and static member variables:
<?php
class X {
    private $non_static_member = 1;
    private static $static_member = 2;

    function __construct() {
        echo $this->non_static_member . ' '
           . self::$static_member;
    }
}

new X();
?> 

Here is an example of polymorphism with $this for member functions:
<?php
class X {
    function foo() {
        echo 'X::foo()';
    }

    function bar() {
        $this->foo();
    }
}

class Y extends X {
    function foo() {
        echo 'Y::foo()';
    }
}

$x = new Y();
$x->bar();
?> 

Here is an example of suppressing polymorphic behaviour by using self for member functions:
<?php
class X {
    function foo() {
        echo 'X::foo()';
    }

    function bar() {
        self::foo();
    }
}

class Y extends X {
    function foo() {
        echo 'Y::foo()';
    }
}

$x = new Y();
$x->bar();
?>  
For more details visit this discussing thread.

No comments:

Post a Comment