Difference between revisions of "Php"
(18 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
===functions to know=== | |||
func_num_args() | |||
function_exists() | |||
setcookie(“OrderCookie”,34); | |||
mail($to,$subject,$body) | |||
empty() | |||
if(!empty($p)){ // if $p is not empty | |||
echo 'variable is not empty '; | |||
} else { | |||
echo 'value is null'; | |||
} | |||
unset(); | |||
isset(); | |||
if(isset($a)){ | |||
echo 'value is set '; | |||
} else { | |||
echo 'value is not set '; | |||
} | |||
trim() | |||
use for removes the whitespaces from the left part of the string. | |||
trim($a); | |||
explode () ; | |||
convert strin to array | |||
$str = "Rajeev Dhar dwivedi"; $array = explode(" ",$str); print_r($array); | |||
outPut : | |||
Array ( [0] => Rajeev [1] => Dhar [2] => dwivedi ) | |||
implode(); convert array to string | |||
$array = array( 'Rajeev' ,'Dhar','Dwived') ; | |||
echo implode(" ",$array); | |||
Output : Rajeev Dhar Dwived | |||
date() function | |||
this function use fot get date from system | |||
echo date('Y-M-d'); | |||
time() | |||
this function use for get time from system in mili second | |||
echo time(); | |||
strip_tags(); | |||
strip slashes(); | |||
mysql_real_escape_string() | |||
func_get_args(); | |||
// yes, the argument list can be empty | |||
function foo() { | |||
// returns an array of all passed arguments | |||
$args = func_get_args(); | |||
foreach ($args as $k => $v) { | |||
echo "arg".($k+1).": $v\n"; | |||
} | |||
} | |||
glob('*.php'); | |||
memory_get_usage() | |||
memory_get_peek_usage() | |||
json_encode($myvar); | |||
json_decode($myvar); | |||
wordwrap() or chunk_split() | |||
ucwords() makes every first letter of every word capital | |||
getallheaders() | |||
array_unique ( array $array [, int $sort_flags = SORT_STRING ] ) Takes an input array and returns a new array without duplicate values. | |||
array functions http://www.w3schools.com/php/php_ref_array.asp | |||
error_reporting(E_ALL); | |||
shell_exec() | |||
PHP provides useful magic constants for fetching the current line number (__LINE__), file path (__FILE__), directory path (__DIR__), function name (__FUNCTION__), class name (__CLASS__), method name (__METHOD__) and namespace (__NAMESPACE__). | |||
$fileHandle = @fopen($fileName, $writeAttributes); @symbol suppresses error messages | |||
===best practice=== | ===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. | 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. | ||
$unsafe_variable = $_POST["user-input"]; | |||
$safe_variable = mysql_real_escape_string($unsafe_variable); | |||
mysql_query("INSERT INTO table (column) VALUES ('" . $safe_variable . "')"); | |||
use PDO | |||
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name'); | |||
$stmt->execute(array('name' => $name)); | |||
foreach ($stmt as $row) { | |||
// do something with $row | |||
} | |||
print out call stack | |||
$e = new Exception; | |||
var_dump($e->getTraceAsString()); | |||
What enctype is required for file uploads to work? | |||
multipart/form-d | |||
Which of the following is used to maintain the value of a variable over different pages? | |||
session_register() | |||
What is the best way to change the key without changing the value of a PHP array element? | |||
$arr[$newkey] = $arr[$oldkey]; unset($arr[$oldkey]); | |||
===competency=== | ===competency=== | ||
http://www.techinterviews.com/php-interview-questions-and-answers | http://www.techinterviews.com/php-interview-questions-and-answers | ||
http://responsivewebsitepro.com/cv/ProveItPHP5TestResults.pdf | http://responsivewebsitepro.com/cv/ProveItPHP5TestResults.pdf |
Latest revision as of 10:58, 5 October 2015
functions to know
func_num_args() function_exists() setcookie(“OrderCookie”,34); mail($to,$subject,$body) empty()
if(!empty($p)){ // if $p is not empty echo 'variable is not empty '; } else { echo 'value is null'; }
unset(); isset();
if(isset($a)){ echo 'value is set '; } else { echo 'value is not set '; }
trim()
use for removes the whitespaces from the left part of the string. trim($a);
explode () ;
convert strin to array $str = "Rajeev Dhar dwivedi"; $array = explode(" ",$str); print_r($array); outPut :
Array ( [0] => Rajeev [1] => Dhar [2] => dwivedi )
implode(); convert array to string
$array = array( 'Rajeev' ,'Dhar','Dwived') ;
echo implode(" ",$array); Output : Rajeev Dhar Dwived
date() function
this function use fot get date from system echo date('Y-M-d');
time()
this function use for get time from system in mili second echo time();
strip_tags(); strip slashes(); mysql_real_escape_string() func_get_args();
// yes, the argument list can be empty function foo() { // returns an array of all passed arguments $args = func_get_args(); foreach ($args as $k => $v) { echo "arg".($k+1).": $v\n"; } }
glob('*.php'); memory_get_usage() memory_get_peek_usage() json_encode($myvar); json_decode($myvar); wordwrap() or chunk_split() ucwords() makes every first letter of every word capital getallheaders() array_unique ( array $array [, int $sort_flags = SORT_STRING ] ) Takes an input array and returns a new array without duplicate values. array functions http://www.w3schools.com/php/php_ref_array.asp error_reporting(E_ALL); shell_exec()
PHP provides useful magic constants for fetching the current line number (__LINE__), file path (__FILE__), directory path (__DIR__), function name (__FUNCTION__), class name (__CLASS__), method name (__METHOD__) and namespace (__NAMESPACE__).
$fileHandle = @fopen($fileName, $writeAttributes); @symbol suppresses error messages
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.
$unsafe_variable = $_POST["user-input"]; $safe_variable = mysql_real_escape_string($unsafe_variable); mysql_query("INSERT INTO table (column) VALUES ('" . $safe_variable . "')");
use PDO
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name'); $stmt->execute(array('name' => $name)); foreach ($stmt as $row) { // do something with $row }
print out call stack
$e = new Exception; var_dump($e->getTraceAsString());
What enctype is required for file uploads to work?
multipart/form-d
Which of the following is used to maintain the value of a variable over different pages?
session_register()
What is the best way to change the key without changing the value of a PHP array element?
$arr[$newkey] = $arr[$oldkey]; unset($arr[$oldkey]);
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