Php
best practice
The best and safest way is to use mysql_real_escape_string() for all database before it is added to the database. This function makes all strings safe in terms of quotes and other functions that can harm your database or contain malicious code, so use it to be sure you have taken the first step against protection of your data. Another thing you can do is validate all POST and GET strings, never use $_REQUEST, and make sure all form submitted data is of the right type and value before adding it to a database query.
competency
http://www.techinterviews.com/php-interview-questions-and-answers
http://responsivewebsitepro.com/cv/ProveItPHP5TestResults.pdf
http://www.odesk-tests.net/odesk-test-answers/web-development/php-test-answers-2015.html
http://www.w3schools.com/php/php_quiz.asp
http://terrychay.com/article/php-coders.shtml
http://testsolutionok.blogspot.com/p/blog-page_19.html
http://world-earn-news.blogspot.com/p/odesk-php-5-test-answers.html
http://devaprai.blogspot.com/2014/12/php-frontend-developer-test-v2-answer.html
http://www.odesk-answers.com/php-test-2015/
php frameworks TDD and BDD
Curl
http://wiki.uniformserver.com/index.php/PHP_cURL:_GET_%26_POST
best practices
bits of code I always forget
combining $key $val into WHERE str
<syntaxhighlight> <?php $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
function array2where($arr){ $str="\n\nWHERE "; foreach($arr as $key=>$val){ $str= $str."`$key`=\"$val\" AND "; } $str=substr($str,0,-4); return $str; } echo(array2where($fruits)); ?> WHERE `d`="lemon" AND `a`="orange" AND `b`="banana" AND `c`="apple" </syntaxhighlight>
howto - store data in object instead of array
howto - change an object to an array
<syntaxhighlight> $thefile=file_get_contents("php://input"); echo $thefile; $json = $thefile; $return_obj->setJson($json); //the true parameter forces it to decode to array instead of object //$thearr = (array) json_decode($thefile) only converts the outer object $thearr = json_decode($thefile,true); </syntaxhighlight>
howto - read command line arguments
<syntaxhighlight lang="php"> <?php echo count($argv); if (count($argv)<2){ //if no command line argument echo("script requires command line argument with name of db to backup"); exit(); } $db = $argv[1]; ?> </syntaxhighlight>
howto - MYSQL -> JSON PDO
<syntaxhighlight> $sth = mysql_query("SELECT ..."); $rows = array(); while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
} print json_encode($rows); </syntaxhighlight> or better from rwky <syntaxhighlight> <?php $pdo=new PDO("mysql:dbname=database;host=127.0.0.1","user","password"); $statement=$pdo->prepare("SELECT * FROM table"); $statement->execute(); $results=$statement->fetchAll(PDO::FETCH_ASSOC); $json=json_encode($results); ?> </syntaxhighlight> as in http://stuff2get.sitebuilt.net/services/getfoodlist.php?repo=tpn&list=groceries&need=1 which gets you:
{"items":[{"stuff":"Blueberries imported or domestic org.","id":"430"},{"stuff":"Rasberries","id":"992"},{"stuff":"Strawberries, org","id":"420"},{"stuff":"Teccino herbal. Coffee, original","id":"876"},{"stuff":"Unsweetened almond milk","id":"110"}]}
<syntaxhighlight> $repo = $_GET['repo']; $list = $_GET['list']; $need = $_GET['need']; ChromePhp::log("stuff="); $sql = "SELECT stuff, id FROM `lists` WHERE repo=? AND list=? AND need=? ORDER BY stuff"; try { $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $dbh->prepare($sql); $stmt->execute(array($repo, $list, $need)); $needlist = $stmt->fetchAll(PDO::FETCH_OBJ); $dbh = null; echo '{"items":'. json_encode($needlist) .'}'; } catch(PDOException $e) { echo '{"error":{"text":'. $e->getMessage() .'}}'; } </syntaxhighlight>
howto - PDO insert
<syntaxhighlight> array( "title"=>$title "userid"=>$userid "post"=>$body ) function pdo_insert($table, $arr=array()) {
if (!is_array($arr) || !count($arr)) return false;
// your pdo connection $dbh = '...'; $bind = ':'.implode(',:', array_keys($arr)); $sql = 'insert into '.$table.'('.implode(',', array_keys($arr)).') '. 'values ('.$bind.')'; $stmt = $dbh->prepare($sql); $stmt->execute(array_combine(explode(',',$bind), array_values($arr)));
} pdo_insert($table, array('title'=>$title, 'userid'=>$user_id, 'post'=>$body)); </syntaxhighlight>
from phpeveryday <syntaxhighlight> <?php // configuration $dbtype = "sqlite"; $dbhost = "localhost"; $dbname = "test"; $dbuser = "root"; $dbpass = "admin"; // database connection $conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass); // new data $title = 'PHP Security'; $author = 'Jack Hijack'; // query $sql = "INSERT INTO books (title,author) VALUES (:title,:author)"; $q = $conn->prepare($sql); $q->execute(array(':author'=>$author,
':title'=>$title));
?> </syntaxhighlight>
howto - see if a character is in a string
you need the ! to test if $somechar==";" (strcmp returns 0 if true)
- if(!strcmp($somechar, ";")) {
- as seen in assess/wikiquiz/wikivo2db.php
to get from text area w/o losing linebreaks
- $apage=nl2br(stripslashes($_POST[apage]));
to iterate through the lines in a string
- foreach (preg_split("/(\r?\n)/", $apage) as $line)
howto - populate multi-dimensional arrays
/*multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";
$firephp->log($a, 'nearrtest');
misc
assoc array
$car["weight"] = "100kg"; $car["year"] = "2004"; $car["price"] = "7000"; $car["discount rebate"] = "12";
multidimensional array
hosted/vocab/quiz/db2egg.php: uses multidimensional arrays
- does sorting
refs
good class tutorial
get meta tag function
[http://sitebuilt.net/w/index.php?title=Comp&action=edit§ion=9 authentication script