- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
function count_arr($arr)
{
$rr = array_keys($arr);
if ($rr[0] !== 0) return 1;
$i = 0;
foreach ($arr as $k => $v) $i++;
return $i;
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+160
function count_arr($arr)
{
$rr = array_keys($arr);
if ($rr[0] !== 0) return 1;
$i = 0;
foreach ($arr as $k => $v) $i++;
return $i;
}
no comments qq
+152
function run_service($ivf_service)
{
$ivf_result = null;
if ( file_exists('base/services/'.$ivf_service.'/config.php') )
{
$ivf_result.= include_once('base/services/'.$ivf_service.'/config.php');
}
if ( file_exists('base/services/'.$ivf_service.'/index.php') )
{
$ivf_result.= include_once('base/services/'.$ivf_service.'/index.php');
}
return $ivf_result;
}
Проблема в том что каждый раз "вручную" писать это ни к чему. А такой вид вызывает сомнения в рациональности и скорости обработки. Как можно это удобно реализовать без юзания классов и автоинклудинга?
+147
<?php
class Bot {
public $brouser = 'Opera/9.60 (J2ME/MIDP; Opera Mini/4.2.14912/812; U; ru) Presto/2.4.15';
public $wait_ot = 1;
public $wait_do = 3;
public $log_url = "";
public $sir_e;
private $ch;
private $php_sesid;
private $domen = 'http://rugame.mobi/';
public function __construct($user_agent, $wait_ot, $wait_do, $log_url, $sir_e = 1) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIESESSION, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_USERAGENT, $this->brouser);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$this->ch = $ch;
if(($sir_e != 1) AND ($sir_e != 0)){
$this->sir_e = $sir_e;
}
if($user_agent != ""){
$this->brouser = $user_agent;
}
if(($wait_ot AND $wait_do) != 0){
$this->wait_ot = $wait_ot;
$this->wait_do = $wait_do;
}
if($log_url != ""){
$this->login($log_url);
}else{
die("Ошибка: в настройках не прописаны ссылка для логина \n");
}
}
private function __go($url){
if($this->php_sesid == 0){
$url = $this->domen.$url;
}
elseif(preg_match_all('#\?(.*)#ismU', $url, $matches) == 0){
$url = $this->domen.$url.'?PHPSESSID='.$this->php_sesid;
} else {
$url = $this->domen.$url.'&PHPSESSID='.$this->php_sesid;
}
sleep(rand($this->wait_ot, $this->wait_do));
curl_setopt($this->ch, CURLOPT_URL, $url);
echo '__go(\' '.$url.' \')<br />';
return curl_exec($this->ch);
}
public function login($log_url) {
do{
preg_match_all('#PHPSESSID=(.*)"#ismU', $this->__go($log_url), $matches);
}while($matches[1][0] == 0);
$this->php_sesid = $matches[1][0];
$this->__go('mgame/');
$this->__go('mx/');
}
public function find_and_execute(){
$actions = array(
///////////////////////////////////
/// Действия в разделе "рудники"///
///////////////////////////////////
'mx/?w_fd=', // Накормить шахтера
'mx/?t_md=', // Заправить технику
'mx/?s_rs=', // Добывать сырьё
'mx/?s_en=', // Взорвать породу
'mx/?s_ip=', // Разведать породу
'mx/?s_in=', // Забрать породу
);
$data = $this->__go('mx/?gt=1');
foreach($actions as $act){
$pattern = str_replace("?", "\?",'#'.$act.'(.*)&PHPSESSID#');
preg_match_all($pattern, $data, $matches);
if($matches[1] != 0){
foreach ($matches[1] as $id_rudnik){
if($act == 'mx/?s_rs='){
list($rudnik, $sir_e) = explode("_", $id_rudnik);
$this->__go($act.$rudnik."_".$this->sir_e);
}else{
$this->__go($act.$id_rudnik);
}
}
}
}
}
}
require ('/config/config.php');
$bot = new Bot($user_agent, $wait_ot, $wait_do, $log_url, $sir_e);
$bot->find_and_execute();
unset($bot);//освободим память (спец. для govnokod.ru)
exit("Я что смог сделал, пока");//пока пока
Моя первая попытка написать класс бота для он-лайн игрушки... Процедура find_and_execute() убивает самого на повал, так как в ней есть что-то запутанное после объявления массива . Но всё работает так как надо, так что я справился с задачей, и результат этому - ГОВНОКОД =D
+156
<?
include "config/bd.php";
class watermark1
{
function create_watermark( $main_img_obj, $text, $font, $r = 128, $g = 128, $b = 128, $alpha_level = 0 )
{
$width = imagesx($main_img_obj);
$height = imagesy($main_img_obj);
$angle = -rad2deg(atan2((-$height),($width)));
$text = " ".$text." ";
$c = imagecolorallocatealpha($main_img_obj, $r, $g, $b, $alpha_level);
$size = (($width+$height)/2)*2/strlen($text);
$box = imagettfbbox ( $size, $angle, $font, $text );
$x = $width/2 - abs($box[4] - $box[0])/2;
$y = $height/2 + abs($box[5] - $box[1])/2;
imagettftext($main_img_obj,$size ,$angle, $x, $y, $c, $font, $text);
return $main_img_obj;
}
}
$myrow22 = mysql_query("select * from `content` where id_content=3");
$row22 = mysql_fetch_array($myrow22);
include "includes/head1.php";
include "includes/leftm.php";
$category_id = isset($_GET['category_id']) ? (int)$_GET['category_id'] : 1;
$myrow = mysql_query("SELECT * FROM `gallery` LEFT JOIN `gallery_files` `gf` ON `gallery`.id = gallery_id WHERE category_id = " . $category_id . " ORDER BY `gf`.id");
$items = array();
$photos = array();
while($row = mysql_fetch_array($myrow)) {
$items[ $row['gallery_id']] = $row;
$photos[ $row['gallery_id']][] = $row['filename'];
}
echo '<div id=content>
<p><table width=100% >
<tr>';
$i = 0;
foreach ($items as $id => $item) {
$i++;
echo '<td>';
$photo = array_shift($photos[$id]); // только первая картинка
$photo2='./uploads/text'.$photo;
$watermark = new watermark1();
$type=mime_content_type($photo);
if (($type != 'image/jpeg')and($type != 'image/png'))
{
}
else
{
// определяем расширение переданного файла
switch ($type)
{
case 'image/jpeg':
$img = imagecreatefromjpg("./uploads/resized_$photo");
break;
case 'image/png':
$img = imagecreatefrompng("./uploads/resized_$photo");
break;
}
$im=$watermark->create_watermark($img,”jeka911.wordpress.com”,'./1.ttf',0,0,255,120);
imagejpeg($im,$photo2);
echo '<a href="infokuhni.php?id=' . $item['gallery_id'] . '" ><img src="'. $photo2 . '" /><br/><br/>';
echo '<font face="Georgia, Times New Roman, Times, serif">'; echo $item['title'] . '</font><br/>';
echo '<font face="Times New Roman, Times, serif">Цена: '; echo $item['price'] . ' рублей</font></a><br/><br>';
echo '</td>';
if (!($i % 4)) echo '</tr><tr>';
}
echo '</tr>
</table>
<p></div>';
include "includes/foot.php";
?>
+156
public static function ObjectToArray($obj, $filter_fields = true)
{
$a = array();
$cv = array();
if($filter_fields)
{
$cv = get_class_vars(get_class($obj));
}
else
{
$cv = get_object_vars($obj);
}
foreach($cv as $k => $v)
{
$a[$k] = $obj->$k;
}
return $a;
}
Написано n-ное количество лет назад. Делало из объекта ассоциативный массив, который передавался в метод, осуществляющий запись в БД :D
А ведь все это можно было заменить на return (array)$obj
+152
<?
include "config/bd.php";
class watermark1
{
function create_watermark( $main_img_obj, $text, $font, $r = 128, $g = 128, $b = 128, $alpha_level = 100 )
{
$width = imagesx($main_img_obj);
$height = imagesy($main_img_obj);
$angle = -rad2deg(atan2((-$height),($width)));
$text = " ".$text." ";
$c = imagecolorallocatealpha($main_img_obj, $r, $g, $b, $alpha_level);
$size = (($width+$height)/2)*2/strlen($text);
$box = imagettfbbox ( $size, $angle, $font, $text );
$x = $width/2 - abs($box[4] - $box[0])/2;
$y = $height/2 + abs($box[5] - $box[1])/2;
imagettftext($main_img_obj,$size ,$angle, $x, $y, $c, $font, $text);
return $main_img_obj;
}
}
$myrow22 = mysql_query("select * from `content` where id_content=3");
$row22 = mysql_fetch_array($myrow22);
include "includes/head1.php";
include "includes/leftm.php";
$category_id = isset($_GET['category_id']) ? (int)$_GET['category_id'] : 1;
$myrow = mysql_query("SELECT * FROM `gallery` LEFT JOIN `gallery_files` `gf` ON `gallery`.id = gallery_id WHERE category_id = " . $category_id . " ORDER BY `gf`.id");
$items = array();
$photos = array();
while($row = mysql_fetch_array($myrow)) {
$items[ $row['gallery_id']] = $row;
$photos[ $row['gallery_id']][] = $row['filename'];
}
echo '<div id=content>
<p><table width=100% >
<tr>';
$i = 0;
foreach ($items as $id => $item) {
$i++;
echo '<td>';
$watermark = new watermark1();
$img = imagecreatefromjpeg(“' . $photo . '”);
$im=$watermark->create_watermark($img,”jeka911.wordpress.com”,”1.ttf”,0,0,255,120);
imagejpeg($im,”result.jpg”);
$photo = array_shift($photos[$id]); // только первая картинка
echo '<a href="infokuhni.php?id=' . $item['gallery_id'] . '" ><img src="./uploads/resized_' . $photo . '" /><br/><br/>';
echo '<font face="Georgia, Times New Roman, Times, serif">'; echo $item['title'] . '</font><br/>';
echo '<font face="Times New Roman, Times, serif">Цена: '; echo $item['price'] . ' рублей</font></a><br/><br>';
echo '</td>';
if (!($i % 4)) echo '</tr><tr>';
}
echo '</tr>
</table>
<p></div>';
include "includes/foot.php";
?>
+153
<?
include "config/bd.php";
$myrow22 = mysql_query("select * from `content` where id_content=3");
$row22 = mysql_fetch_array($myrow22);
include "includes/head1.php";
include "includes/leftm.php";
$category_id = isset($_GET['category_id']) ? (int)$_GET['category_id'] : 1;
$myrow = mysql_query("SELECT * FROM `gallery` LEFT JOIN `gallery_files` `gf` ON `gallery`.id = gallery_id WHERE category_id = " . $category_id . " ORDER BY `gf`.id");
$items = array();
$photos = array();
while($row = mysql_fetch_array($myrow)) {
$items[ $row['gallery_id']] = $row;
$photos[ $row['gallery_id']][] = $row['filename'];
}
echo '<div id=content>
<p><table width=100% >
<tr>';
$i = 0;
foreach ($items as $id => $item) {
$i++;
echo '<td>';
$photo = array_shift($photos[$id]); // только первая картинка
echo '<a href="infokuhni.php?id=' . $item['gallery_id'] . '" ><img src="./uploads/resized_' . $photo . '" /><br/><br/>';
echo '<font face="Georgia, Times New Roman, Times, serif">'; echo $item['title'] . '</font><br/>';
echo '<font face="Times New Roman, Times, serif">Цена: '; echo $item['price'] . ' рублей</font></a><br/><br>';
echo '</td>';
if (!($i % 4)) echo '</tr><tr>';
}
echo '</tr>
</table>
<p></div>';
include "includes/foot.php";
?>
+158
$_SESSION['m_icds'][$_GET['boxid']][$_GET['symptom']] = $_GET['symptom'];
$box_array = $_SESSION['m_icds'][$_GET['boxid']][$_GET['symptom']];
if ($box_array) {
unset($_SESSION['m_icds'][$_GET['boxid']][$_GET['symptom']]);
}
else{
$_SESSION['m_icds'][$_GET['boxid']][$_GET['symptom']] = $_GET['symptom'];
}
Производство TRUE армянских девелоперов
+146
if( file_exists("controllers/{$controller}.php") ) {
include_once "controllers/{$controller}.php";
} else {
throw new Exception('Controller is invalid.');
}
с хабры.
Вообще, эт делается самим парсером php скрипта, без лишних телодвижений <_<
+147
function FileUpload(...) {
// ...
return array($name,$link);
header("HTTP/1.1 204 No Content");
}
echo FileUpload(...);
Что хотел этим сказать автор, для меня остаётся полнейшей загадкой.
Особенно хедерером 204.