Удаление из MYSQL записи символа \n
UPDATE tbl set pole = REPLACE(pole, CAST(0x0d AS CHAR), '')
4 ноября 2014, 07:12
UPDATE tbl set pole = REPLACE(pole, CAST(0x0d AS CHAR), '')
kldload pf kldstat echo 'pf_enable="YES"' >> /etc/rc.conf
if="em0" pass in on $if proto tcp from any to $if port ssh flags S/SA keep state (max-src-conn-rate 3/60, overload <ssh-bruteforce> flush global) block drop in quick on $if from <ssh-bruteforce> #обязательно оставьте пустую строку в конце файла
pfctl -e pfctl -f /etc/pf.conf
cd /usr/ports/security/expiretable make install clean rehash
*/5 * * * * root /usr/local/sbin/expiretable -t 3600 ssh-bruteforce
who
last
w
csup -h cvsup6.freebsd.org /usr/share/examples/cvsup/ports-supfile
csup -h cvsup6.freebsd.org /usr/share/examples/cvsup/stable-supfile
:wq






ssh -N -D 9999 root@server_ip
git clone git+ssh://git-user@git-host.com:1111/rep.git rep
fetch https://github.com/downloads/glk/pefs/pefs-2011-04-14.tar.gz tar -xvf pefs-2011-04-14.tar.gz cd pefs-2011-04-14 make
===> sys/modules/pefs (all)
"Makefile", line 11: Malformed conditional (${MACHINE_CPUARCH} == "i386" || ${MACHINE_CPUARCH} == "amd64")
"Makefile", line 14: if-less endif
make: fatal errors encountered -- cannot continue
*** Error code 1
.if ${MACHINE_CPUARCH} == "i386" || ${MACHINE_CPUARCH} == "amd64"
SRCS+= pefs_aesni.c
CFLAGS+= -DPEFS_AESNI
.endif
#.if ${MACHINE_CPUARCH} == "i386" || ${MACHINE_CPUARCH} == "amd64"
SRCS+= pefs_aesni.c
CFLAGS+= -DPEFS_AESNI
#.endif
make install clean rehash
mkdir /secret pefs mount /secret /secret pefs addkey /secret
echo 'test' > /secret/file.txt
cat /secret/file.txt
pefs unmount /secret
cat /secret/file.txt
pefs mount /secret /secret pefs addkey /secret
cat /secret/file.txt
var A = new Object; var B = A; A['value'] = 1; alert(B['value']);
var A = new Object;
var B = jQuery.extend({}, A);
server {
listen 80;
server_name your.site.ru;
charset utf-8;
root /usr/local/www/nginx/build;
index index.html index.htm index.php;
location / {
try_files $uri $uri/ /index.php?$args;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/local/www/nginx-dist;
}
location ~ \w+\.php$ {
#вот тут лучше заменить на юникс сокет
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_script_name;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
location ~ /\.ht {
deny all;
}
location ~ ^/protected/ {
deny all;
}
}
cd /usr/ports/textproc/sphinxsearch make install clean rehash
## Конфигурационный файл Sphinx-а для индексации LiveStreet
#######################
#
# Описываем индексы
#
#######################
# Источник-родитель для всех остальных источников. Здесь указываются параметры доступа
# к базе данных сайта
source lsParentSource
{
type = mysql
sql_host = localhost
sql_user = user
sql_pass = pass
sql_db = livestreet
sql_port = 3306
# Для ускорения работы прописываем путь до MySQL-го UNIX-сокета (чтобы
# операции с БД происходили не через TCP/IP стек сервера)
sql_sock = /var/run/mysqld/mysqld.sock
mysql_connect_flags = 32 # 32- включение сжатие при обмене данными с БД
# Включам нужную кодировку соединения и выключаем кеш запросов
sql_query_pre = SET NAMES utf8
sql_query_pre = SET SESSION query_cache_type=OFF
}
# Источник топиков
source topicsSource : lsParentSource
{
# запрос на получения данных топиков
sql_query = \
SELECT t_fast.topic_id, t_fast.topic_title, UNIX_TIMESTAMP(t_fast.topic_date_add) as topic_date_add, \
tc.topic_text, t_fast.topic_publish \
FROM prefix_topic as t_fast, prefix_topic_content AS tc \
WHERE t_fast.topic_id=tc.topic_id AND t_fast.topic_id>=$start AND t_fast.topic_id<=$end
# запрос для дробления получения топиков на неколько итераций
sql_query_range = SELECT MIN(topic_id),MAX(topic_id) FROM prefix_topic
# сколько получать объектов за итерацию
sql_range_step = 1000
# Указываем булевый атрибут критерия "топик опубликован". Для возможности указания этого критерия при поиске
sql_attr_uint = topic_publish
# Атрибут даты добавления, типа "время"
sql_attr_timestamp = topic_date_add
# мульти-аттрибут "теги топика"
sql_attr_multi = uint tag from query; SELECT topic_id, topic_tag_id FROM prefix_topic_tag
sql_ranged_throttle = 0
}
# Источник комментариев
source commentsSource : lsParentSource
{
sql_query = \
SELECT comment_id, comment_text, UNIX_TIMESTAMP(comment_date) as comment_date, comment_delete \
FROM prefix_comment \
WHERE target_type='topic' AND comment_id>=$start AND comment_id<=$end AND comment_publish=1
sql_query_range = SELECT MIN(comment_id),MAX(comment_id) FROM prefix_comment
sql_range_step = 5000
sql_attr_uint = comment_delete
sql_attr_timestamp = comment_date
}
#######################
#
# Описываем индексы
#
#######################
index topicsIndex
{
# Источник, который будет хранить данный индекса
source = topicsSource
path = /var/lib/sphinx/topicIndex
# Тип хранения аттрибутов
docinfo = extern
mlock = 0
# Используемые морфологические движки
morphology = stem_enru
# Кодировака данных из источника
charset_type = utf-8
# Из данных источника HTML-код нужно вырезать
html_strip = 1
html_remove_elements = style, script, code
}
# Индекс комментариев
index commentsIndex
{
source = commentsSource
path = /var/lib/sphinx/commentsIndex
docinfo = extern
mlock = 0
morphology = stem_enru
charset_type = utf-8
# Из данных источника HTML-код нужно вырезать
html_strip = 1
html_remove_elements = style, script, code
}
#######################
#
# Настройки индексатора
#
#######################
indexer
{
# Лимит памяти, который может использавать демон-индексатор
mem_limit = 128M
}
#######################
#
# Настройка демона-поисковика
#
#######################
searchd
{
# Адрес, на котором будет прослушиваться порт
address = 127.0.0.1
# Ну и собственно номер порта демона searchd
port = 3312
# Лог-файл демона
log = /var/log/sphinx/searchd.log
# Лог поисковых запросов. Если закомментировать,то логировать поисковые строки не будет
query_log = /var/log/sphinx/query.log
# Время в секундах, которое ждет демон при обмене данными с клиентом. По исчерпании происходит разрыв коннекта
read_timeout = 5
# Максимальное количество одновременно-обрабатываемых запросов. 0 означает дофига, а точнее без ограничения
max_children = 100
# Файл, в который сохраняется PID-процесса при запуске
pid_file = /var/log/sphinx/searchd.pid
} indexer --all searchd
0 * * * * root /usr/local/bin/indexer --rotate topicsIndex > /dev/null 2>&1 */30 * * * * root /usr/local/bin/indexer --rotate commentsIndex > /dev/null 2>&1
uname -a
rpm -ihv http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-4.noarch.rpm rpm -ihv http://download.fedora.redhat.com/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm
rpm -ihv http://centos.alt.ru/repository/centos/5/i386/centalt-release-5-3.noarch.rpm rpm -ihv http://centos.alt.ru/repository/centos/5/x86_64/centalt-release-5-3.noarch.rpm
rpm -ivh http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el5.rf.i386.rpm rpm -ivh http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
wget http://www.sno.phy.queensu.ca/~phil/exiftool/Image-ExifTool-8.59.tar.gz tar -xvf Image-ExifTool-8.59.tar.gz cd Image-ExifTool-8.59 perl Makefile.PL make make test make install
<?php
$file = 'file.mp3';
$json = array();
exec('/usr/local/bin/exiftool -j \''.escapeshellarg($file).'\'', $json);
$json = json_decode(implode($json));
$json = $json[0];
echo $json->AudioBitrate;
//ну и посмотрим какая информация вообще доступна
print_r($json);
?>
stdClass Object
(
[SourceFile] => /file.mp3
[ExifToolVersion] => 8.59
[FileName] => 11001.mp3
[Directory] => /
[FileSize] => 3.2 MB
[FileModifyDate] => 2011:05:25 14:27:58+04:00
[FilePermissions] => rw-rw-rw-
[FileType] => MP3
[MIMEType] => audio/mpeg
[MPEGAudioVersion] => 1
[AudioLayer] => 3
[AudioBitrate] => 128 kbps
[SampleRate] => 44100
[ChannelMode] => Stereo
[MSStereo] => Off
[IntensityStereo] => Off
[CopyrightFlag] =>
[OriginalMedia] =>
[Emphasis] => None
[Duration] => 0:03:27 (approx)
)
git reset --hard HEAD git pull
<?php
$factorial = function($n) use (&$factorial) {
if ($n == 0)
return 1;
return $factorial($n - 1) * $n;
};
echo $factorial(4); // 1*2*3*4=24
?>
<?php
echo Curl::init('http://ya.ru')
->referer('http://snippets.pp.ru')
->cookie('cookie.txt')
->exec();
class Curl {
static $cookie;
static $proxy;
static $ua = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.1.7) Gecko/20091221 MRA 5.5 (build 02842) Firefox/3.6.7 (.NET CLR 3.5.30729)';
static $accept = array(
'Accept' => 'application/xhtml+voice+xml;version=1.2, application/x-xhtml+voice+xml;version=1.2, text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/JPEG, image/gif, image/x-xbitmap, *\\/*;q=0.1',
'Accept-Language' => 'ru, en',
'Accept-Charset' => 'windows-1251, utf-8, utf-16, iso-8859-1;q=0.6, *;q=0.1',
'Accept-Encoding' => 'gzip,deflate',
);
private $ch; //идентификатор соединения
protected static $instance; //переменная для singleton
private $info; //переменная для информации о соеденении
private $file; //переменная для файла
//функция для инициализации
public static function init($url='') {
return (self::$instance === null) ?
self::$instance = new self($url) :
self::$instance;
}
//конструктор
function __construct($url) {
$this->ch = curl_init();
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
if ($url)
$this->url($url);
return self::$instance;
}
//деструктор, закрывает соединение
function __destruct() {
if (!is_null(self::$instance))
$this->close();
}
//обертка для сохранения файла
function file($save) {
curl_setopt($this->ch, CURLOPT_FILE, $this->file = fopen($save, 'w+b'));
return self::$instance;
}
//обертка для закрытия соединения
function close() {
curl_close($this->ch);
if (!is_null($this->file)) {
fclose($this->file);
$this->file = null;
}
return self::$instance = null;
}
//обертка для задания url
function url($url) {
curl_setopt($this->ch, CURLOPT_URL, $url);
return self::$instance;
}
//обертка для установки прокси
function proxy($proxy) {
curl_setopt($this->ch, CURLOPT_PROXY, $proxy);
return self::$instance;
}
//обертка для установки редиректов
function followlocation($followlocation) {
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, $followlocation);
return self::$instance;
}
//обертка для установки кукис
function cookie($cookie) {
self::$cookie = $cookie;
if ($cookie) {
curl_setopt($this->ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt($this->ch, CURLOPT_COOKIEJAR, $cookie);
}
return self::$instance;
}
//обертка для установки реферера
function referer($referer) {
curl_setopt($this->ch, CURLOPT_REFERER, $referer);
return self::$instance;
}
//обертка для получения информации о соединении
function get_info() {
return $this->info;
}
//обертка для задания пост данных $post = array();
function post($post) {
$post = http_build_query($post, null, '&');
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post);
return self::$instance;
}
//обертка для выполнения соединения
function exec($close = true) {
curl_setopt($this->ch, CURLOPT_USERAGENT, self::$ua);
if (self::$cookie)
$this->cookie(self::$cookie);
if (self::$proxy)
$this->proxy(self::$proxy);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, self::$accept);
$exec = curl_exec($this->ch);
$this->info = curl_getinfo($this->ch);
//закрываем соединение если задано
if ($close)
$this->close();
return $this->extr($exec);
}
//функция разжимает gzip/deflate
protected function extr($s) {
return (substr($s, 0, 8) == "\x1F\x8B\x08\x00\x00\x00\x00\x00") ? gzinflate(substr($s, 10)) : $s;
}
}
?>
portsnap fetch update
0 5 * * * /usr/sbin/portsnap fetch update
cd /usr/ports/lang/php5 make install clean rehash
cd /usr/ports/lang/php5-extensions make install clean rehash
echo 'php_fpm_enable="YES"' >> /etc/rc.conf
cd /usr/ports/www/nginx make install clean rehash
echo 'nginx_enable="YES"' >> /etc/rc.conf
;listen = 127.0.0.1:9000 listen = /tmp/php-fpm.sock
#user nobody;
#это число выставляется по количеству ядер вашего процессора
worker_processes 1;
#тут можно настроить логи
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
#для FreeBsd включайте это
use kqueue;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
#обозначим, что php-fpm у нас работает через юникс сокет
#лучше задавать именно так, потому что в будущем можно легко будет сменить этот параметр сразу для всех сайтов
upstream fpm {
server unix:/tmp/php-fpm.sock;
}
server {
listen 80;
server_name _;
charset utf-8;
root /home/www/site;
location / {
index index.php;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/local/www/nginx-dist;
}
location ~ \.php$ {
#здесь задается путь к обработчику php, который мы задали выше в upstream
fastcgi_pass fpm;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
#ну и на всякий случай, отдавая дань апаче, скроем его .htaccess
location ~ /\.ht {
deny all;
}
}
}
service nginx start service php-fpm start
<input type="hidden" name="check" value="" id="check" />
<script type="text/javascript">document.getElementById('check').value = 'ok'</script>
<?php if ($_POST['check'] != 'ok') die('spam'); ?>