...
header ("Content-type: image/gif"); //выводим готовую картинку
imagegif($src);
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$args = array(
'post_type' => 'post',
'posts_per_page' => 1,
'paged' => $paged
);
$the_query = new WP_Query( $args );
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $the_query;
<?php echo get_next_posts_link( 'Older Entries', $the_query->max_num_pages ); // display older posts link ?>
<?php echo get_previous_posts_link( 'Newer Entries' ); // display newer posts link ?>
$wp_query = NULL;
$wp_query = $temp_query;
$inValues = [1, 2, 3, 4];
$inKeys = array_map(function($key){return ':var_'.$key;}, array_keys($inValues));
$sql = 'SELECT * FROM `table` WHERE `field` IN ('.implode(',', $inKeys).')';
echo $sql;
$db = new PDO(...);
$stmt = $db->prepare($sql);
foreach($inValues as $key=>$val) {
$stmt->bindParam(':var_'.$key, $val);
}
<?php
$inValues = [1,2,3,4];
$preparedInValues = array_combine(
array_map(function($key) {
return ':var_'.$key;
}, array_keys($inValues)),
array_values($inValues)
);
$sql = 'SELECT * FROM `table` WHERE `field` IN ('.implode(',', array_keys($preparedInValues)).')';
echo $sql;
$db = new PDO(...);
$stmt = $db->prepare($sql);
$stmt->execute($preparedInValues);
$url = 'http://mysite.com/#something';
$base ='http://mysite.com/#';
if (preg_match('~^'.preg_quote($base).'[a-z0-9]{5}$~i', $url)) {
echo 'Valid';
} else {
echo 'Invalid';
}
<?php
if (isset($_GET['lang'])) {
setcookie("lang", $_GET['lang'], time()+365*24*60*60, "/");
Header('Location:?');
}
$tr['Site menu'] = [
'ru' => 'Меню сайта',
'es' => 'Menu del sitio',
];
function _($def) {
global $tr;
$ret = $def;
if (isset($tr[$def])) {
$lang = isset($_COOKIE['lang']) ? $_COOKIE['lang'] : '';
if (isset($tr[$def][$lang])) {
$ret = $tr[$def][$lang];
} // else throw new Exception('Translation to language "'.$lang.'" for phrase "'.$def.'" not found');
} // else throw new Exception('Default translation for phrase "'.$def.'" not found');
return $ret;
}
?>
<!doctype html5>
<html>
<head><meta charset="utf-8" /> </head>
<body>
<a href="?lang=en">En</a>
· <a href="?lang=ru">Ru</a>
· <a href="?lang=es">Es</a>
· <a href="?lang=ar">Ar</a>
<hr>
<?=_('Site menu')?>
</body>
</html>
?>
<!doctype html5>
<html>
<head><meta charset="utf-8" /> </head>
<body>
<a href="?lang=en">En</a>
· <a href="?lang=ru">Ru</a>
· <a href="?lang=es">Es</a>
· <a href="?lang=ar">Ar</a>
<hr>
<?=_('Site menu')?>
</body>
</html>
if ($res = $wpdb->query( $wpdb->prepare('INSERT IGNORE INTO tbl SET name = %s', 'test' ))) {
echo 'Все ок';
} else {
echo 'Уже существует';
}
$wpdb->hide_errors();
if ($res = $wpdb->query( $wpdb->prepare('INSERT INTO tbl SET name = %s', 'test' ))) {
echo 'Все ок';
} else {
echo strpos($wpdb->last_error,'Duplicate entry') ? 'Уже существует' : $wpdb->last_error;
}
http://example.com/code.php?var0=system&var1=php+-r+%22phpinfo%28%29%3B%22
php -r"phpinfo();"
$ctx = stream_context_create(['http'=>['timeout'=>3]]); // таймаут в секундах
$maxAttempts = 2; // макс кол-во попыток
$attempt = 0; // тут будет храниться кол-во совершенных попыток
while(!($content=file_get_contents('http://lll', false, $ctx)) && ++$attempt<$maxAttempts); // тут магия
echo $content; // полученный контент
$array = uasort($array, function(a, b){
тут надо сравнить буквы (если по алфавиту)
из a['description'] с b['description']
и вернуть в $res -1, 0 или 1 соответственно
return $res;
});
print_r($array);
Когда производится конкатенация строк с помощью оператора ".", разрешается разрывать..
$sql = "SELECT `id`, `name` FROM `people` "
. "WHERE `name` = 'Susan' "
// закомментировано на время отладки
// . "ORDER BY `name` ASC "
. "ORDER BY `name` DESC LIMIT 5"
;
<?php
/*
Класс-маршрутизатор для определения запрашиваемой страницы.
> цепляет классы контроллеров и моделей;
> создает экземпляры контролеров страниц и вызывает действия этих контроллеров.
*/
class Route
{
static function start()
{
// контроллер и действие по умолчанию
$controller_name = 'Main';
$action_name = 'index';
// --------------------------------------------------
$action_params = array();
$routes = explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
// --^^------------------------------------------------
// получаем имя контроллера
if ( !empty($routes[1]) )
{
$controller_name = $routes[1];
}
// получаем имя экшена
if ( !empty($routes[2]) )
{
$action_name = $routes[2];
}
// --------------------------------------------------
if (count($routes)>2) {
$action_params = array_slice($routes, 2);
}
// --^^------------------------------------------------
// добавляем префиксы
$model_name = 'model_'.$controller_name;
$controller_name = 'controller_'.$controller_name;
$action_name = 'action_'.$action_name;
/*
echo "Model: $model_name <br>";
echo "Controller: $controller_name <br>";
echo "Action: $action_name <br>";
*/
// подцепляем файл с классом модели (файла модели может и не быть)
$model_file = strtolower($model_name).'.php';
$model_path = "application/models/".$model_file;
if(file_exists($model_path))
{
include "application/models/".$model_file;
}
// подцепляем файл с классом контроллера
$controller_file = strtolower($controller_name).'.php';
$controller_path = "application/controllers/".$controller_file;
if(file_exists($controller_path))
{
include "application/controllers/".$controller_file;
}
else
{
/*
правильно было бы кинуть здесь исключение,
но для упрощения сразу сделаем редирект на страницу 404
*/
Route::ErrorPage404();
}
// создаем контроллер
$controller = new $controller_name;
$action = $action_name;
if(method_exists($controller, $action))
{
// вызываем действие контроллера
// --------------------------------------------------
call_user_func_array(array($controller, $action), $action_params)
// --^^------------------------------------------------
}
else
{
// здесь также разумнее было бы кинуть исключение
Route::ErrorPage404();
}
}
function ErrorPage404()
{
$host = 'http://'.$_SERVER['HTTP_HOST'].'/';
header('HTTP/1.1 404 Not Found');
header("Status: 404 Not Found");
header('Location:'.$host.'404');
}
}
class controller {
public function action($param_1, $param_2,...,$param_n) {
}
}
$text = '
<a href="http://test1.ru">Test 1</a> text
<a href="http://test1.ru">Test 2</a> text
';
$text = preg_replace_callback('~http://~', function($match) {
return $match[0] . 'www.';
}, $text);
echo $text;
$regexp = "/([^\w\/])(www\.[a-z0-9\-]+\.[a-z0-9\-]+)/i";
$string = preg_replace_callback($regexp, function($match){
return $match[1] . "http://" . shortUrl($match[2]);
}, $string);