- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
/*
* Условия для шаблонов и не только ;)
* $content - то что проверям
* $data - то что выводим
*/
function if_set($content, $data) {
return empty($content) ? '' : stripslashes($data);
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+151
/*
* Условия для шаблонов и не только ;)
* $content - то что проверям
* $data - то что выводим
*/
function if_set($content, $data) {
return empty($content) ? '' : stripslashes($data);
}
Комментарий больше кода, и автор ещё Вам подмигивает.
+163
function utf_decode($str) {
/*static $table = array("\xD0\x81" => "\xA8", "\xD1\x91" => "\xB8",);
return preg_replace('#([\xD0-\xD1])([\x80-\xBF])#se', 'isset($table["$0"]) ? $table["$0"] : chr(ord("$2")+("$1" == "\xD0" ? 0x30 : 0x70))', $str);*/
return $str;
}
Зря закоментил такая панацея была что вы, что вы...
+168
/*
* Выводим чекбоксы :D
* $name - имя инпута чеки
* $val - тру ор фалсе
*/
function checkbox($name, $val)
{
$checked = !empty($val) ? 'checked ' : false;
return "<input type=\"checkbox\" name=\"" . $name . "\" " . $checked . "/>";
}
Тру от фалсе
+161
/*
* Получаем категории из массива ЭКСПЕРЕМЕНТАЛЬНАЯ ФУНКЦИЯ :D
* $fp - файл
* $content - то что запишем
*/
function save_conf($fp, $content)
{
$file_name = basename($fp);
if(!file_exists($fp))
{
file_put_contents($fp,'');
@chmod(ROOT . $fp, 0666 );
}
if (file_exists($fp) && $content)
{
$fp = fopen($fp, "wb");
$content = "<?php
if (!defined('ACCESS'))
{
header('Location: /');
exit;
}
\n\n".$content."\n";
fwrite($fp, $content);
fclose($fp);
}
}
И как же он тут получит категории остаётся загадкой, и поржать он любит в комментариях смотрю)
* BY Toogle CMS
+163
Файл 1 :
<?php
for ($i=0; $i<10; $i++) // Моё примечение - вонять начинает отсюда
{
include "delstr.php";
include "razdel2.php";
include "gendat.php";
include "dopismain.php";
}
Файл delstr.php:
<?php
$num_stroka = 7; //Удалим 7 строку из файла
$file = file("gendat.php"); // Считываем весь файл в массив
for($i = 0; $i < sizeof($file); $i++)
if($i == $num_stroka) unset($file[$i]);
$fp = fopen("gendat.php", "w");
fputs($fp, implode("", $file));
fclose($fp);
?>
Файл razdel2.php:
<?php
$sl = file('ancorrzd.txt');
$sm = $sl[array_rand($sl, 1)];
$datam = $sm;
$file = fopen ("rzd.txt","w");
$str = "$datam";
fputs ( $file, $str);
fclose ($file);
$dataC = trim(file_get_contents ("rzd.txt"));
$data="\$dataCata='$dataC';";
$file = 'gendat.php';
$array=file( $file );
$array[7]= $data; //строка в которой нужно изменить значение $data
file_put_contents( $file, $array );
?>
Файл gendat.php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
ini_set('session.auto_start', '1');
//ini_set('upload_tmp_dir', 'c:\tmp');
set_time_limit(120);
@session_start();
$dataCata='xfgjcfyi';
$txtFile = 'result.txt'; // файл с текстом
$ancorFile = 'ancor.txt'; // файл с заголовками
$tplFile = 'template.txt'; // файл шаблона .dat файлов
$mainTplFile= 'maintemplate.txt'; // Шаблон файла со ссылками
$datDir = "articles/$dataCata"; // директория для .dat файлов
$datExt = 'dat'; // расширение .dat файлов
$mainFile = 'main.dat'; // Файл со ссылками на .dat файлы
$srcCharset = 'cp1251'; // Кодировка исходных файлов
$destCharset = 'cp1251'; // Кодировка файлов на выходе
$scriptCharset = 'utf-8'; // Кодировка скрипта
$blockLength = 4000; // Максимальный размер блока в байтах из файла с текстом
$file = fopen ("engine/menu.php","a");
$str = "<li><a href=\"/$dataCata/\">$dataCata</a></li>";
if ( !$file )
{
echo("Ошибка открытия файла");
}
else
{
fputs ( $file, $str);
}
fclose ($file);
if ($srcCharset == 'utf-8') $blockLength *= 2;
$blockLength = $blockLength % 2 > 0 ? $blockLength+1 : $blockLength;
if ( !is_dir($datDir) ) mkdir($datDir, 0777, true);
$hMain = NULL;
if ( !(@$hMain = fopen($mainFile, 'w+')) ) die("Невозможно создать файл $mainFile<br/>\b");
$hText = fopen($txtFile, 'r');
$ancors = explode("\n", $srcCharset == $scriptCharset ? file_get_contents($ancorFile) : iconv($srcCharset, $scriptCharset, file_get_contents($ancorFile)));
$template = $srcCharset == $scriptCharset ? file_get_contents($tplFile, 'r') : iconv( $srcCharset, $scriptCharset, file_get_contents($tplFile, 'r') ); // читаем шаблон
$content = '';
while ($content = fread($hText, $blockLength)) {
$fname = genName();
if (@$hDat = fopen("$datDir/$fname.$datExt", 'w')) {
$ancor = trim($ancors[rand(0, count($ancors)-1)]);
$content = $srcCharset == $scriptCharset ? trim($content) : iconv($srcCharset, $scriptCharset, trim($content));
// Генерим dat файлы по шаблону
$thisTpl = preg_replace("/(<!--.*?Kan_title.*?-->).*?(<!--.*?Kan_title.*?-->)/uism", "$1\n$ancor\n$2", $template);
$thisTpl = preg_replace("/(<!--.*?Kan_content.*?-->).*?(<!--.*?Kan_content.*?-->)/uism", "$1\n$content\n$2", $thisTpl);
$thisTpl = $scriptCharset == $destCharset ? $thisTpl : iconv( $scriptCharset, $destCharset, $thisTpl );
if (fwrite($hDat, $thisTpl)) {
echo "Файл $dataCata/$fname.$datExt записан<br/>\n";
$html = "
<loc><a href=\"/$dataCata/$fname.html\">$ancor</a></loc>\n";
fwrite($hMain, iconv($scriptCharset, $destCharset, $html));
} else { echo "Ошибка записи в файл $dataCata/$fname.$datExt<br/>\n"; }
} else {
echo "Не могу записать в файл $dataCata/$fname.$datExt<br/>\n";
}
}
// Генерация уникального имени
function genName() {
return substr(md5(uniqid(rand(), true)), 0, rand(7, 13));
}
?>
Человек интересуется, почему цикл выполняется только 1 раз. Ему посоветовали разместить лучше свой код тут, но по-моему, делать это самостоятельно у него желания нет, решил помочь. Пруфлинк - http://forum.searchengines.ru/showthread.php?t=643176
+169
if(!$this->first_name && !$this->last_name && !$this->countryID && !$this->zoneID && !$this->zip && !$this->state && !$this->city && !$this->address_street && !trim(strip_tags($strAddress))){
return '';
}
if(!$this->first_name && !$this->last_name && !$this->countryID && !$this->zoneID && !$this->zip && !$this->state && !$this->city && !$this->address_street && !$this->address_home && !trim(strip_tags($strAddress))){
return '';
}
if(!$this->first_name && !$this->last_name && !$this->countryID && !$this->zoneID && !$this->zip && !$this->state && !$this->city && !$this->address_street && !$this->address_home && !$this->address_houses && !trim(strip_tags($strAddress))){
return '';
}
if(!$this->first_name && !$this->last_name && !$this->countryID && !$this->zoneID && !$this->zip && !$this->state && !$this->city && !$this->address_street && !$this->address_home && !$this->address_houses && !$this->address_houseroom && !trim(strip_tags($strAddress))){
return '';
}
Найдено в одной CMS
+132
open System.Net
open System.Text.RegularExpressions
open System.Text
open System
type userInfo =
{ User : string;
Rating : double;}
let mutable Users = []
(* Заполняем списки юзверей *)
let getUsersInfo s =
let mutable m = Regex.Match(s, @">(?<user>[^<]+)</a></td>\s+<td class=""strength"">[^<]+</td>\s+<td class=""rating""><strong>(?<rating>[^<]+)") //+ Оптимизировать регулярку. (Page 2)
while(m.Success) do
let info = {User = m.Groups.["user"].Value; Rating = m.Groups.["rating"].Value |> double}
Users <- Users @ [info]
m <- m.NextMatch()
(* скачивание страницы по индексу *)
let getSourceForUsers p =
let url = "http://freehabr.ru/people/good/page" + string(p)
let wc = new WebClient();
let s = wc.DownloadString(url);
printfn "Разобрана %i страница" p
getUsersInfo s
(* получить индекс последней страницы *)
let getLastPage =
let wc = new WebClient()
wc.Encoding <- Encoding.UTF8
let s = wc.DownloadString "http://freehabr.ru/people/"
Regex.Match(s,@"(?<=e)\d+(?=/"">п)").Value |> int
let lastPage = getLastPage
let printList a =
a |> List.iter (fun x -> printfn "%s рейтинг - %.2f" x.User x.Rating)
Console.ReadKey() |> ignore
[<EntryPoint>]
let main(args:string[]) =
printfn "Парсер юзерей с положительным (или нулевым) рейтингом"
printfn "%i -- Количество страниц" lastPage
printfn "scan --XX - __ Cбор списка пользователей от первой страницы до XX"
printfn "scan --YY --XX __ Сбор списка пользователей от YY страницы до XX. \nXX не может быть больше, чем максимальное количество страниц в списках юзеров с положительной кармой"
let userInput = Console.ReadLine();
match userInput with
| _ when userInput.StartsWith "scan --" -> let a = Regex.Split(userInput,"--")
let dig = a.[1] |> int
if a.Length = 2 then // для первого варианта
[1 .. dig]
|> List.iter getSourceForUsers
else // для второго
[ dig .. a.[2] |> int ]
|> List.iter getSourceForUsers
printfn "~~~\nЮзеры посчитаны"
| _ -> printfn "Завершение приложения"
exit(1)
printfn "~~~~\nОбработка списка\n~~~~"
printfn "usersGreaterRate --XX __ Показать пользователей,\nу которых рейтинг больше или равен XX"
printfn "usersLessRate --XX __ Показать пользователей,\nу которых рейтинг меньше или равен XX"
printfn "usersWithNamesBegins --String __ Показать пользователей,\nу которых имя начинается со строки String"
let usersOper = Console.ReadLine()
let param = Regex.Split(usersOper," --").[1]
match usersOper with
| _ when usersOper.StartsWith "usersGreaterRate --" -> Users
|> List.filter (fun x -> x.Rating > (param |> double))
|> printList
| _ when usersOper.StartsWith "usersLessRate --" -> Users
|> List.filter (fun x -> x.Rating < (param |> double))
|> printList
| _ when usersOper.StartsWith "usersWithNamesBegins --" -> Users
|> List.filter (fun x -> x.User.StartsWith param)
|> printList
| _ -> printfn "Завершение приложения"
exit(1)
0
+78
private String createJndiName(Class homeClass) {
return "ejb/" + homeClass.getName().replace(".".charAt(0), "/".charAt(0));
}
no comments
+156
/**
* Checks that user client was not banned. Dies on false
* @param string $peer_id Peer_id of client
* @return void
* Взято с kinokpk
*/
function checkclient($peer_id){
$agent = $_SERVER['HTTP_USER_AGENT'];
//die($peer_id);
//return true;
//check by headers
if (function_exists('getallheaders')){
$headers = getallheaders();
}else{
$headers = emu_getallheaders();
}
if (isset($headers['Cookie']) || isset($headers['Accept-Language']) || isset($headers['Accept-Charset']))err('Вы не можете использовать этот клиент. Возможно вы читер.');
.................................................................
* BY LiteTracker Source
+166
//Анти - XSS
function antixss() {
//Запрещенные элементы
$array = array('./' , '../' , '\'' , '<script>' , 'document.cookie' , '</script>' );
//GET
$query = $_GET;
if( sizeof($query) ) {
foreach($query AS $arr => $value) {
$clear_xss = str_replace($array , '[xss]' , $value);
$_GET[$arr] = $clear_xss;
}
}
//GET
$query = $_POST;
if( sizeof($query) ) {
foreach($query AS $arr => $value) {
$clear_xss = str_replace($array , '[xss]' , $value);
$_POST[$arr] = $clear_xss;
}
}
return true;
}
Наконец-то школьники придумали средство от XSS.
* BY LiteTracker Source