| Autor | Správa |
stenley
 Moderátor
 Založený: 27.07.2007 Príspevky: 3715 Bydlisko: Bratislava Vek: 26
 | Zaslal: St 26.11.08 15:48 |   |
Sprava URL adresy 2 ("pekne url adresy")
Autor: stenley
Popis:
| citácia: | | string MRWgenerateURL ( [mixed $param1, mixed $value1, ...] ) |
Ako som nedavno avizoval, nasledujuca funkcia sluzi na spravu "peknych url adries", tzn. na jednoduche pridavanie, mazanie a zmenu jednotlivych casti adresy, pricom je mozne funkcii predat viacero "operacii" naraz. K spravnej funkcnosti musia byt funkcii MRWgenerateURL dostupne pravidla, ktorymi sa riadi prepisovanie adries (.htaccess). V prikladoch pouzitia najdete popisany format tychto pravidiel - premenna $arrRules. Dalej je potrebne uviest adresar, z ktoreho sa skript spusta - premenna $pageDir. Obe tieto premenne su globalnymi premennymi funkcie.
| kód: | <?php
/**
* MRWgenerateURL()
*
* Sprava URL adresy 2 ("pekne url adresy")
*
* @author stenley <stenley@webdev.sk>
* @version 1.0
*/
function MRWgenerateURL()
{
global $pageDir,$arrRules;
$GET = $_GET;
$num_args = func_num_args();
if($num_args>0 && $num_args%2==0) {
$args = func_get_args();
foreach($args as $index => $paramName) {
$paramName = trim($paramName);
if($index%2==0 && !empty($paramName)) {
$paramValue = trim($args[$index+1]);
if(array_key_exists($paramName,$GET)) {
if(!empty($paramValue)) {
$GET[$paramName] = $paramValue;
} else {
unset($GET[$paramName]);
}
} else {
$GET[$paramName] = $paramValue;
}
}
}
if(count($GET)>0) {
foreach($arrRules as $eregRule => $arrUrlRule) {
list($urlRule,$urlMRWRule) = $arrUrlRule;
parse_str($urlRule,$arrUrlRule);
if(count($GET)==count($arrUrlRule)) {
foreach($GET as $key => $value) {
if(array_key_exists($key,$arrUrlRule)) {
$urlMRWRule = str_replace($arrUrlRule[$key],$value,$urlMRWRule);
}
}
if(eregi("^".$eregRule."$",$urlMRWRule) && strpos($urlMRWRule,'$')===false) {
return $pageDir.$urlMRWRule;
}
}
}
} else {
return $pageDir;
}
}
return $_SERVER['REQUEST_URI'];
}
?> |
Priklady pouzitia:
Na fiktivnom webe pouzivame adresy typu:
1. www.nieco.sk/kategoria (klasicka adresa: www.nieco.sk/?a=kategoria)
2. www.nieco.sk/kategoria/subkategoria (klasicka adresa: www.nieco.sk/?a=kategoria&b=subkategoria)
kde kategoria predstavuje hodnotu parametra a a subkategoria hodnotu parametra b.
Kedze pouzivame 2 formaty adries, pole pravidiel bude obsahovat 2 polozky (pravidla); stranka sa spusta z korenoveho adresara:
| kód: | $pageDir = "/";
$arrRules = array(
'([^/]+)/([^/]+)' => array('a=$1&b=$2','$1/$2'),
'([^/]+)' => array('a=$1','$1')
); |
Pravidla su ulozene vo viacrozmernom poli $arrRules. Format pravidiel je podobny formatu pouzivanemu v .htaccess. Kazde pravidlo pozostava z regularneho vyrazu pravidla (index pola) a 2 hodnot: format klasickej adresy a format vyslednej "peknej adresy". Jednotlive casti, ktore vyhovuju regularnemu vyrazu, sa oznacuju $1, $2, ... Prepisovanie sa teda riadi len tymito pravidlami, ak tam zabudnete niektore uviest, funkcia vam vrati aktualnu adresu. Mozno som to trosku zlozito popisal, ale priklad bude hadam nazornejsi:
1. Zistenie aktualnej adresy:
Aktualna adresa: /
Pouzitie: MRWgenerateURL()
Vysledok: /
2. Pridanie novej casti adresy (parameter b):
Aktualna adresa: /auto
Pouzitie: MRWgenerateURL("b","bmw")
Vysledok: /auto/bmw
3. Zmena druhej casti adresy (parameter b):
Aktualna adresa: /auto/bmw
Pouzitie: MRWgenerateURL("b","skoda")
Vysledok: /auto/skoda
4. Pokus o pridanie tretej casti adresy:
Aktualna adresa: /auto/skoda
Pouzitie: MRWgenerateURL("c","octavia")
Vysledok: /auto/skoda
Vysvetlenie: Nakolko sa v pravidlach nenachadza tvar pravidla s 3 castami, prepis nebol uspesny
5. Zmena viacerych casti naraz:
Aktualna adresa: /auto/skoda
Pouzitie: MRWgenerateURL("a","motorka","b","honda")
Vysledok: /motorka/honda |
_________________ Desktop: CPU: AMD Athlon64 3000+ | MB: Biostar K8T890-A9 | VGA: NVIDIA GeForce 6200 LE 256MB | RAM: 2x 1GB A-DATA DDR 400 MHz Dual Kit | HDD: WD Caviar Blue 320GB | DVD: LG GSA-H10N | Keyboard: Chicony KU-0420 Silver/Black | Mouse: Logitech RX1000 | Zdroj: Corsair CX400 400W | CASE: DELUX DLC-MD370 Black | LCD: 20" Samsung 206BW | Repro: Teac XL-20
Notebook: ACER Aspire 4820TG 14" | CPU: Intel Core i5 2,53 GHz | VGA: ATI Mobility Radeon HD5650 1GB / Intel HD Graphics | RAM: 4GB DDR3 1066 MHz | HDD: 640GB
Naposledy upravil stenley dňa St 19.01.11 20:50, celkom upravené 2 krát. | |
    |
 |
Flety
 Užívateľ
 Založený: 26.11.2006 Príspevky: 4109 Bydlisko: HE(Humenne) - KE Vek: 18
 | Zaslal: Št 27.11.08 16:50 |   |
Zmena veľkosti obrázka
Autor: neznámy(niekde na nete nájdené )
Úpravy: Jakub Sakáč(jsakac) a Márius Rak(akože ja )
Popis: Pomocou tejto funkcie vygenerujete jednoduchú (väčšinou) zmenšeninu obrázka. Dá sa použiť aj na zväčšenie ale myslím, že je to zbytočnosť.
| kód: | <?php
function get_file_type($subor)
{
$pripona = substr($subor, -4, 4);
$pripona = strtolower($pripona);
switch($pripona)
{
case '.jpg':
return 'jpg';
break;
case '.jpe':
return 'jpg';
break;
case '.gif':
return 'gif';
break;
case '.png':
return 'png';
break;
case '.bmp':
return 'bmp';
break;
}
}
function onlineresize($subor, $NovaSirka, $NovaVyska)
{
switch(get_file_type($subor))
{
case 'jpg':
$image = imagecreatefromjpeg($subor);
break;
case 'gif':
$image = imagecreatefromgif($subor);
break;
case 'png':
$image = imagecreatefrompng($subor);
break;
case 'bmp':
$image = imagecreatefrombmp($subor);
break;
}
$sirka = imagesx($image);
$vyska = imagesy($image);
if($NovaVyska == 0)
{
$pomer = $sirka / $vyska;
$NovaVyska = $NovaSirka / $pomer;
}
else
{
$NovaSirka = $NovaSirka;
$NovaVyska = $NovaVyska;
}
if ($NovaSirka == 0)
{
$pomer = $vyska / $sirka;
$NovaSirka = $NovaVyska / $pomer;
}
else
{
$NovaSirka = $NovaSirka;
$NovaVyska = $NovaVyska;
}
$image_zmenseny = imagecreatetruecolor($NovaSirka, $NovaVyska);
imagecopyresampled($image_zmenseny, $image, 0, 0, 0, 0, $NovaSirka, $NovaVyska, $sirka, $vyska);
// Zobrazíme zmenšeninu
switch(get_file_type($subor))
{
case 'jpg':
header('Content-type: image / jpeg');
imagejpeg($image_zmenseny);
break;
case 'gif':
header('Content-type: image / gif');
imagegif($image_zmenseny);
break;
case 'png':
header('Content-type: image / png');
imagepng($image_zmenseny);
break;
case 'bmp':
header('Content-type: image / bmp');
imagebmp($image_zmenseny);
break;
}
}
//zavolame funkciu a zobrazime obrazok
onlineresize($_GET['img'], $_GET['sirka'], $_GET['vyska']);
?> |
Použitie: Najlepšie je to uložiť do samostatného súboru napríklad ako obrazok.php potom to používame spôsobom: <img src="obrazok.php?img=cesta/ku/obrazku/obrazok.jpg&sirka=250" alt="">
kde samozrejme do img definujete relatívnu cestu vzhľadom na súbor alebo absolútnu cestu a do premennej sirka samozrejme šírku alebo ju môžeme nahradiť aj premennou vyska.
Je to použiteľné na všetky typy obrázkov okrem bmp, aj keď tam je zahrnutá podpora nefunguje ako by mala. |
| |
       |
 |
stenley
 Moderátor
 Založený: 27.07.2007 Príspevky: 3715 Bydlisko: Bratislava Vek: 26
 | Zaslal: Ne 22.02.09 14:18 |   |
Vkladanie retazca na urcitu poziciu druheho retazca
Autor: stenley (inspirovane funkciou strwpos (Thomas Oldbury))
Popis:
| citácia: | | string strwpos ( string $str, string $ins, mixed $pos [, bool $rewrite=false ] ) |
Funkcia strwpos() sluzi na vlozenie urciteho retazca $ins na definovanu poziciu $pos v retazci $str. Pozicia je vyjadrena ako (kladne/zaporne) cislo pripadne pole takychto cisiel, pricom 0 predstavuje zaciatok retazca, -1 predposledny znak retazca, ... podobne ako vo funkcii substr(). Nepovinny parameter $rewrite urcuje, ci sa retazec $ins len cisto vlozi na zvolenu poziciu (default nastavenie), alebo sa povodne znaky v $str (na dotknutych poziciach) prepisu hodnotou v $ins ($rewrite=true).
| kód: | <?php
/**
* strwpos()
*
* Vkladanie retazca na urcitu poziciu druheho retazca
*
* @author stenley <stenley@webdev.sk>
* @version 1.1
*/
function strwpos($str, $ins, $pos, $rewrite=false) {
$pos = is_array($pos) ? $pos : array($pos);
//dlzka vkladaneho retazca
$insLen = strlen($ins);
foreach($pos as $i) {
//dlzka generovaneho retazca
$strLen = strlen($str);
//vlozenie retazca na zaciatok
if($i==0 || $i<=-$strLen) {
$str = $rewrite ? $ins.substr($str,$insLen) : $ins.$str;
//vlozenie retazca niekam do stredu
} elseif(abs($i)<$strLen) {
//pozicia pocitana od zaciatku generovaneho retazca
if($i>0) {
$str = substr($str,0,$i).$ins.($rewrite ? substr($str,$i+$insLen) : substr($str,$i));
//pozicia pocitana od konca generovaneho retazca
} else {
$striLen = $strLen+$i;
$str = substr($str,0,$striLen).$ins.($rewrite ? substr($str,$striLen+$insLen): substr($str,$i));
}
//vlozenie retazca na koniec
} else {
$str = $str.$ins;
}
}
return $str;
}
?> |
Priklad pouzitia:
| kód: | $str = "123456789";
$ins = "abc";
$pos = 0;
echo strwpos($str, $ins, $pos); //vypise abc123456789
echo strwpos($str, $ins, $pos, true); //vypise abc456789
$pos = array(1,-4);
echo strwpos($str, $ins, $pos); //vypise 1abc2345abc6789
echo strwpos($str, $ins, $pos, true); //vypise 1abc5abc9 |
|
_________________ Desktop: CPU: AMD Athlon64 3000+ | MB: Biostar K8T890-A9 | VGA: NVIDIA GeForce 6200 LE 256MB | RAM: 2x 1GB A-DATA DDR 400 MHz Dual Kit | HDD: WD Caviar Blue 320GB | DVD: LG GSA-H10N | Keyboard: Chicony KU-0420 Silver/Black | Mouse: Logitech RX1000 | Zdroj: Corsair CX400 400W | CASE: DELUX DLC-MD370 Black | LCD: 20" Samsung 206BW | Repro: Teac XL-20
Notebook: ACER Aspire 4820TG 14" | CPU: Intel Core i5 2,53 GHz | VGA: ATI Mobility Radeon HD5650 1GB / Intel HD Graphics | RAM: 4GB DDR3 1066 MHz | HDD: 640GB
Naposledy upravil stenley dňa St 19.01.11 20:50, celkom upravené 1 krát. | |
    |
 |
Tominator
 Zablokovaný užívateľ
 Založený: 21.02.2007 Príspevky: 4009
 | Zaslal: Po 23.02.09 21:15 |   |
PHP Template Class
Autor: Tomáš Bončo
Popis: Trieda slúži na parsovanie template súborov, pričom výstupom je hotové HTML. Trieda obsahuje aj podtriedu (nadstavbu), ktorá urýchľuje zápis. Parser umoznuje vkladanie hodnot, cykly, podmienky, include
Blizsie info: www.comper.sk/Template (dokumentácia, príklady, changelog, download)
Posledná zmena na PCF: 25.06.09 12:25
Pozn.: V príklade je uvedená iba časť celej funkcionality triedy
| kód: | <?php
/**
* @author Tomáš Bončo
* @copyright 2010
*
* TENTO TEXT NESMIETE ZMAZAŤ
*
* Pre používanie tejto triedy musíte dodržať licenciu vo všetkých jej bodoch.
*
* Licencia: http://parser.comper.sk/Licencia
* Homepage: http://parser.comper.sk
*
* Verzia 1.3 RC
*/
class Parser {
var $File;
var $Values = array();
var $Blocks = array();
var $Conditions = array();
var $Content;
var $Clean;
var $Show;
function Parse() {
if(file_exists($this -> File)){
/** BEGIN **/
$File = fopen($this -> File,"r");
$this -> Content = fread($File, filesize($this -> File));
$this -> Content = str_replace("\n","°°°°°°",$this -> Content);
$this -> Content = str_replace("\r","ˇˇˇˇˇˇ",$this -> Content);
$this -> Content = str_replace("\t","´´´´´´",$this -> Content);
$this -> Includes();
$this -> Blocks();
$this -> Conditions();
$this -> Values();
/** END **/
$this -> Content = str_replace("°°°°°°","\n",$this -> Content);
$this -> Content = str_replace("ˇˇˇˇˇˇ","\r",$this -> Content);
$this -> Content = str_replace("´´´´´´","\t",$this -> Content);
/** SHOW **/
$this -> Show();
} else die("PARSER: Súbor nenájdený!");
}
/**
* @Includes
* */
function Includes() {
$a_Include = preg_split("#<!-- INCLUDE (.*?) -->#",$this -> Content,"-1", PREG_SPLIT_DELIM_CAPTURE );
if(Count($a_Include) > 0){
$r_Path = explode("/", $this -> File); $r_Path[Count($r_Path)-1] = null; $r_Path = implode("/", $r_Path);
for($i = 0; $i < Count($a_Include); $i++){
if($i % 2 !== 0){
$p_include = new QuickParse($r_Path.$a_Include[$i],$this -> Values, false, $this -> Blocks, $this -> Conditions, $this -> Clean);
$a_Include[$i] = null; $a_Include[$i] = $p_include -> Content;
}
}
}
$this -> Content = implode("",$a_Include);
if(preg_match("#<!-- INCLUDE (.*?) -->#", $this -> Content) > 0) $this -> Includes();
}
/**
* @Blocks
* */
function Blocks() {
$a_Blocks = preg_split("#<!-- BEGIN (.*?) -->(.+?)<!-- END \\1 -->#", $this -> Content, "-1", PREG_SPLIT_DELIM_CAPTURE ); // Rozdeluje stránku do poľa
if(is_array($a_Blocks) && Count($a_Blocks) > 0){
$a_Page = $this -> SplitPage($a_Blocks);
$a_Identifikator_Cyklu = $a_Page[0]; // Obsahuje identifikátor (názov) cyklu a jeho pozíciu v poli $a_Blocks
$a_Content = $a_Page[1]; // Obsahuje pozíciu v poli a obsah cyklu
if(is_array($a_Identifikator_Cyklu) && Count($a_Identifikator_Cyklu) > 0){
foreach ($a_Identifikator_Cyklu as $r_Identifikator_Cyklu => $r_Pozicia){
$r_ReplaceText = null;
$r_Identifikator_Cyklu = reset(explode("|´#´|",$r_Identifikator_Cyklu));
if(!Empty($this -> Blocks[$r_Identifikator_Cyklu])){
foreach($this -> Blocks[$r_Identifikator_Cyklu] as $r_Nazov_Premennej => $a_Hodnota_Premennej){
$r_ReplaceText .= $a_Content[$r_Pozicia+1];
foreach($this -> Blocks[$r_Identifikator_Cyklu][$r_Nazov_Premennej] as $r_Nazov => $r_Hodnota){
$r_ReplaceText = str_replace("{". $r_Nazov ."}", $r_Hodnota, $r_ReplaceText);
/* RESET */
$r_Nazov = null;
$r_Hodnota = null;
}
}
$a_Blocks[$r_Pozicia] = null; //zmažeme identifikátor
$a_Blocks[$r_Pozicia+1] = $r_ReplaceText; // starý obsah nahradíme novým obsahom
$r_ReplaceText = null; // reset kvôli ďalšiemu cyklu
} else { /* Pokial je cyklus definovaný v tpl ale nie v php */
$a_Blocks[$r_Pozicia] = null; // zmažeme identifikátor
$a_Blocks[$r_Pozicia+1] = null; // zmažeme obsah
}
}
$this -> Content = implode("", $a_Blocks);
if(preg_match("#<!-- BEGIN (.*?) -->(.+?)<!-- END \\1 -->#", $this -> Content) > 0) $this -> Blocks();
}
}
}
/**
* @Conditions
* */
function Conditions() {
$a_Conditions = preg_split("#<!-- IF (.*?) -->(.+?)<!-- END \\1 -->#",$this -> Content,"-1", PREG_SPLIT_DELIM_CAPTURE );
if(is_array($a_Conditions) && Count($a_Conditions) > 0){
$a_Page = $this -> SplitPage($a_Conditions);
$a_Identifikator_Cyklu = $a_Page[0]; // Obsahuje identifikátor (názov) cyklu a jeho pozíciu v poli $a_Permisions
$a_Content = $a_Page[1]; // Obsahuje pozíciu v poli a obsah cyklu
if(is_array($a_Identifikator_Cyklu) && Count($a_Identifikator_Cyklu) > 0){
foreach ($a_Identifikator_Cyklu as $r_Identifikator_Cyklu => $r_Pozicia){
$r_Identifikator_Cyklu = reset( explode("|´#´|", $r_Identifikator_Cyklu) );
$a_ElseIf_in_Content = preg_split("#<!-- ELSEIF $r_Identifikator_Cyklu -> (.*?) -->#", $a_Content[$r_Pozicia+1], "-1", PREG_SPLIT_DELIM_CAPTURE ); // PRE IF - ELSEIF
$a_Else_in_Content = preg_split("#<!-- ELSE $r_Identifikator_Cyklu -->#",$a_Content[$r_Pozicia+1]); // PRE IF - ELSE
$a_Else_in_ElseIf = preg_split("#<!-- ELSE $r_Identifikator_Cyklu -->#",$a_ElseIf_in_Content[Count($a_ElseIf_in_Content)-1]); // PRE IF - ELSEIF - ELSE(!)
$a_ElseIf_in_Else = preg_split("#<!-- ELSEIF $r_Identifikator_Cyklu -> (.*?) -->#", $a_Else_in_Content[0], "-1", PREG_SPLIT_DELIM_CAPTURE ); // PRE IF - ELSEIF(!) - ELSE
if(!Empty($this -> Conditions[$r_Identifikator_Cyklu]) && $this -> Conditions[$r_Identifikator_Cyklu]){ /* Splnena IF podmienka */
$a_Conditions[$r_Pozicia] = null;
$a_Conditions[$r_Pozicia+1] = $a_ElseIf_in_Else[0];
} else { /* Nie je splnena IF podmienka */
if(Count($a_ElseIf_in_Content) > 1 || Count($a_Else_in_ElseIf) > 1 || Count($a_Else_in_Content) > 0){ /* Existuje ELSEIF alebo ELSE */
for($c_Current = 0; $c_Current < Count($a_ElseIf_in_Content); $c_Current = $c_Current + 2){ /* Posuvame sa v strome */
if($c_Current == ( Count($a_ElseIf_in_Content) - 1 ) && Count($a_Else_in_ElseIf) > 0){ /* Pokial je aktuálna vetva posledná v strome */
if(!Empty($a_ElseIf_in_Content[$c_Current-1]) && !Empty($this -> Conditions[$a_ElseIf_in_Content[$c_Current-1]]) && $this -> Conditions[$a_ElseIf_in_Content[$c_Current-1]]){ /* Pokial je to ELSEIF */
$a_Conditions[$r_Pozicia] = null;
$a_Conditions[$r_Pozicia+1] = $a_Else_in_ElseIf[0];
} else { /* Pokial je to ELSE */
$a_Conditions[$r_Pozicia] = null;
$a_Conditions[$r_Pozicia+1] = (!Empty($a_Else_in_ElseIf[1]))? $a_Else_in_ElseIf[1] : null;
} break;
} else { /* Pokial nie je posledna v strome */
if($this -> Conditions[$a_ElseIf_in_Content[$c_Current-1]]){
$a_Conditions[$r_Pozicia] = null;
$a_Conditions[$r_Pozicia+1] = $a_ElseIf_in_Content[$c_Current];
break;
}
}
}
}
}
}
$this -> Content = implode("",$a_Conditions);
}
}
if(preg_match("#<!-- IF (.*?) -->(.+?)<!-- END \\1 -->#", $this -> Content) > 0) $this -> Conditions();
}
/**
* @Values
* */
function Values() {
if(is_array($this -> Values) AND Count($this->Values) > 0){
foreach($this -> Values as $r_Key => $r_Value) {
$r_Value = str_replace("{","&{&&;",$r_Value);
$r_Value = str_replace("}","&}&&;",$r_Value);
$this -> Content = str_replace("{". $r_Key ."}", $r_Value, $this -> Content);
}}
if(!is_bool($this -> Clean)) $this -> Clean = true;
if($this -> Clean) $this -> Content = preg_replace("#{([^[:space:]\:\{\}\=\+\;]+)}#", "", $this -> Content);
$this -> Content = str_replace("&{&&;","{",$this -> Content);
$this -> Content = str_replace("&}&&;","}",$this -> Content);
}
/**
* @Show
* */
function Show() {
if(!is_bool($this -> Show)) $this -> Show = true;
if($this -> Show) echo $this -> Content;
}
/**
* @Others
* */
function SplitPage($array){
$a_Identifikator_Cyklu = array();
$a_Content = array();
$i = 0;
foreach($array as $r_ArrayName => $r_ArrayValue) {
$r_LocalInfo = round(($r_ArrayName/3)*10);
$r_LocalInfo = substr($r_LocalInfo, -1); /* získame buď 1, 3 alebo 7 */
if($r_LocalInfo == 3) $a_Identifikator_Cyklu[$r_ArrayValue. "|´#´|". $i] = $r_ArrayName;
elseif($r_LocalInfo == 7) $a_Content[$r_ArrayName] = $r_ArrayValue;
$i++;
/*
Celé je to cyklus 3 prvkov, pričom sú číslované:
0 - to čo je pred cyklom
1 - identifikátor cyklu
2 - obsah cyklu
Pre nás sú podstatné iba posledné 2
*/
}
return array($a_Identifikator_Cyklu,$a_Content);
}
}
/** Zrychlena funkcia **/
class QuickParse extends Parser {
function QuickParse($sb,$ar,$vp = true,$bl = null,$pm = null, $cl = true){
$this -> File = $sb;
$this -> Values = $ar;
$this -> Show = $vp;
$this -> Blocks = $bl;
$this -> Conditions = $pm;
$this -> Clean = $cl;
$this -> Parse();
}
}
?> |
Príklad s cyklami:
| kód: |
####### PHP:
<?php
include "config.php";
include_once "parser.php";
$SQL = mysql_query("SELECT * FROM user");
$i = 0;
while ($FETCH = mysql_fetch_array($SQL)) {
$Blocks["Content"][$i]["Nick"] = $FETCH["Nick"];
$Blocks["Content"][$i]["ID"] = $FETCH["ID"];
$i++;
}
$test = new parser;
$test -> File = "parser.tpl";
$test -> Values = array("Nadpis" => "Príklad 2. - Bloky", "Obsah" => "Toto je príklad na bloky");
$test -> Blocks = $Blocks;
$test -> Show = true;
$test -> Parse();
?>
####### TPL:
<h3>{Nadpis}</h3>
{Obsah}
<br>
<!-- BEGIN Content -->
{ID}:{Nick}<br>
<!-- END Content -->
|
Výsledok:
| kód: | Príklad 2. - Bloky
Toto je príklad na bloky
1:User1
2:User2
3:User5
5:User8
6:Tester
11:Comper |
|
| |
  |
 |
stenley
 Moderátor
 Založený: 27.07.2007 Príspevky: 3715 Bydlisko: Bratislava Vek: 26
 | Zaslal: St 25.02.09 23:30 |   |
Najdenie pozicie vyskytu podretazca v retazci
Autor: stenley
Popis:
| citácia: | | string strpos2 ( string $haystack, string $needle [, number $n=1 ] ) |
V php existuju vstavane funkcie na zistenie pozicie urciteho podretazca v zadanom retazci (texte). Vsetky umoznuju najst bud prvy alebo posledny vyskyt. Funkcia strpos2() predstavuje vylepsenu verziu standardnej funkcie strpos() v tom, ze mozete najst poziciu n-teho vyskytu v retazci, pricom je mozne vyhladavat zlava alebo zprava. Vratene cislo je pozicia podretazca od zaciatku textu. V pripade chyby vracia funkcia FALSE.
$n=-2 => najst predpredposledny vyskyt
$n=-1 => najst predposledny vyskyt
$n=0 => najst posledny vyskyt
$n=1 => najst prvy vyskyt
$n=2 => najst druhy vyskyt
| kód: | <?php
/**
* strpos2()
*
* Najdenie pozicie vyskytu podretazca v retazci
*
* @author stenley <stenley@webdev.sk>
* @version 1.0
*/
function strpos2($haystack, $needle, $n=1) {
if(strpos($haystack,$needle)===false) {
return false;
}
if($n<=0) {
$haystack = strrev($haystack);
$needle = strrev($needle);
$init = true;
}
$offset = 0;
for($i=(int)!isset($init); $i<=abs($n); $i++,$offset++) {
if(($offset = strpos($haystack,$needle,$offset))===false) {
return false;
}
}
return $n>0 ? $offset-1 : strlen($haystack)-$offset+1-strlen($needle);
}
?> |
Priklad pouzitia:
| kód: | $haystack = "abcabcabcabc";
$needle = "bc";
echo strpos2($haystack,$needle); //vypise 1
echo strpos2($haystack,$needle,2); //vypise 4
echo strpos2($haystack,$needle,0); //vypise 10
echo strpos2($haystack,$needle,-3); //vypise 1 |
|
_________________ Desktop: CPU: AMD Athlon64 3000+ | MB: Biostar K8T890-A9 | VGA: NVIDIA GeForce 6200 LE 256MB | RAM: 2x 1GB A-DATA DDR 400 MHz Dual Kit | HDD: WD Caviar Blue 320GB | DVD: LG GSA-H10N | Keyboard: Chicony KU-0420 Silver/Black | Mouse: Logitech RX1000 | Zdroj: Corsair CX400 400W | CASE: DELUX DLC-MD370 Black | LCD: 20" Samsung 206BW | Repro: Teac XL-20
Notebook: ACER Aspire 4820TG 14" | CPU: Intel Core i5 2,53 GHz | VGA: ATI Mobility Radeon HD5650 1GB / Intel HD Graphics | RAM: 4GB DDR3 1066 MHz | HDD: 640GB
Naposledy upravil stenley dňa St 19.01.11 20:50, celkom upravené 2 krát. | |
    |
 |
Flety
 Užívateľ
 Založený: 26.11.2006 Príspevky: 4109 Bydlisko: HE(Humenne) - KE Vek: 18
 | Zaslal: Št 26.02.09 18:42 |   |
Je súbor obrázok?
Autor: p360t, stenley, Snacker (korekcie)
Popis: Zistenie, či je súbor, resp. názov súboru, obrázok.
| kód: | function isImage($file) {
$suff = substr(strrchr($file, '.'), 1);
if(!preg_match('/^(jpe?g|gif|bmp|png)$/', $suff)) { //v pripade potreby treba doplnit dalsie formaty obrazkov
return false;
}
if(!function_exists('exif_imagetype')) {
$imgInfo = @getimagesize($file);
if(strstr($imgInfo['mime'],"image")!==false) {
return true;
}
} else {
if(@exif_imagetype($file)!==false) {
return true;
}
}
return false;
} | Použitie: | kód: | | if(isImage($nazov_suboru)) echo 'Je to obrázok'; |
//zmeneny povodny zdrojak za efektivnejsi (stenley) |
_________________ Desktop: CASE: Cooler Master Centurion 532 MB: ASUS P5K CPU: Intel Core 2 Quad Q6600@2,4GHz FSB 1066MHz RAM: A-Data Vitesta 2×2GB 800MHz Cl 5-5-5-12 GPU: Saphire ATi Radeon HD5850 Toxic HDD: Seagate Barracuda 500GB 7200rpm ODD1: LG DVD+/-RW + LS(PATA) ODD2:LG DVD+/-RW(SATA) PSU: Fortron Epsilon 700W LCD: LG L226W 1680x1050 2ms | |
       |
 |
Flety
 Užívateľ
 Založený: 26.11.2006 Príspevky: 4109 Bydlisko: HE(Humenne) - KE Vek: 18
 | Zaslal: Št 26.02.09 18:59 |   |
Výpis obsahu adresara
Autor: pravdepodobne Márius Rak(Flety)
Popis: Vypísanie všetkých súborov a priečinkov zo zadaného priečinka| kód: | $path = 'priečinok/';
$dir_handle = @opendir($path) or die("Unable to open $path");
while ($file = readdir($dir_handle))
{
if($file != '.' && $file != '..')
{
echo $file;
}
}
closedir($dir_handle); |
Prípadne ak chcete len súbory:| kód: | $path = 'priečinok/';
$dir_handle = @opendir($path) or die("Unable to open $path");
while ($file = readdir($dir_handle))
{
if($file != '.' && $file != '..')
{
if(is_file($file)echo $file);
}
}
closedir($dir_handle); |
Alebo len priečinky:| kód: | $path = 'priečinok/';
$dir_handle = @opendir($path) or die("Unable to open $path");
while ($file = readdir($dir_handle))
{
if($file != '.' && $file != '..')
{
if(is_dir($file)echo $file);
}
}
closedir($dir_handle); |
Použitie: Do premennej $path sa zadá priečinok. Ostatné sa už urobí samo. Tvar výpisu je možne upravovať, snaď všetci viete ako  |
_________________ Desktop: CASE: Cooler Master Centurion 532 MB: ASUS P5K CPU: Intel Core 2 Quad Q6600@2,4GHz FSB 1066MHz RAM: A-Data Vitesta 2×2GB 800MHz Cl 5-5-5-12 GPU: Saphire ATi Radeon HD5850 Toxic HDD: Seagate Barracuda 500GB 7200rpm ODD1: LG DVD+/-RW + LS(PATA) ODD2:LG DVD+/-RW(SATA) PSU: Fortron Epsilon 700W LCD: LG L226W 1680x1050 2ms | |
       |
 |
sedlák
 Užívateľ
 Založený: 16.07.2007 Príspevky: 863 Bydlisko: pp/za
 |
Zistenie veľkosti priečinka
Autor: neznámy (nájdené na nete)
Popis Pomocou tejto funkcie zistíte veľkosť daného priečinka
| kód: | function directory_size($directory) {
$directorySize=0;
if ($dh = @opendir($directory)) {
while (($filename = readdir ($dh))) {
if ($filename != "." && $filename != "..") {
if (is_file($directory."/".$filename)){
$directorySize += filesize($directory."/".$filename);
}
if (is_dir($directory."/".$filename)){
$directorySize += directory_size($directory."/".$filename);
}
}
}
}
@closedir($dh);
return $directorySize;
}
|
Konkrétny príklad vypíše veľkosť adresára foto v megabajtoch. :
| kód: |
$bajt = 1;
$kilobajt = 1024;
$megabajt = 1048576;
$directory = "foto/";
$totalSize = round((directory_size($directory) / $megabajt), 2);
echo "Veľkosť dát spolu: <br><b>".$totalSize. "</b>"; |
|
_________________ NB: msi gx623; Intel Core 2 Duo 2,00 GHz; 4 GB (2x 2048 MB) DDR2 800 MHz; ATI Mobility Radeon HD4670 s 512 MB; 15,4 "TFT LCD; win 7 ultimate | |
  |
 |
stenley
 Moderátor
 Založený: 27.07.2007 Príspevky: 3715 Bydlisko: Bratislava Vek: 26
 | Zaslal: Ut 24.03.09 11:02 |   |
Predpoved pocasia (Google)
Autor: stenley
Popis:
Nasledujuca trieda sluzi na ziskanie údajov o pocasi z Google API pre zadane mesto na niekolko dni. Informacie sa ukladaju do pola, ktoreho struktura je popisana v prikladoch pouzitia. Je to len ukazka, v reali by bolo vhodnejsie a rychlejsie xml-ko najskor stiahnut, ulozit na disk (napr. cez cron kazdu hodinu) a nasledne s nim pracovat. Takisto, pouzit vlastne obrazky, tj. neziskavat ich z google.com. V pripade, ze je zadane mesto, ktore Google nepozna, vracia sa prazdne pole.
| kód: | <?php
/**
* GoogleWeather
*
* Predpoved pocasia (google)
*
* @author stenley <stenley@webdev.sk>
* @version 1.1
*/
class GoogleWeather {
var $lang = "sk";
var $country = "Slovakia";
var $charset = "utf-8";
function getWeatherObj($city) {
$city = urlencode($city);
$data = @file_get_contents("http://www.google.com/ig/api?weather=".$city.",".$this->country."&hl=".$this->lang);
if(!$data) {
return false;
}
$data = iconv("ISO-8859-2",$this->charset,$data);
return new SimpleXMLElement($data);
}
function getWeatherInfo($city) {
$weather = array();
$obj = $this->getWeatherObj($city);
if(is_object($obj)) {
$data = $obj->xpath("/xml_api_reply/weather/current_conditions");
if(!empty($data)) {
$weather[] = array(
"condition" => $this->getAttr($data[0]->xpath("condition")),
"temp_f" => $this->getAttr($data[0]->xpath("temp_f")),
"temp_c" => $this->getAttr($data[0]->xpath("temp_c")),
"humidity" => $this->getAttr($data[0]->xpath("humidity")),
"icon" => $this->getAttr($data[0]->xpath("icon")),
"wind_condition" => $this->getAttr($data[0]->xpath("wind_condition"))
);
}
$data = $obj->xpath("/xml_api_reply/weather/forecast_conditions");
if(!empty($data)) {
foreach($data as $value) {
$weather[] = array(
"day_of_week" => $this->getAttr($value->xpath("day_of_week")),
"low" => $this->getAttr($value->xpath("low")),
"high" => $this->getAttr($value->xpath("high")),
"icon" => $this->getAttr($value->xpath("icon")),
"condition" => $this->getAttr($value->xpath("condition"))
);
}
}
}
return $weather;
}
function getAttr($obj) {
if(is_object($obj[0])) {
$attr = $obj[0]->attributes();
}
return (isset($attr['data'])) ? (string)$attr['data'] : '';
}
}
?> |
Priklad pouzitia:
| kód: | $gw = new GoogleWeather();
$weather = $gw->getWeatherInfo("Bratislava"); //pocasie pre Bratislavu
print_r($weather);
//$weather = $gw->getWeatherInfo("Kosice"); //pocasie pre Kosice
//print_r($weather); |
Vysledok:
| kód: | Array
(
[0] => Array
(
[condition] => Prevažne oblačno
[temp_f] => 45
[temp_c] => 7
[humidity] => Vlhkosť: 61%
[icon] => /images/weather/mostly_cloudy.gif
[wind_condition] => Vietor: J s rýchlosťou 0 km/h
)
[1] => Array
(
[day_of_week] => Ut
[low] => -2
[high] => 8
[icon] => /images/weather/chance_of_rain.gif
[condition] => Občasný dážď
)
[2] => Array
(
[day_of_week] => St
[low] => 2
[high] => 5
[icon] => /images/weather/chance_of_snow.gif
[condition] => Občasné sneženie
)
[3] => Array
(
[day_of_week] => Št
[low] => 1
[high] => 8
[icon] => /images/weather/chance_of_rain.gif
[condition] => Občasný dážď
)
[4] => Array
(
[day_of_week] => Pi
[low] => 0
[high] => 10
[icon] => /images/weather/chance_of_rain.gif
[condition] => Občasný dážď
)
) |
Vysvetlivky:
| kód: | [0] - pole s aktualnym pocasim
[1] - pole s pocasim na dnes
[2] - pole s pocasim na zajtra
[3] - pole s pocasim na pozajtra
[4] - pole s pocasim na popozajtra
[condition] - slovny popis pocasia
[temp_f] - teplota vo F
[temp_c] - teplota v C
[humidity] - vlhkost vzduchu
[icon] - obrazok (slnko, dazd, ...)
[wind_condition] - veterne podmienky
[day_of_week] - skratka nazvu dna
[low] - najnizsia teplota
[high] - najvyssia teplota |
Prakticky priklad:
| kód: | $gw = new GoogleWeather();
$arrCity = array("Bratislava","Kosice","Poprad","Zilina","Nitra","Trnava","Trencin");
$content = '<table>';
foreach($arrCity as $city) {
$weather = $gw->getWeatherInfo($city);
if(!empty($weather)) {
$content .= '<tr>';
$content .= '<td rowspan="2"><img src="'.$weather[1]['icon'].'"></td>';
$content .= '<td width="120"><strong>'.$city.'</strong></td>';
$content .= '<td>'.$weather[1]['high'].'°C / '.$weather[1]['low'].'°C</td>';
$content .= '</tr><tr>';
$content .= '<td colspan="2">'.$weather[1]['condition'].'</td>';
$content .= '</tr>';
}
}
$content .= '</table>';
echo $content; |
|
_________________ Desktop: CPU: AMD Athlon64 3000+ | MB: Biostar K8T890-A9 | VGA: NVIDIA GeForce 6200 LE 256MB | RAM: 2x 1GB A-DATA DDR 400 MHz Dual Kit | HDD: WD Caviar Blue 320GB | DVD: LG GSA-H10N | Keyboard: Chicony KU-0420 Silver/Black | Mouse: Logitech RX1000 | Zdroj: Corsair CX400 400W | CASE: DELUX DLC-MD370 Black | LCD: 20" Samsung 206BW | Repro: Teac XL-20
Notebook: ACER Aspire 4820TG 14" | CPU: Intel Core i5 2,53 GHz | VGA: ATI Mobility Radeon HD5650 1GB / Intel HD Graphics | RAM: 4GB DDR3 1066 MHz | HDD: 640GB
Naposledy upravil stenley dňa Št 26.05.11 20:40, celkom upravené 7 krát. | |
    |
 |
incredible
 Užívateľ
 Založený: 11.02.2009 Príspevky: 1030
 | Zaslal: So 04.04.09 12:14 |   |
Kalendar
Autor: Ja
Funkcia: Zobrazi stlpcovi kalendar (aktualny mesiac) a farebne vyznaci aktualny den
Verzia PHP: funguje pod PHP 5.1.0 a vyssie, nizsie verzie netestovane
| kód: |
<?php
$mesiac=date("m");$rok=date("Y"); //zistenie mesiaca a roka
$prvyDen=date("w",mktime(0,0,0,$mesiac,1,$rok)); //ktorym dnom zacina mesiac, marec 2009 zacina nedelou cize 7. dnom
if ($prvyDen==0) $prvyDen=7; //nedela je 0. den, cize podmienka zabezpeci aby bol 7.
$pocetDni=date("t",mktime(0,0,0,$mesiac,1,$rok)); //pocet dni v mesiaci
$pocetStlpcov=ceil(($pocetDni+$prvyDen-1)/7); //kolko stlpcov bude kalendar potrebovat, bud 4,5 alebo 6
$cislo=0; //pomocou inkremetacie tohto cisla sa vyplna pole kalendara
$pole[$pocetStlpcov-1][7-1]; //pole kalendara
$month=Array(1=>"Januar","Februar","Marec","April","Maj","Jun","Jul","August","September","Oktober","November","December");
for ($st=0; $st<$pocetStlpcov; $st++) //cyklus pre vyplnenie formulara
for ($ri=0; $ri<7; $ri++) /*dni prveho tyzdna v kalendary ktore patria do minuleho mesiaca,takisto aj dni
posledneho tyzdna patriace do dalsieho mesiaca sa vyplnia nulov */
if ((($ri<$prvyDen-1)&&($st==0)) ||($cislo>=$pocetDni)) {$pole[$st][$ri]=0;}
else {$cislo++; $pole[$st][$ri]=$cislo;} //vyplnenie pola inkrementujucou prem. $cislo (od 1 do $pocetDni)
//hlavicka kalendara
echo "<TABLE border=\"1\" style=\"border-collapse:collapse\"><th height=\"30\" bgcolor=\"gray\" colspan=\"8\">".$month[(int)$mesiac]." ".date("Y")."</th> ";
//cyklus pre vypisanie tabulky, pole sa vypisuje opacne (po riadkoch, naplnane bolo po stlpcoch)
for ($ri=0;$ri<7; $ri++){ echo "<tr><td bgcolor=\"lightblue\">"; //riadky, farba prveho stlpca s dnami
//vyplnenie prveho stlpca tabulky nazvami dnov podla toho na ktorom riadku cyklus je
if ($ri==0) echo "Pondelok";if ($ri==1) echo "Utorok";if ($ri==2) echo "Streda";
if ($ri==3) echo "Stvrtok";if ($ri==4) echo "Piatok";if ($ri==5) echo "Sobota";
if ($ri==6) echo "Nedela";echo "</td>";
for ($st=0; $st<$pocetStlpcov; $st++) { //vypise jednotlive bunky riadku
echo "<td ";
if ($pole[$st][$ri]==date("d")) echo "bgcolor=\"lightgray\" "; //farba bunky s aktualnym datumom
echo "style=\"text-align:center;width:22;height:25;\">"; //format buniek
if ($pole[$st][$ri]==0) echo " "; //vypise medzeru ak ma pole hodnotu 0
else echo $pole[$st][$ri]; //inak vypise hodnotu pola (cislo dna - prem $cislo)
echo"</td>"; }
echo "</tr>"; }
echo "</table>"
?> |
Alternatívny kód kalendára
| kód: | <?php
/**
* @author stenley <stenley@webdev.sk>
* @version 1.0
*/
$month = date('n'); //cislo mesiaca
$year = date('Y'); //rok
$weekday_abbr = array(1 => 'Po', 'Ut', 'St', 'St', 'Pi', 'So', 'Ne');
$mktime = mktime(0, 0, 0, $month, 1, $year); //mktime pre 1.den daneho mesiaca a roku
$month_days = date('t', $mktime); //pocet dni v mesiaci
$weekday_first = date('N', $mktime); //den v tyzdni, kedy je prveho
$days = range(1, $month_days);
$days = array_pad($days, -($weekday_first + $month_days - 1), ' ');
$days = array_pad($days, ceil(count($days) / 7) * 7, ' ');
$days = array_chunk($days, 7);
echo '<table><tr><th>'.implode('</th><th>', $weekday_abbr).'</th></tr>';
foreach($days as $week)
{
echo '<tr>';
foreach($week as $day)
{
echo '<td>'.$day.'</td>';
}
echo '</tr>';
}
echo '</table>';
?> |
|
| |
  |
 |
stenley
 Moderátor
 Založený: 27.07.2007 Príspevky: 3715 Bydlisko: Bratislava Vek: 26
 | Zaslal: Ut 23.06.09 22:01 |   |
Export dat z MySQL do XML
Autor: stenley
Poziadavky: PHP5
Popis:
Trieda MySQL2XML sluzi na export dát z MySQL do XML. Umoznuje ulozit vysledok lubovolneho sql prikazu, exportovat data z urcitych tabuliek alebo celej databazy. Trieda neriesi pripojenie k databaze.
| kód: | <?php
/**
* MySQL2XML
*
* Export dat z MySQL do XML
*
* @author stenley <stenley@webdev.sk>
* @version 1.0
*/
class MySQL2XML
{
private $dom;
public $database = '';
public $tables = array();
public $formatOutput = TRUE;
public $encoding = 'utf-8';
public $rootElement = 'export';
public $rowElement = 'row';
public function generate($query = NULL) {
$this->dom = new DOMDocument('1.0', $this->encoding);
$this->dom->formatOutput = $this->formatOutput;
$rootElm = $this->addElement($this->dom, $this->rootElement);
if(!is_null($query)) {
$res = @mysql_query($query);
if($res !== FALSE) {
if(@mysql_num_rows($res) > 0) {
$arrCols = $this->getCols($res);
while($row = @mysql_fetch_assoc($res)) {
$rowElm = $this->addElement($rootElm, $this->rowElement);
foreach($arrCols as $colname) {
$colElm = $this->addElement($rowElm, $colname, $row[$colname]);
}
}
return TRUE;
}
}
} else {
if(empty($this->tables)) {
$this->getTables();
}
foreach($this->tables as $table) {
$res = @mysql_query('SELECT * FROM '.$table);
if($res !== FALSE) {
if(@mysql_num_rows($res) > 0) {
$arrCols = $this->getCols($res);
$tableElm = $this->addElement($rootElm, $table);
while($row = @mysql_fetch_assoc($res)) {
$rowElm = $this->addElement($tableElm, $this->rowElement);
foreach($arrCols as $colname) {
$colElm = $this->addElement($rowElm, $colname, $row[$colname]);
}
}
}
}
}
return TRUE;
}
return FALSE;
}
public function save($file) {
if(!empty($file)) {
$fp = @fopen($file, 'w');
if($fp !== FALSE) {
@fwrite($fp, $this->getXML());
}
}
}
public function getXML() {
return $this->dom->saveXML();
}
private function addElement(&$root, $name, $value = null, $attributes = array()) {
if(is_null($value)) {
$elm = $this->dom->createElement($name);
} else {
$elm = $this->dom->createElement($name, $value);
}
foreach($attributes as $attrName => $attrValue) {
$attr = $this->dom->createAttribute($attrName);
$elm->appendChild($attr);
$value = $this->dom->createTextNode($attrValue);
$attr->appendChild($value);
}
$root->appendChild($elm);
return $elm;
}
private function getCols($res) {
$arrCols = array();
$numCols = @mysql_num_fields($res);
for($i = 0; $i < $numCols; $i++) {
$arrCols[] = @mysql_field_name($res, $i);
}
return $arrCols;
}
private function getTables() {
if($this->database == '') {
return FALSE;
}
$res = @mysql_query('SHOW TABLES FROM '.$this->database);
if($res !== FALSE) {
$this->tables = array();
while($row = @mysql_fetch_assoc($res)) {
$this->tables[] = array_shift($row);
}
}
}
}
?> |
Priklady pouzitia:
1. Konkretny sql prikaz (vypis vysledneho xml retazca):
| kód: | $export = new MySQL2XML();
$export->generate("SELECT * FROM tblname");
echo $export->getXML(); |
2. Vybrane tabulky (vypis vysledneho xml retazca):
| kód: | $export = new MySQL2XML();
$export->tables = array('tblname1', 'tblname2');
$export->generate();
echo $export->getXML(); |
3. Cela databaza (vypis vysledneho xml retazca):
| kód: | $export = new MySQL2XML();
$export->database = 'dbname';
$export->generate();
echo $export->getXML(); |
4. Ak chcete namiesto vypisania ulozit vysledny xml retazec do suboru napr. mysql.xml:
| kód: | | $export->save('mysql.xml'); |
|
_________________ Desktop: CPU: AMD Athlon64 3000+ | MB: Biostar K8T890-A9 | VGA: NVIDIA GeForce 6200 LE 256MB | RAM: 2x 1GB A-DATA DDR 400 MHz Dual Kit | HDD: WD Caviar Blue 320GB | DVD: LG GSA-H10N | Keyboard: Chicony KU-0420 Silver/Black | Mouse: Logitech RX1000 | Zdroj: Corsair CX400 400W | CASE: DELUX DLC-MD370 Black | LCD: 20" Samsung 206BW | Repro: Teac XL-20
Notebook: ACER Aspire 4820TG 14" | CPU: Intel Core i5 2,53 GHz | VGA: ATI Mobility Radeon HD5650 1GB / Intel HD Graphics | RAM: 4GB DDR3 1066 MHz | HDD: 640GB
Naposledy upravil stenley dňa St 19.01.11 20:51, celkom upravené 1 krát. | |
    |
 |
Flety
 Užívateľ
 Založený: 26.11.2006 Príspevky: 4109 Bydlisko: HE(Humenne) - KE Vek: 18
 | Zaslal: St 08.07.09 13:21 |   |
Skopírovanie všetkých súborov zo zadaného priečinka na FTP
Autor:Márius Rak(Flety)
Popis: Skopíruje všetky súbory z priečinku na FTP do priečinku na vašom serveri| kód: | function ftp_full_copy($connect, $source, $target, $lenght)
{
foreach(ftp_nlist($connect, $source) as $file)
{
if(substr($file, -1) == '.' || substr($file, -2) == '..')
{
continue;
}
if(ftp_size($connect, $file) == -1)
{
@mkdir('../'.substr($file, 15 + $lenght));
ftp_full_copy($connect, $file, $target, $lenght);
}
else
{
ftp_get($connect, '..'.substr($file, 15 + $lenght), $file, FTP_BINARY);
}
}
} | Použitie:| kód: | //Pripojenie k FTP
$connect = ftp_connect('ftp.server');
$login_result = ftp_login($connect, 'meno', 'heslo');
//Použitie funkcie
ftp_full_copy($connect, 'zdroj/na/FTP', 'ciel/na/vasom/serveri', strlen('zdroj/na/FTP')); |
|
_________________ Desktop: CASE: Cooler Master Centurion 532 MB: ASUS P5K CPU: Intel Core 2 Quad Q6600@2,4GHz FSB 1066MHz RAM: A-Data Vitesta 2×2GB 800MHz Cl 5-5-5-12 GPU: Saphire ATi Radeon HD5850 Toxic HDD: Seagate Barracuda 500GB 7200rpm ODD1: LG DVD+/-RW + LS(PATA) ODD2:LG DVD+/-RW(SATA) PSU: Fortron Epsilon 700W LCD: LG L226W 1680x1050 2ms | |
       |
 |
emer
 Užívateľ
 Založený: 26.12.2006 Príspevky: 3451 Bydlisko: Nitra Vek: 18
 | Zaslal: Št 09.07.09 22:05 |   |
Export dat z MySQL do .sql súboru
Autor: emer (http://emer.grafika4u.sk/clanky/php-mysql/export-dat-z-mysql-do-sql-suboru)
Požiadavky: PHP5, MySQL
Popis: Potrebujete exportovať svoju databázu ako SQL príkaz/y za pomoci PHP ? Táto trieda Vám to umožňuje, so základnými možnostami. (používať auto_increment, if not exists, drop table?). Výsledný SQL dotaz možete uložiť do .sql súboru alebo vypísať priamo v scripte.
| kód: | class BackUpDB{
var $DropTables = false;
var $AddIfNotExists = false;
var $AddAI = true;
var $FileName = '';
function __construct($host, $user, $pass, $database){
$link = mysql_connect($host,$user,$pass) or die(mysql_error());
mysql_select_db($database,$link) or die(mysql_error());
}
function GenerateSQL($Tables = ''){
$SQL = '';
if($Tables == ''){
$ShowTables = mysql_query("SHOW TABLES");
$Tables = array();
while($r = mysql_fetch_array($ShowTables)){
$Tables[] = $r[0];
}
}else{
$Tables = is_array($Tables) ? $Tables : explode(',', $Tables);
}
foreach($Tables as $Table){
$CreateTable = mysql_query("SHOW CREATE TABLE `$Table`");
if($this->DropTables == true){
$SQL .= 'DROP TABLE `'.$Table.'`;'."\n\n";
}
$SQL .= mysql_result($CreateTable, 0, 1).";\n\n";
$Data = mysql_query("SELECT * FROM `$Table`");;
$DescribeTable = mysql_query("DESCRIBE `$Table`");
$Fields = array();
while($r = mysql_fetch_array($DescribeTable)){
$Fields[] = $r['Field'];
}
$DataNum = mysql_num_rows($Data);
if($DataNum != 0){
$SQL .= 'INSERT INTO `'.$Table.'` (';
for($i=0;$i<count($Fields);$i++){
$SQL .= '`'.$Fields[$i].'`'.($i == count($Fields)-1 ? '' : ', ');
}
$SQL .= ') VALUES '."\n";
$Y = 0;
while($r = mysql_fetch_array($Data)){
$Y++;
$SQL .= '(';
$FieldsNum = count($r);
for($i=0;$i<$FieldsNum/2;$i++){
$SQL .= (is_numeric($r[$i]) || $r[$i] == 'NULL' ? $r[$i] : '\''.$r[$i].'\'').($i < ($FieldsNum/2)-1 ? ', ' : '');
}
$SQL .= ($Y == $DataNum ? ')' : '),'."\n");
}
}
$SQL .= ";\n\n";
}
if($this->AddAI == false){
$SQL = preg_replace("/AUTO_INCREMENT=([0-9]{1,})/", "", $SQL);
}
if($this->AddIfNotExists == true){
$SQL = str_replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS', $SQL);
}
if($this->FileName == ''){
return $SQL;
}else{
if(!(substr($this->FileName, -4) == '.sql')){
$this->FileName .= '.sql';
}
$handle = fopen($this->FileName,'w+');
fwrite($handle,$SQL);
fclose($handle);
return $this->FileName.' úspešne vygenerovaný.';
}
}
} |
Použitie:
| kód: | $BackUp = new BackUpDB('localhost', 'root', '', 'dbname');
$BackUp->DropTables = true; //poskytneme zmazanie tabuliek
$BackUp->AddIfNotExists = true; //ku CREATE TABLE pridáme IF NOT EXISTS
$BackUp->AddAI = true; //do štruktúry pridáme aj nasledujúci AI
$BackUp->FileName = 'zalohadatabazy'; //zadáme meno súboru
echo $BackUp->GenerateSQL(); //vygenerujeme SQL dotazy pre všetky tabulky. Ak by sme chceli exportovať iba štruktúru a obsah tabuliek tblname1 a tblname2, zadáme $BackUp->GenerateSQL('tblname1,tblname2'); |
|
_________________ PODPIS BOL ZMAZANY Z DOVODU NERESPEKTOVANIA PRAVIDIEL FORA!!!
Luks | |
    |
 |
VireL
 Užívateľ
 Založený: 19.12.2009 Príspevky: 10
 | Zaslal: So 19.12.09 21:52 |   |
Autor: VireL
Popis: Script pre upload s funkciou povolenia pripon(whitelist)
Uploadne subor s povolenou priponou a velkostou do zvoleneho vytvoreneho priecinka.
Pripony zadavajte bez bodiek.
| kód: | <?php
###########################
#------Upload script------#
#--------By VireL---------#
#----------For------------#
#-http://www.pcforum.sk/--#
#------Thx for using------#
###########################
//Velkost v B
define("VELKOST", "150528");
//Priecinok kde ukladat subory
$priecinok = "uploads";
//Povolene pripony
$pripony = array("gif", "GIF", "jpg", "JPG", "jpeg", "JPEG", "png", "PNG", "rar", "RAR", "zip", "ZIP");
//Rozdelenie pripon
$b = 0;
foreach($pripony as $pripona)
{
$b++;
if(count($pripony) == $b)
{$allow .= "\.".$pripona;}
else
{$allow .= "\.".$pripona."|";}
}
//Urcenie ID nazvu suboru, podla poctu suborov
$id = 0;
$open = opendir($priecinok);
while ($files = readdir($open))
{
$filename = $files;
if ($filename != "." and $filename != "..")
{
$id++;
}
}
//Formular
echo "<form method='post' action'".$_SERVER['PHP_SELF']."' enctype='multipart/form-data'>";
echo "<input type='file' name='subor'><br>";
echo "<input type='submit' name='upload' value='Upload'></form>";
//Podmienka ci bol odoslany formular, ci subor existuje a ci pripona suhlasi
if(isset($_POST['upload']) and
is_uploaded_file($_FILES["subor"]["tmp_name"]) and
preg_match("/(".$allow.")$/", $_FILES["subor"]["name"]))
{
if($_FILES["subor"]["size"] <= VELKOST)//Kontrola velkosti
{
if(!file_exists($priecinok."/".$id."-".$_FILES["subor"]["name"]))//Ci neexistuje subor s rovnakym menom
{
$meno = $id."-".$_FILES["subor"]["name"];
move_uploaded_file($_FILES["subor"]["tmp_name"], $priecinok."/".$meno);
}
else//Ak ano funkcia rand() zvoli nahodnu hodnotu
{
$meno = $id."-".rand(0, 99999)."-".$id."-".$_FILES["subor"]["name"];
move_uploaded_file($_FILES["subor"]["tmp_name"], $priecinok."/".$meno);
}
echo "<a href='".$priecinok."/".$meno."'>Link na subor</a>";//Link na subor
}
else//Ak je velkost presahujuca
{
echo "Subor je prilis velky :(";
}
}
?> |
|
| |
  |
 |
neXor
 Užívateľ
 Založený: 27.06.2009 Príspevky: 75 Bydlisko: Levice, Slovensko
 | Zaslal: Št 24.12.09 11:21 |   |
Oseknutie reťazca po medzere
Autor: neXor
Poziadavky: PHP5
Popis:
Funkcia cutString oreže reťazec na určitú veľkosť, bez toho aby reťazec orezalo v strede slova. Na koniec pridá tri bodky (...).
| kód: | <?php
/*
* Oseknutie reťazca
*
* Oseknutie reťazca na určitú veľkosť
*
* @author neXor <neXor.sk@gmail.com>
* @version 1.1
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/
function cutString ( $text, $limit = 20, $end = "..." ) {
if ( strlen ( $text ) <= $limit ) {
return $text;
} else {
$po = substr ( $text, 0, $limit );
$pos = strrpos ( $po, " " );
$koniec = substr ( $po, 0, $pos );
return $koniec . $end;
}
}
?> |
Príklad použitia
| kód: | $text = "Ahoj, ako sa mas? Ja sa mam dobre a ty?";
cutString ( $text ); |
|
| |
    |
 |
|
Nemôžete pridávať nové témy do tohto fóra. Nemôžete odpovedať na témy v tomto fóre. Nemôžete upravovať svoje príspevky v tomto fóre. Nemôžete mazať svoje príspevky v tomto fóre. Nemôžete hlasovať v tomto fóre.
|
|