Source codes, small scripts...

Collapse
This is a sticky topic.
X
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • arnage
    replied
    Easy way to make every first letter in a sentence uppercase.

    PHP Code:
    function capsfirst_sentence($string) {
    
        return empty($string) ? '' : preg_replace('/\b(\w)/e', 'strtoupper("$1")', $string);
    
    } 
    

    Leave a comment:


  • arnage
    replied
    I just got idea from this topic: http://coding-talk.com/f14/count-fil...-script-10983/

    PHP Code:
    function count_files($dir_path = '', $what = '') {
        $count = count(glob($dir_path.'/*.'.$what.''));
        return echo 'There is '.($count > 1 
                ? '<b>'.$count.'</b> files' : ($count == 1 
                ? '<b>one</b> file' : '<b>no files</b>')).' in '.dirname($dir_path).'<br/>'.PHP_EOL;
    }
    //
    count_files('downloads/images', 'jpg');
    count_files('downloads/images', 'jpg|jpeg');
    count_files('downloads/videos', '3gp');
    count_files('downloads/videos', '3gp|mp4'); 
    

    Leave a comment:


  • arnage
    replied
    Random readable password

    PHP Code:
    function random_readable_pwd($length=10){
     
        // the wordlist from which the password gets generated 
        // (change them as you like)
        $words = 'dog,cat,sheep,sun,sky,red,ball,happy,ice,';
        $words .= 'green,blue,music,movies,radio,green,turbo,';
        $words .= 'mouse,computer,paper,water,fire,storm,chicken,';
        $words .= 'boot,freedom,white,nice,player,small,eyes,';
        $words .= 'path,kid,box,black,flower,ping,pong,smile,';
        $words .= 'coffee,colors,rainbow,plus,king,tv,ring';
     
        // Split by ",":
        $words = explode(',', $words);
        if (count($words) == 0){ die('Wordlist is empty!'); }
     
        // Add words while password is smaller than the given length
        $pwd = '';
        while (strlen($pwd) < $length){
            $r = mt_rand(0, count($words)-1);
            $pwd .= $words[$r];
        }
     
        // append a number at the end if length > 2 and
        // reduce the password size to $length
        $num = mt_rand(1, 99);
        if ($length > 2){
            $pwd = substr($pwd,0,$length-strlen($num)).$num;
        } else { 
            $pwd = substr($pwd, 0, $length);
        }
     
        return $pwd;
     
    } 
    
    random_readable_pwd(10) => returns something like: pingwater6, radiohap28, sunwhite84, happykid44, etc...

    Leave a comment:


  • kiss
    replied
    Anti Xss

    PHP Code:
     function anti_xss( $string, $type )
     {
      switch ( $type ) {
       case "int":
        $string = ( int )$string ;
        break ;
       case "mysql":
        $string = mysql_real_escape_string( $string ) ;
        break ;
       case "nohtml":
        $string = htmlentities( $string , ENT_QUOTES, "UTF-8" ) ; // or ISO-8859-2 for romanian charset
        break ;
      }
      return $string ;
     }
    
    //- int, use it for parameters with numbers. Example: 
    $uid = anti_xss($_GET["uid"], "int"); // profil.php?uid=25
    
    //- mysql, use it for parameters with data base. Example: 
    $pass = anti_xss($_POST["pass"], "mysql"); // INSERT INTO `x_table` WHERE `pass`='".$pass."'
    
    //- nohtml, use it for showing information on site. Example: 
    $text = "Playromania it kid and write <script>alert("Im nobody and a lost soul on the net :D");</script>";
    echo anti_xss($text, "nohtml"); 
    
    Last edited by arnage; 06.09.12, 19:41.

    Leave a comment:


  • i0nutzxp
    replied
    PHP browser Debugger

    Function to be included in functions list:
    PHP Code:
    function console_log()
    {
        $args = func_get_args();        
        $argsSize = count($args);
            
        if ($argsSize == 0)
        {
            return false;
        }
        
        if ($argsSize == 1)
        {
            $output = sprintf($args[0]);
        }
        else
        {
            $output = call_user_func_array('sprintf', $args);
        }         
        $output = str_replace(array("\r", "\n"), '', $output);    
        echo '<script type="text/javascript"> if ( ! window.console) console = {}; console.log = console.log || function(name, data){}; console.log("'.$output.'"); </script>';                           
    } 
    
    Usage:

    PHP Code:
    class Test
    {
        private $test = 2;
    }
    
    console_log(print_r(new Test(), true));
    
    $day = 21;
    console_log("%d %s %d", $day, 'Dec', 2004); 
    console_log("Code at line %d .", __LINE__);
    console_log(print_r($days, true));
    
    echo 'Hellow world!'; 
    
    Just open browser console to use this tool.

    Leave a comment:


  • arnage
    replied
    Get last modified time of a dir (when a file changed in dir) (from php.net comments)

    PHP Code:
    function dirmtime($dir) {
         $last_modified = 0;
         $files = glob($dir.'/*');
         foreach ($files as $file) {
             if (is_dir($file)) {
                 $modified = dirmtime($file);
             } else {
                 $modified = filemtime($file);
             }
             if ($modified > $last_modified) {
                 $last_modified = $modified;
             }
         }
         return $last_modified;
    } 
    
    Random color

    PHP Code:
    function random_color(){
        mt_srand((double)microtime()*1000000);
        $c = '';
        while(strlen($c)<6){
            $c .= sprintf("%02X", mt_rand(0, 255));
        }
        return $c;
    }
    
    random_color() // => returns something like: '7C42BA', '5F3964' 
    
    File download with speed limit

    PHP Code:
    // local file that should be send to the client
    $local_file = 'test-file.zip';
     
    // filename that the user gets as default
    $download_file = 'your-download-name.zip';
     
    // set the download rate limit (=> 20,5 kb/s)
    $download_rate = 20.5;
     
    if(file_exists($local_file) && is_file($local_file)) {
     
        // send headers
        header('Cache-control: private');
        header('Content-Type: application/octet-stream');
        header('Content-Length: '.filesize($local_file));
        header('Content-Disposition: filename='.$download_file);
     
        // flush content
        flush();
     
        // open file stream
        $file = fopen($local_file, "r");
     
        while (!feof($file)) {
     
            // send the current file part to the browser
            print fread($file, round($download_rate * 1024));
     
            // flush the content to the browser
            flush();
     
            // sleep one second
            sleep(1);
        }
     
        // close file stream
        fclose($file);
     
    }
    else {
        die('Error: The file '.$local_file.' does not exist!');
    } 
    
    Last edited by arnage; 23.08.12, 17:23.

    Leave a comment:


  • arnage
    replied
    Easy way to just cut the string or cut it with three dots like etc.

    PHP Code:
    function cutout($string, $howmuch, $etc = false) {
        return mb_strlen($string, 'UTF-8') > $howmuch 
        ? mb_substr($string, 0, $howmuch, 'UTF-8').($etc !== false ? '...' : '') : $string;
    } 
    
    Example with ...
    PHP Code:
    $string = 'Some too long string';
    $string = cutout($string, 10, true);
    echo $string; //Some too l... 
    

    Leave a comment:


  • arnage
    replied
    This is just a kind of slightly extended this idea, the usage has remained very much the same.
    Original function

    PHP Code:
    function openFile($file, $mode, $input, $marker = "") {
        if ($mode == 'READ') {
            if (is_readable($file)) {
                $handle = @fopen($file, 'r');
                $output = fread($handle, filesize($file));
                return $output;
            } else {
                return false;
            }
        } elseif ($mode == 'ECHO') {
            if (is_file($file)) {
                return str_replace(PHP_EOL, "<br/>", htmlentities(file_get_contents($file), ENT_QUOTES | ENT_IGNORE, 'UTF-8'));
            } else {
                return false;
            }
        } elseif ($mode == 'WRITE') {
            if (is_writeable($file) && !empty($input)) {
                $handle = @fopen($file, 'w');
                if (!fwrite($handle, $input)) {
                    return false;
                } else {
                    return true;
                }
            } else {
                return false;
            }
        } elseif ($mode == 'EDITBACK') {
            if (is_file($file) && !empty($input)) {
                $handle = @fopen($file, 'r+');
                $read = fread($handle, filesize($file));
                $data = $read.$input;
                if (!fwrite($handle, $data)) {
                    return false;
                } else {
                    return true;
                }
            } else {
                return false;
            }
        } elseif ($mode == 'EDITBEGIN') {
            if (is_file($file) && !empty($input)) {
                $handle = @fopen($file, 'r+');
                $read = fread($handle, filesize($file));
                $data = $input.$read;
                if (!fwrite($handle, $data)) {
                    return false;
                } else {
                    return true;
                }
            } else {
                return false;
            }
        } elseif ($mode == 'UPDATE') {
            if (is_writeable($file) && !empty($input)) {
                $marker = empty($marker) ? "\n" : $marker;
                $handle = @fopen($file, 'a');
                $data = $input.$marker;
                if (!fwrite($handle, $data)) {
                    return false;
                } else {
                    return true;
                }
            } else {
                return false;
            }
        } elseif ($mode == 'CLEAR') {
            if (is_file($file)) {
                $handle = @fopen($file, 'a+');
                if (ftruncate($handle, 0)) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } elseif ($mode == 'DELFILE') {
            if (is_file($file)) {
                if (!unlink($file)) {
                    return false;
                } else {
                    return true;
                }
            } else {
                return false;
            }
        } elseif ($mode == 'CRTDIR') {
            if (!empty($file) && !is_dir($file)) {
                if (!mkdir($file)) {
                    return false;
                } else {
                    return true;
                }
            } else {
                return false;
            }
        } elseif ($mode == 'DELDIR') {
            if (!empty($file) && is_dir($file)) {
                if (!rmdir($file)) {
                    return false;
                } else {
                    return true;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
        fclose($handle);
        clearstatcache();
    } 
    

    Leave a comment:


  • arnage
    replied
    This validates case-insensitive e-mail addresses like:

    Code:
    name@mail.com
    name.lastname@mail.com
    name.lastname@some-mail.com
    and so on.

    PHP Code:
    function validemail($string) {
        if (preg_match('/^[a-z0-9\._-]+@[a-z0-9\.-]+\.[a-z]{2,4}$/iD', $string)) {
            return true;
        } else {
            return false;
        }
    } 
    
    This simple function can be used to set the hours time in the whole script at once or remotley where its called, can be used for mysql queries.

    PHP Code:
    function thetime($toset = 0) {
        $thetime = time();
        $toset = (int) $toset;
        $set = $toset + 0;
        return $thetime + ($set * 60 * 60);
    } 
    
    This one is to display time and format stamp in desired format with time hour setting also:

    PHP Code:
    function formatstamp($setformat = '', $stamp, $settime = 0) {
        return date($setformat, $stamp + ($settime * 60 * 60));
    } 
    
    Example with these two:
    PHP Code:
    echo formatstamp('d.m.Y H:i', thetime(), $sethours).'<br/>'; 
    
    Last edited by arnage; 17.03.12, 19:58.

    Leave a comment:


  • shad0w
    replied
    To "fix" Filezilla:

    Edit > Settings > Transfers > File types > Choose Binary

    Leave a comment:


  • i0nutzxp
    replied
    Code that cleans that ugly white lines caused by filezila and other:

    PHP Code:
    <?php
    $fileName = '';
    
    if ($fileName == NULL)
    {
        $fileName = isset($_GET['f']) ? $_GET['f'] : exit('<b>Usage: ?f=Filename.ext</b>');
    }
    $newLine = isset($_GET['nl']) ? TRUE : FALSE;
    
    $f = file($fileName);
    
    foreach ($f AS $k => $value)
    {
        $f[$k] = str_replace(PHP_EOL, '', $f[$k]);
        if ($newLine)
        {
            $f[$k] = str_replace('{', PHP_EOL.'{'.PHP_EOL, $f[$k]);
            $f[$k] = str_replace('}', PHP_EOL.'}'.PHP_EOL, $f[$k]);
        }
        if ($f[$k] == NULL) 
            unset($f[$k]);
    }
    file_put_contents(mt_rand(10000, 99999).'-'.$fileName, implode(PHP_EOL, $f));
    ?>
    Added after 7 minutes:

    My simple number separator function:

    PHP Code:
    <?php
    function format_number($numar, $separator = '.', $precizie = 3)
    {
        $numar = (string) $numar;
        $cifre = strlen($numar);
        
        $t = 1;
        $numar_formatat = '';
        for ($i = $cifre-1; $i>=0; $i--)
        {
            $numar_formatat = $numar[$i] . $numar_formatat;
            if ($t % $precizie == 0 && isset($numar[$i-1]))
            {
                $numar_formatat = $separator . $numar_formatat;
                $t = 1;
            }
            else
                $t++;
        }
        return $numar_formatat;
    }
    echo format_number(3000000); // Will output : 3.000.000
    echo format_number(3000000, ','); // Will output : 3,000,000
    // ARGS: format_number(int/string number, separator, precision);
    
    //PS: if you pass the number like an int make sure that it not contains more than 14 digits or by string with unlimited digits
    ?>
    Last edited by i0nutzxp; 04.10.11, 16:02.

    Leave a comment:


  • i0nutzxp
    replied
    If your script uses register globals on(and/or your server doesnt support it) and your to lazy use this function to help you.
    PHP Code:
    function RegisterGlobalsOff()
    {
       foreach ($_REQUEST AS $key=>$value)
       {
           if( ! isset(${$key}))
           {
               ${$key} = $value;
           }
       }
    } 
    

    Leave a comment:


  • arnage
    replied
    It can read and collect the content of xml file into a variable but as regards the elements of xml its needed to come up with some way to loop through it and call the specific elements.

    Leave a comment:


  • Aan Damar
    replied
    Can it used to open XML and parse it into php?

    Leave a comment:


  • arnage
    replied
    From php.net comments:

    PHP Code:
    function openFile($file, $mode, $input) {
        if ($mode == "READ") {
            if (file_exists($file)) {
                $handle = fopen($file, "r"); 
                $output = fread($handle, filesize($file));
                return $output; // output file text
            } else {
                return false; // failed.
            }
        } elseif ($mode == "WRITE") {
            $handle = fopen($file, "w");
            if (!fwrite($handle, $input)) {
                return false; // failed.
            } else {
                return true; //success.
            }
        } elseif ($mode == "READ/WRITE") {        
            if (file_exists($file) && isset($input)) {
                $handle = fopen($file, "r+");
                $read = fread($handle, filesize($file));
                $data = $read.$input;
                if (!fwrite($handle, $data)) {
                    return false; // failed.
                } else {
                    return true; // success.
                }
            } else {
                return false; // failed.
            }
        } else {
            return false; // failed.
        }
        fclose($handle); 
    } 
    
    Example calls are:

    PHP Code:
    openFile("files/text.txt", "WRITE", "Hello World!");
    echo openFile("files/text.txt", "READ"); // OUTPUT > Hello World!
    openFile("files/text.txt", "READ/WRITE", "!!");
    echo openFile("files/text.txt", "READ"); // OUTPUT > Hello World!!! 
    
    And i edited it to be more usable for me with:

    PHP Code:
    elseif ($mode == 'UPDATE') {
    $marker = "\n";
    if (is_writeable($file) && isset($input)) {
    $handle = @fopen($file, 'a');
    $data = $input.$marker;
    if (!fwrite($handle, $data)) {
    return false;
    } else {
    return true;
    }
    } else {
    return false;
    }
    } 
    
    Last edited by arnage; 19.04.11, 15:57.

    Leave a comment:

Working...
X