PHP – Remove Duplicate Values From Multi-dimension Array


<?php
function super_unique($array)
{
  $result = array_map("unserialize", array_unique(array_map("serialize", $array)));

  foreach ($result as $key => $value)
  {
    if ( is_array($value) )
    {
      $result[$key] = super_unique($value);
    }
  }

  return $result;
}
?>


source:
http://stackoverflow.com/questions/3598298/php-remove-duplicate-values-from-multidimensional-array

Code Igniter Error: Disallowed Key Characters


1. Search for function _clean_input_keys on /system/core/Input.php

2. Modify this line

exit(‘Disallowed Key Characters.’);

to

exit(‘Disallowed Key Characters.’ .  $str);

3. Refresh page to see the characters which generate the error

4. If you need to add those characters into the exception list, just add to this line

if ( ! preg_match(“/^[a-z0-9:_\/-]+$|/i”, $str))

I add | (pipe) character on the example above

Note: In most cases you can resolve the problem just by clearing the cookies

PHP – Unzip Large File


    $filename = 'c:\kosmas.zip';
        $archive = zip_open($filename);
        while($entry = zip_read($archive)){
            $size = zip_entry_filesize($entry);
            $name = zip_entry_name($entry);
            $unzipped = fopen('c:/unzip/'.$name,'wb');
            while($size > 0){
                $chunkSize = ($size > 10240) ? 10240 : $size;
                $size -= $chunkSize;
                $chunk = zip_entry_read($entry, $chunkSize);
                if($chunk !== false) fwrite($unzipped, $chunk);
            }

            fclose($unzipped);
        }


source:
http://stackoverflow.com/questions/3263129/unzipping-larger-files-with-php

Working with PHP, MySQL and UTF-8


Heres a list of actions you should do in order to get PHP + MySQL working with UTF-8:

1. Database:

CREATE DATABASE db_name
CHARACTER SET utf8
DEFAULT CHARACTER SET utf8
COLLATE utf8_general_ci
DEFAULT COLLATE utf8_general_ci
;

or if the database was already created:

ALTER DATABASE db_name
CHARACTER SET utf8
DEFAULT CHARACTER SET utf8
COLLATE utf8_general_ci
DEFAULT COLLATE utf8_general_ci
;

CREATE TABLE table_name(

)
DEFAULT CHARACTER SET utf8
COLLATE utf8_general_ci;

Or if the tables are already created:

ALTER TABLE tbl_name
DEFAULT CHARACTER SET utf8
COLLATE utf8_general_ci;

2. Enable this line in php.ini:

extension=php_mbstring.dll

and configure the following in the same file:

mbstring.language = Neutral
mbstring.internal_encoding = UTF-8
mbstring.encoding_translation = On
mbstring.http_input = auto
mbstring.http_output = UTF-8
mbstring.detect_order = auto
mbstring.substitute_character = none
default_charset = UTF-8

3. Use the following php functions instead:

mail() -> mb_send_mail()
strlen() -> mb_strlen()
strpos() -> mb_strpos()
strrpos() -> mb_strrpos()
substr() -> mb_substr()
strtolower() -> mb_strtolower()
strtoupper() -> mb_strtoupper()
substr_count() -> mb_substr_count()
ereg() -> mb_ereg()
eregi() -> mb_eregi()
ereg_replace() -> mb_ereg_replace()
eregi_replace() -> mb_eregi_replace()
split() -> mb_split()
htmlentities($var) -> htmlentities($var, ENT_QUOTES, ‘UTF-8’)

4. Use headers and meta tags like:

header(‘Content-type: text/html; charset=UTF-8’) ;

<meta http-equiv=”Content-type” value=”text/html; charset=UTF-8″ />

5. add charset to form

<form accept-charset=”utf-8″ …>

6. Before any insert / update in the database you should perform the following:

mysql_query(“SET NAMES ‘utf8′”);

or use this before making DB connection

mysql_set_charset(‘utf8’);

source:

http://akrabat.com/php/utf8-php-and-mysql/

http://tympanus.net/codrops/2009/08/31/solving-php-mysql-utf-8-issues/

PHP – Remove Allowable Whitespace


$newSource = '';
foreach (token_get_all($source) as $i => $token) {
    if (!is_array($token)) {
        $newSource .= $token;
    }

    if ($token[0] == T_WHITESPACE) {
        if (   isset($tokens[$i - 1])      && isset($tokens[$i + 1])
            && is_array($tokens[$i - 1])   && is_array($tokens[$i + 1])
            && isLabel($tokens[$i - 1][1]) && isLabel($tokens[$i + 1][1])
        ) {
            $newSource .= ' ';
        }
    } else {
        $newSource .= $token[1];
    }
}

function isLabel($str) {
    return preg_match('~^[a-zA-Z0-9_\x7f-\xff]+$~', $str);
}


source:
http://stackoverflow.com/questions/4908588/removing-allowable-whitespace-in-php-using-parser-tokens

PHP – Remove Comments from PHP File


$fileStr = file_get_contents('path/to/file');
$newStr  = '';

$commentTokens = array(T_COMMENT);

if (defined('T_DOC_COMMENT'))
    $commentTokens[] = T_DOC_COMMENT; // PHP 5
if (defined('T_ML_COMMENT'))
    $commentTokens[] = T_ML_COMMENT;  // PHP 4

$tokens = token_get_all($fileStr);

foreach ($tokens as $token) {    
    if (is_array($token)) {
        if (in_array($token[0], $commentTokens))
            continue;

        $token = $token[1];
    }

    $newStr .= $token;
}

echo $newStr;


source:
http://stackoverflow.com/questions/503871/best-way-to-automatically-remove-comments-from-php-code

PHP, Crystal Report, MS SQL Server


PHP 5.1.6, MSSQL2005 and Crystal Report Server XI RL2

<?php
//- Variables – for your RPT and PDF
echo “Print Report Test”;
$my_report = “D:\\Folder1\\SubFolder1\\Report.rpt”; //
rpt source file
$my_pdf = “D:\\Folder1\\SubFolder1\\Report.pdf”; // RPT export to pdf file
//-Create new COM object-depends on your Crystal Report version
$ObjectFactory= new COM(“CrystalReports115.ObjectFactory.1”) or die (“Error on load”); // call COM port
$crapp = $ObjectFactory-> CreateObject(“CrystalDesignRunTime.Application”); // create an instance for Crystal
$creport = $crapp->OpenReport($my_report, 1); // call rpt report

// to refresh data before

//- Set database logon info – must have
$creport->Database->Tables(1)->SetLogOnInfo(“servername”, “DBname”, “user”, “password”);

//- field prompt or else report will hang – to get through
$creport->EnableParameterPrompting = 0;

//- DiscardSavedData – to refresh then read records
$creport->DiscardSavedData;
$creport->ReadRecords();
//export to PDF process
$creport->ExportOptions->DiskFileName=$my_pdf; //export to pdf
$creport->ExportOptions->PDFExportAllPages=true;
$creport->ExportOptions->DestinationType=1; // export to file
$creport->ExportOptions->FormatType=31; // PDF type
$creport->Export(false);

//—— Release the variables ——
$creport = null;
$crapp = null;
$ObjectFactory = null;

//—— Embed the report in the webpage ——
print “
?>

 

source:

http://php.net/manual/en/class.com.php

 

PHP – Template Engine in One Line of Code


templateEngine.php:

<?php

print preg_replace(“/\{([^\{]{1,100}?)\}/e”,”$$1″,file_get_contents(“template.tpl”));

?>

template.tpl:

<html>
<head>
<title>{title}</title>
</head>
<body>
<h1>{header}</h1>
{text}
</body>
</html>

variables:

$title=”Example page”;
$header=”My Examples”;
$text=”See the placeholders replaced?”;

 

REGEX Explanation:

"/\{([^\{]{1,100}?)\}/e","$$1"
I’m delimiting the regular expression with / / and using the modifier ‘e’ which causes the second argument to be evaluated by PHP.

The pattern looks for an opening curly-brace ( \{ ) – the end of the pattern is a closing curly-brace ( \} ).

In between the two braces I look for any character which isn’t an opening curly-brace [^\{], avoiding mistaken nesting of tags.

I match between 1 and 100 of these non-{ characters by writing {1,100} and then I make the match non-greedy (try to find the shortest strings between { and }, not the longest) by adding a?. (? after *, + or {a,b} expressions changes them to non-greedy – in other situations? means 0 or 1 of the preceding).

The full string of non-{ characters is matched and stored as string $1 by surrounding that part of the pattern with brackets ().

Finally, the second argument of the preg_replace is “$$1”, using variable variables. If the pattern encounters “{title}” then the matched string $1 is “title” and so $$1 is $title. 

 

source:

http://www.webmasterworld.com/php/3444822.htm