Warning: Cannot use a scalar value as an array in /home/admin/public_html/forum/include/fm.class.php on line 757

Warning: Invalid argument supplied for foreach() in /home/admin/public_html/forum/include/fm.class.php on line 770

Warning: Invalid argument supplied for foreach() in /home/admin/public_html/forum/topic.php on line 737
Форумы портала PHP.SU :: Класс для работы с файловой системой

 PHP.SU

Программирование на PHP, MySQL и другие веб-технологии
PHP.SU Портал     На главную страницу форума Главная     Помощь Помощь     Поиск Поиск     Поиск Яндекс Поиск Яндекс     Вакансии  Пользователи Пользователи


 Страниц (1): [1]   

> Без описания
akaish
Отправлено: 19 Апреля, 2010 - 00:05:11
Post Id



Новичок


Покинул форум
Сообщений всего: 8
Дата рег-ции: Апр. 2010  
Откуда: СПБ


Помог: 0 раз(а)




Итак, не так давно я понял, что в php я не полный нуб =)
Изучил ооп, вещи даже работают =)
Решил начать писать библиотеки для php, что бы потом на их основе написать что-либо приличное. Данный сайт очень помог мне в изучении как программирования в целом, так и php в частности. Недавно даже понял, что могу писать на любом c-подобном языке после недельного ознакомления с мануалами.
Теперь я бы хотел помочь остальным. Сюда и себе на сайт (http://akaish-troyan[dot]net ) я буду выкладывать свои исходники. Что-то написано хорошо, что-то плохо, но надеюсь, что они окажутся вам полезны = )
Итак, библиотеку можно скачать тут: http://blog[dot]akaish-troyan[dot]net/?p=34
Вот и она (библиотека простейшая):
PHP:
скопировать код в буфер обмена
  1. <?PHP
  2. /**
  3.  * @author akaish: akaish@mail.ru akaish-troyan.net akaish@akaish-troyan.net
  4.  * @category lib to work with filesys
  5.  * @version 0.1
  6.  */
  7. Class FileSys
  8. {
  9.         //Descr: variables and contstants
  10.         public $path, $whattowrite, $chmod;
  11.         private $fileid, $dir;
  12.         //Descr: constructor
  13.         private function __construct($path, $chmod = "0770")
  14.         {
  15.                 $this->path = $path;
  16.                 $this->chmod = $chmod;
  17.         }
  18.         //Descr: check if file exists
  19.         private function IfFileExists()
  20.         {
  21.                 return file_exists($this->path);
  22.         }
  23.         //Descr: open file
  24.         public function OpenFile($mod)
  25.         {
  26.                 if (self::IfFileExists())
  27.                 {
  28.                         $fileid = fopen($this->path, $mod) or die(print("Error: I cant open file" . $this->path));
  29.                         return;
  30.                 }
  31.                 else
  32.                 {
  33.                         echo "File " . $this->path . " doesn't exists";
  34.                         return;
  35.                 }
  36.         }
  37.         //Descr: Get array of files in target directory
  38.         public function ScanDir()
  39.         {              
  40.                 $this->dir = opendir($this->path);
  41.                 $i = 0;
  42.                 while (false !== ($file = readdir($this->dir)))
  43.         {  
  44.                 if($file != "." && $file != "..")
  45.                 {
  46.                         $arrayoffiles[$i] = $file;
  47.                         $i++;
  48.                 }  
  49.         }
  50.         return $arrayoffiles;
  51.         }
  52.         //Descr: ReWriteFile
  53.         protected function ReWrite()
  54.         {
  55.                 $this->fileid = self::OpenFile("w+");
  56.                 fwrite($this->fileid, $this->whattowrite, 2048) or die(print("FileSys::ReWrite error:" . $this->path));
  57.                 return;
  58.         }
  59.         //Descr: Delete File
  60.         protected function DeleteFile()
  61.         {
  62.                 if(self::IfFileExists())
  63.                 {
  64.                         unlink($this->path);
  65.                         echo "File " . $this->path . " was deleted succesesfully!";
  66.                         return;
  67.                 }
  68.                 else
  69.                 {
  70.                         echo "Can not delete file: It doesn't exists!";
  71.                         return;
  72.                 }
  73.         }
  74.         //Descr: Create file
  75.         public final function CreateFile()
  76.         {
  77.                 if (self::IfFileExists())
  78.                 {
  79.                         echo "File " . $this->path . " is already exists";
  80.                         return false;
  81.                 }
  82.                 else
  83.                 {
  84.                         fopen($this->path, "w+") or die("Error with creating file:" . $this->path);
  85.                         return true;
  86.                 }
  87.         }
  88.         //Descr: delete folder
  89.         public final function DeleteDir()
  90.         {
  91.                 if (!self::IfFileExists())
  92.                 {
  93.                         echo "Folder " . $this->path . " is not exists";
  94.                         return false;
  95.                 }
  96.                 else
  97.                 {
  98.                         rmdir($this->path) or die("Error with deleting folder:" . $this->path);
  99.                         return true;
  100.                 }
  101.         }
  102.         //Descr: create folder
  103.         public final function CreateDir()
  104.         {
  105.                 if (self::IfFileExists())
  106.                 {
  107.                         echo "Folder " . $this->path . " is already exists";
  108.                         return false;
  109.                 }
  110.                 else
  111.                 {
  112.                         mkdir($this->path, $this->chmod) or die("Error with creating folder:" . $this->path);
  113.                         return true;
  114.                 }
  115.         }
  116.         //Descr: destructor
  117.         private final function __destruct()
  118.         {
  119.                 fclose($this->fileid);
  120.                 closedir($this->dir);
  121.         }
  122. }
  123.  
  124. ?>


-----
Скучно...
 
 Top
akaish
Отправлено: 28 Апреля, 2010 - 02:50:15
Post Id



Новичок


Покинул форум
Сообщений всего: 8
Дата рег-ции: Апр. 2010  
Откуда: СПБ


Помог: 0 раз(а)




Итак, ещё один маленький класс, на этотраз для работы с MySQL:
PHP:
скопировать код в буфер обмена
  1. <?PHP
  2. /**
  3.  * @author akaish akaish-troyan.net
  4.  * @category sql-lib
  5.  * @desc some common functions to operate with sql
  6.  */
  7.  
  8. class sql
  9. {
  10.         //Descr: vars
  11.         public $link, $tablearray, $query, $resultarray, $affectedrows, $result;
  12.         private $dbhost, $databaseuser, $databasepassword, $databaseport;
  13.         //Descr: constructor
  14.         public function __construct()
  15.         {
  16.                 $this->Vars();
  17.                 $this->NewConnection();
  18.                 $this->GetArrayOfTables();
  19.         }
  20.         //Descr: here we can definite some variables
  21.         private function Vars()
  22.         {
  23.                 $this->dbhost = "";
  24.                 $this->databaseuser = "";
  25.                 $this->databasepassword = "";
  26.                 $this->databaseport = "";
  27.         }
  28.         //Descr: create new connection
  29.         private function NewConnection()
  30.         {
  31.                 $this->link = mysql_connect($this->dbhost, $this->databaseuser, $this->databasepassword, $this->databaseport) or die("Some  error occured with connecting: " . mysql_error($this->link));
  32.                 mysql_select_db($this->dbmain, $this->link) or die("Can't select db" . $this->dbmain);
  33.                 return;
  34.         }
  35.         // Descr: close connection
  36.         private function CloseConnection()
  37.         {
  38.                 mysql_close($this->link);
  39.                 return;
  40.         }
  41.         // Descr: this function gets table's names from sys database
  42.         protected function GetArrayOfTables()
  43.         {
  44.                 $this->query = "SHOW TABLES";
  45.                 $affrows = mysql_affected_rows($this->link);
  46.                 for ($i=0; $i < $affrows; $i++)
  47.                 {
  48.                         $arrayoftb[$i] = mysql_fetch_row($this->result);
  49.                 }
  50.                 $this->tablearray = $arrayoftb;
  51.                 return;
  52.         }
  53.         // Descr: execute query
  54.         private function ExecQuery()
  55.         {
  56.                 if (self::CheckQueryForLegacy())
  57.                 {
  58.                         $this->result = mysql_query($this->query, $this->link) or die("Can not execute query " . $this->query . ", reason: " . mysql_error($this->link));
  59.                         $this->affectedrows = mysql_affected_rows($this->link);
  60.                         return;
  61.                 }
  62.                 else
  63.                 {
  64.                         echo "Query " . $this->query . " was denied by function CheckQueryForLegacy";
  65.                         return;
  66.                 }      
  67.         }
  68.         // Descr: checks some conditions
  69.         private function CheckQueryForLegacy()
  70.         {
  71.                 $testarray = explode(" ", $this->query);
  72.                 $operation = $testarray[0];
  73.                         switch ($operation)
  74.                         {
  75.                                 case "DROP":
  76.                                         if ($testarray[1] == "TABLE")
  77.                                         {
  78.                                                 return self::CheckIfExistsTable($testarray[2]);
  79.                                         }
  80.                                         break;
  81.                                 case "DELETE":
  82.                                         if ($testarray[1] == "TABLE")
  83.                                         {
  84.                                                 return self::CheckIfExistsTable($testarray[2]);
  85.                                         }
  86.                                         break;
  87.                                 case "CREATE":
  88.                                         if ($testarray[1] == "TABLE")
  89.                                         {
  90.                                                 return !self::CheckIfExistsTable($testarray[2]);
  91.                                         }
  92.                                         break;
  93.                         }
  94.                         return TRUE;
  95.         }
  96.         // Descr: check existance of table
  97.         private function CheckIfExistsTable($table)
  98.         {
  99.                 return in_array($table, $this->tablearray);
  100.         }
  101.         // Descr: Save from result
  102.         public function ExecuteAndSaveToArray($query)
  103.         {
  104.                 $this->query = $query;
  105.                 self::ExecQuery();
  106.                 for ($i=0; $i < $this->affectedrows; $i++)
  107.                 {
  108.                         $this->resultarray[$i] = mysql_fetch_row($this->result);
  109.                 }
  110.                 return;
  111.         }
  112. }
  113. ?>

(Отредактировано автором: 28 Апреля, 2010 - 02:51:10)



-----
Скучно...
 
 Top
akaish
Отправлено: 10 Мая, 2010 - 01:04:07
Post Id



Новичок


Покинул форум
Сообщений всего: 8
Дата рег-ции: Апр. 2010  
Откуда: СПБ


Помог: 0 раз(а)




Немного поигрался с cURL =))
PHP:
скопировать код в буфер обмена
  1. <?PHP
  2.  
  3. Class Curl
  4. {
  5.         public $targeturl, $htmltext;
  6.         public $sslverificate, $sslcheckdomain;
  7.         public $headers, $from_refer, $agent, $followlocation, $returntransfer, $cookiesession, $timeout;
  8.         private $curlobject;
  9.         public function __construct($targeturl, $ifissetparameters)
  10.         {
  11.                 $this->targeturl = $targeturl;
  12.                 if ($ifissetparameters!="no" and is_array($ifissetparameters) and sizeof($ifissetparameters)==9)
  13.                 {
  14.                         $this->headers = $ifissetparameters[0];
  15.                         $this->from_refer = $ifissetparameters[1];
  16.                         $this->agent = $ifissetparameters[2];
  17.                         $this->followlocation = $ifissetparameters[3];
  18.                         $this->returntransfer = $ifissetparameters[4];
  19.                         $this->cookiesession = $ifissetparameters[5];
  20.                         $this->timeout = $ifissetparameters[6];
  21.                         $this->sslverificate = $ifissetparameters[7];
  22.                         $this->sslcheckdomain = $ifissetparameters[8];
  23.                 }
  24.                 elseif($ifissetparameters == "no")
  25.                 {
  26.                         $header [] = "Accept: text/html;q=0.9, text/plain;q=0.8, image/png, */*;q=0.5" ;
  27.                         $header [] = "Accept_charset: windows-1251, utf-8, utf-16;q=0.6, *;q=0.1";
  28.                         $header [] = "Accept_encoding: identity";
  29.                         $header [] = "Accept_language: en-us,en;q=0.5";
  30.                         $header [] = "Connection: close";
  31.                         $header [] = "Cache-Control: no-store, no-cache, must-revalidate";
  32.                         $header [] = "Keep_alive: 300";
  33.                         $header [] = "Expires: Thu, 01 Jan 1970 00:00:01 GMT";
  34.                         $this->headers = $header;
  35.                         $this->agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; ru-RU; rv:1.7.12) Gecko/20050919 Firefox/1.0.7";
  36.                         $this->from_refer = $this->targeturl;
  37.                         $this->followlocation = true;
  38.                         $this->returntransfer = true;
  39.                         $this->cookiesession = true;
  40.                         $this->timeout = 50;
  41.                         $this->sslcheckdomain = false;
  42.                         $this->sslverificate = false;
  43.                 }
  44.                 else
  45.                 {
  46.                         die("Не получается создать кёрл объект, так как я не имею информации для его создания или информация неккоректна");
  47.                 }
  48.                 self::CurlSetOpt();
  49.         }
  50.        
  51.         private function CurlSetOpt()
  52.         {
  53.                 $this->curlobject = curl_init($this->targeturl);
  54.                 curl_setopt($this->curlobject, CURLOPT_RETURNTRANSFER, $this->returntransfer);
  55.                 curl_setopt($this->curlobject, CURLOPT_HEADER, true);
  56.                 if($this->cookiesession == true)
  57.                 {
  58.                         curl_setopt($this->curlobject, CURLOPT_COOKIESESSION, $this->cookiesession);
  59.                         curl_setopt($this->curlobject, CURLOPT_COOKIEJAR, "cookie");
  60.                         curl_setopt($this->curlobject, CURLOPT_COOKIEFILE, "cookie");
  61.                 }
  62.                 curl_setopt($this->curlobject, CURLOPT_FOLLOWLOCATION, $this->followlocation);
  63.                 curl_setopt($this->curlobject, CURLOPT_CONNECTTIMEOUT, $this->timeout);
  64.                 curl_setopt($this->curlobject, CURLOPT_USERAGENT, $this->agent );
  65.                 curl_setopt($this->curlobject, CURLOPT_REFERER, $this->from_refer);
  66.                 curl_setopt($this->curlobject, CURLOPT_HTTPHEADER, $this->headers);
  67.                 curl_setopt($this->curlobject, CURLOPT_SSL_VERIFYPEER, $this->sslverificate);
  68.                 curl_setopt($this->curlobject, CURLOPT_SSL_VERIFYHOST, $this->sslcheckdomain);
  69.                 return;
  70.         }
  71.        
  72.         public function GetPageText()
  73.         {
  74.                 $this->htmltext = curl_exec($this->curlobject);
  75.                 return;
  76.         }
  77.        
  78.         private function __destruct()
  79.         {
  80.                 curl_close($this->curlobject);
  81.         }
  82.        
  83.        
  84. }
  85. ?>


-----
Скучно...
 
 Top
akaish
Отправлено: 10 Мая, 2010 - 07:21:34
Post Id



Новичок


Покинул форум
Сообщений всего: 8
Дата рег-ции: Апр. 2010  
Откуда: СПБ


Помог: 0 раз(а)




Дали мне заказик, написать простой парсер с поддержкой шаблонов для парсинга, мозги не работают(((
В принципе, парсер готов на 70%, но, вглядевшись в код туманным взглядом, понял, что собирать и отлаживать всю эту бяку буду долго...
Если кому интересно, плод моей больной фантазии после сдачи выложу сюда, просто хочется с кем-нибудь обсудить, как и куда засунуть мне руки))


-----
Скучно...
 
 Top
Страниц (1): [1]
Сейчас эту тему просматривают: 0 (гостей: 0, зарегистрированных: 0)
« Напишите за меня, пожалуйста »


Все гости форума могут просматривать этот раздел.
Только зарегистрированные пользователи могут создавать новые темы в этом разделе.
Только зарегистрированные пользователи могут отвечать на сообщения в этом разделе.
 



Powered by PHP  Powered By MySQL  Powered by Nginx  Valid CSS  RSS

 
Powered by ExBB FM 1.0 RC1. InvisionExBB