php / PHP программистский фольклор
$hash=md5($_GET["user_id"]."huy_sosayete");
на реальном проекте
2010-09-09 17:39:48
$hash=md5($_GET["user_id"]."huy_sosayete");
$file = $_GET['file'];
if (substr($file, -4, 4) !== ".doc")
die();
$file=iconv("UTF-8", "windows-1251", $file);
if (!file_exists("./".$file))
die();
header('Content-type: application/doc');
header('Content-Disposition: attachment; filename="'.$file.'"');
readfile($file);
$obj = new SomeClass(); //Total time: 678 µs //+ 100 % $obj =& new SomeClass(); //Total time: 709 µs //+ 105 %
for($i = 0; $i < 1000000; ++$i); //Total time: 115263 µs //+ 100 % $i = 0; while($i < 1000000) ++$i; //Total time: 117311 µs //+ 102 %
class Object {
function Object(){
...
}
...
}
class AdminObject extends Object
{
function AdminObject() {
$par = get_parent_class($this);
$this->$par();
}
...
}
<?php $a = 't9'; echo ++$a; ?>
$ php -r '$a=true; !$a && $r=9; echo $r;'
PHP Notice: Undefined variable: r in Command line code on line 1
Но если
$ php -r '$a=false; !$a && $r=9; echo $r;'
9
Что в принципе аналогично:
$a=true;
if ($a) {
$r=9;
}
echo $r;
/**
* @access public
* @return string
*/
function getSql()
{
if( !$criteria = $this->criteria )
{
error_log('...');
return '';
}
return $this->criteria->getQuery();
}
if (65=0)
{
printf("Ребят, тут ваще не реальная фигня какая-то случилась\n");
exit(0);
}
<?
function downloadFile($filename, $mimetype='application/octet-stream') {
if (!file_exists($filename)) die('Нет файла');
$from=$to=0; $cr=NULL;
if (isset($_SERVER['HTTP_RANGE'])) {
$range=substr($_SERVER['HTTP_RANGE'], strpos($_SERVER['HTTP_RANGE'], '=')+1);
$from=strtok($range, '-');
$to=strtok('/'); if ($to>0) $to++;
if ($to) $to-=$from;
header('HTTP/1.1 206 Partial Content');
$cr='Content-Range: bytes ' . $from . '-' . (($to)?($to . '/' . $to+1):filesize($filename));
} else header('HTTP/1.1 200 Ok');
$etag=md5($filename);
$etag=substr($etag, 0, 8) . '-' . substr($etag, 8, 7) . '-' . substr($etag, 15, 8);
header('ETag: "' . $etag . '"');
header('Accept-Ranges: bytes');
header('Content-Length: ' . (filesize($filename)-$to+$from));
if ($cr) header($cr);
header('Connection: close');
header('Content-Type: ' . $mimetype);
header('Last-Modified: ' . gmdate('r', filemtime($filename)));
$f=fopen($filename, 'r');
header('Content-Disposition: attachment; filename="' . basename($filename) . '";');
if ($from) fseek($f, $from, SEEK_SET);
if (!isset($to) or empty($to)) {
$size=filesize($filename)-$from;
} else {
$size=$to;
}
$downloaded=0;
while(!feof($f) and !connection_status() and ($downloaded<$size)) {
echo fread($f, 512000);
$downloaded+=512000;
flush();
}
fclose($f);
}
///
$f=$_GET[f];
downloadFile($f);
?>
class A {
private $_d = array();
public function __construct(){
$this->_d = 'A';
}
public function __toString(){
return $this->_d;
}
}
class B extends A {
public function __construct(){
parent::__construct();
$this->_d = 'B';
}
}
$b = new B();
echo $b,"\n";
abstract class RecessConf {
...
if(self::$useTurboSpeed) {
Library::$useNamedRuns = true;
$cacheProvidersReversed = array_reverse(self::$cacheProviders);
foreach($cacheProvidersReversed as $provider) {
$provider = $provider . 'CacheProvider';
Cache::reportsTo(new $provider);
}
}
...
}
function Y($F) {
$func = function ($f) { return $f($f); };
return $func(function ($f) use($F) {
return $F(function ($x) use($f) {
$ff = $f($f);
return $ff($x);
});
});
}
class SomeObjectActions extends sfActions
{
public function executeShowObject(sfWebRequest $request){
...
$this->getResponse()->setTitle($this->object->getMetaTitle());
$this->getResponse()->addMeta('meta_keywords', $this->object->getMetaKeywords());
$this->getResponse()->addMeta('meta_description', $this->object->getMetaDescription());
}
}
class changeLayoutFilter extends sfFilter
{
public function execute($filterChain)
{
// Execute this filter only once
if ($this->isFirstCall())
{
// Filters don't have direct access to the request and user objects.
// You will need to use the context object to get them
$request = $this->getContext()->getRequest();
$user = $this->getContext()->getUser();
//устанавливаю layuot
if(isNY()){
sfConfig::set('symfony.view.'.
$this->getContext()->getModuleName().'_'.
$this->getContext()->getActionName().'_layout',
'your_layout');
}
}
// Execute next filter
$filterChain->execute();
}
}
/**
* sfValidatorTelephone
*
* @package
* @subpackage validator
* @author broderix
* @version
*/
class sfValidatorTelephone extends sfValidatorRegex
{
/**
* @see sfValidatorRegex
*/
protected function configure($options = array(), $messages = array())
{
parent::configure($options, $messages);
$this->setOption('pattern', '/^(\+\d\(\d+\)\d*)$/i');
}
}
require __DIR__.'/c.php';
if (!is_callable($c = @$_GET['c'] ?: function() { echo 'Woah!'; }))
throw new Exception('Error');
$c();
<?php
abstract class Graphic{
abstract public function draw();
}
class Triangle extends Graphic{
private $name = '';
public function __construct($name = 'unknown'){
$this->name = $name;
}
public function draw(){
echo '-I\'m a triangle '.$this->name.'.<br>';
}
}
class Container extends Graphic{
private $name = '';
private $container = array();
public function __construct($name = 'unknown'){
$this->name = $name;
}
public function draw(){
echo 'I\'m a container '.$this->name.'.<br>';
foreach($this->container as $graphic)
$graphic->draw();
}
public function add(Graphic $graphic){
$this->container[] = $graphic;
}
public function del(Graphic $graphic){
unset($this->container[$graphic]);
}
}
$tri1 = new Triangle('1');
$tri2 = new Triangle('2');
$tri3 = new Triangle('3');
$container1 = new Container('1');
$container2 = new Container('2');
$container3 = new Container('3');
$container1->add($tri1);
$container1->add($tri2);
$container2->add($tri3);
$container3->add($container1);
$container3->add($container2);
$container3->draw();
?>
Результатом будет:
I'm a container 3.
I'm a container 1.
-I'm a triangle 1.
-I'm a triangle 2.
I'm a container 2.
-I'm a triangle 3.
<?php
class Example
{
// Параметризированный фабричный метод
public static function factory($type)
{
if (include_once 'Drivers/' . $type . '.php') {
$classname = 'Driver_' . $type;
return new $classname;
} else {
throw new Exception ('Драйвер не найден');
}
}
}
//Использование
interface Driver_Interface {
}
class Drivers_MYSQL_PDO implements Driver_Interface {
}
$db = Example::factory("MYSQL_PDO");
?>
<?php
class Example
{
// Содержит экземпляр класса
private static $instance;
// Закрытый конструктор; предотвращает прямой доступ к
// созданию объекта
private function __construct()
{
echo 'Я конструктор';
}
// Метод синглтон
public static function singleton()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
// Метод для примера
public function bark()
{
echo 'Гав!';
}
// Предотвращает клонирование экземпляра класса
public function __clone()
{
trigger_error('Клонирование запрещено.', E_USER_ERROR);
}
}
?>
// Пример работы
// Позволяет вернуть единственный экземпляр класса Example
<?php
// Такой вариант завершится неудачей, так как конструктор
// объявлен как private
$test = new Example;
// Это всегда возвращает единственный экземпляр класса
$test = Example::singleton();
$test->bark();
// Это вызовет ошибку E_USER_ERROR.
$test_clone = clone $test;
?>
$mq = mysql_connect("localhost", "user", "pass");
mysql_select_db("name_db");
$str = "username=vasya; userpass=1234; age=34";
$ex = explode("; ", $str);
foreach ($ex as $exp) {
$expl = explode("=", $exp);
if ($expl[0]=="username") { $username = $expl[1];}
if ($expl[0]=="userpass") { $userpass = $expl[1];}
if ($expl[0]=="age") { $age = $expl[1];}
}
$sql = "SELECT username FROM `name_db` WHERE username='$username'";
$result = mysql_query($sql);
for ($data=array(); $row = mysql_fetch_assoc($result); $data[]=$row);
if (!isset($data['username'])){
$sql_i = "INSERT INTO `name_db` VALUES ('$username', '$userpass', '$age')";
$result_i = mysql_query($sql_i);
} else {
$sql_u = "UPDATE `name_db` SET userpass='$userpass', age='$age' WHERE username='$username'";
$result_u = mysql_query($sql_u);
}
class Router extends Object {
protected $aConfigRoute=array();
static protected $sAction=null;
static protected $sActionEvent=null;
static protected $sActionClass=null;
static protected $aParams=array();
protected $oAction=null;
protected $oEngine=null;
static protected $bShowStats=true;
static protected $oInstance=null;
/**
* Делает возможным только один экземпляр этого класса
*
* @return Router
*/
static public function getInstance() {
if (isset(self::$oInstance) and (self::$oInstance instanceof self)) {
return self::$oInstance;
} else {
self::$oInstance= new self();
return self::$oInstance;
}
}
...
}
if ($____) $_____ = ____($_____); $_______++; $____ = ''; return $_____;
echo true*10; //10 echo false/2; //0
secure_login($params){
if($this->authorized){
return true;
} else {
return false;
}
//на всякий случай
return false;
}