Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Monday, June 18, 2012

Install APC for PHP in CentOS

yum install pcre-devel gcc httpd-devel php-pear
pecl install apc
64bit: restorecon /usr/lib64/php/modules/apc.so
32bit: restorecon /usr/lib/php/modules/apc.so
echo "extension=apc.so" > /etc/php.d/apc.ini
service httpd restart

Solution: Fatal error: Cannot inherit previously-inherited or override constant LEVEL_TOP from interface Swift_Mime_Message in Symfony

There is a bug in APC. You need install the latest version of APC to solve the problem between Swiftmailer and APC: Install the Latest APC on Debian

Friday, June 8, 2012

Doctrine Schema: float(18,4) ?

Use decimal instead of float in this situation:

    sale_price_eur:
      type: decimal(18)
      scale: 4

Friday, March 9, 2012

Get Field Comments with Doctrine in Symfony

In Action:
$t = Doctrine::getTable('Product'); 
foreach($t->getColumns() as $key => $column) {
   $comments[$key] = $column['comment'];     
}

Wednesday, February 22, 2012

Remove Accents in String with ICONV

Don't forget: Iconv translit is locale sensitive. You must first set locale:
// remove hungarian accents
// magyar ékezetek eltávolítása
setlocale(LC_ALL, 'hu_HU.UTF8');
$text = iconv('UTF-8', 'ASCII//TRANSLIT', 'árvíztűrő tükörfúrógép');
echo $text = str_replace(array('\'', '"', ':'), array(), $text);

url_for Helper in Action in Symfony

$this->getContext()->getConfiguration()->loadHelpers(array('Url'));
// now you can use url_for()

Tuesday, February 21, 2012

Install Symfony Plugin: Warning: require_once(PEAR.php): failed to open stream

  1. If you try to install a plugin (ex. prestaPaypalPlugin) with symfony cli and get something like this...
    sakra:/var/www/sakra# ./symfony plugin:install prestaPaypalPlugin
    >> plugin    installing plugin "prestaPaypalPlugin"
    Warning: require_once(PEAR.php): failed to open stream: No such file or directory in mnt/vol1/vol1/www/sakra/lib/vendor/symfony/lib/plugin/sfPearEnvironment.class.php on line 15
    Fatal error: require_once(): Failed opening required 'PEAR.php' (include_path='.:/usr/share/php:/usr/share/pear') in /mnt/vol1/vol1/www/sakra/lib/vendor/symfony/lib/plugin/sfPearEnvironment.class.php on line 15
  2. Run: apt-get update
  3. Run: apt-get install php-pear
  4. Run again: ./symfony plugin:install prestaPaypalPlugin
  5. If you get an error like this...
    No release available for plugin "prestaPaypalPlugin" in state "stable"
  6. Run with -s parameter (to enable beta plugins): ./symfony plugin:install -s beta prestaPaypalPlugin

Wednesday, February 8, 2012

Format Date Based On User Culture in Action in Symfony

$user_culture = $this->getUser()->getCulture();
$formatdate = new sfDateFormat($user_culture);
echo $formatdate->format(strtotime('2012-02-08'), 'd'); // 'd' is a pattern

Thursday, January 19, 2012

Moodle: Upload Big Files

  1. Set post_max_size to (ex.) 1000M in php.ini.
  2. Set upload_max_filesize to (ex.) 1000M in php.ini.
  3. Check the upload_tmp_dir value on the phpinfo page. If it's empty, php use the default tmp folder. On linux, it is /tmp. Sometimes it's a mapped partition/device and it has a size. If the size is lower than 1000MB, the upload won't work. Change the size of the tmp dir!
  4. If there is a LimitRequestBody row in httpd.conf (apache) or in a virtual host file, change the value to 0, it means unlimited.

Wednesday, August 3, 2011

Generate an Excel file with sfPhpExcel in Symfony

  public function executeExcel(sfWebRequest $request)
  {
    // We're not going to be displaying any html, so no need to pass the data through the template
    $this->setLayout(false);

    // Initialize the Excel document
    $obj = new PHPExcel();
       
    // Set the active excel sheet
    $obj->setActiveSheetIndex(0);
    
    $obj->setActiveSheetIndex(0);
    $obj->getActiveSheet()->setCellValue('A1', 'Hello');
    $obj->getActiveSheet()->setCellValue('B2', 'world!');
    $obj->getActiveSheet()->setCellValue('C1', 'Hello');
    $obj->getActiveSheet()->setCellValue('D2', 'world!');
    
    // Output the excel data to a file
    $filePath = realpath('./excel') . DIRECTORY_SEPARATOR . 'excel.xlsx';
    $writer = PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
    $writer->save($filePath);
    
    // Redirect request to the outputed file
    $this->getResponse()->setHttpHeader('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    $this->redirect('/excel/excel.xlsx');
  }

Thursday, April 7, 2011

Convert RTF to TEXT with PHP and Linux

I always use UnRTF to get text from RTF files. The simplest way to convert the rtf file to html, then use the strip_tags method.
exec("unrtf test.rtf", $output);
echo strip_tags(implode('', $output));
However UnRTF is not fully compatible with UTF-8, it has problems with accents, ex. with the Hungarian accents, thus, I had to correct the Hungarian accents this way:
$from = array("Û", "û", "õ", "Õ");
$to = array("Ű", "ű", "ő", "Ő");

exec("unrtf test.rtf", $output);
echo strip_tags(str_replace($from, $to, html_entity_decode(implode('', $output), ENT_QUOTES, 'UTF-8')));

Convert ODT to TEXT with PHP

Shorter way (requires odt2txt installed and shell_exec enabled):
echo shell_exec("odt2txt --encoding=utf8 test.odt");
Longer way (requires PHP 5.2+ and ZIP extension enabled):
function odt2text($filename) {
    return readZippedXML($filename, "content.xml");
}

function readZippedXML($archiveFile, $dataFile) {
    // Create new ZIP archive
    $zip = new ZipArchive;

    // Open received archive file
    if (true === $zip->open($archiveFile)) {
        // If done, search for the data file in the archive
        if (($index = $zip->locateName($dataFile)) !== false) {
            // If found, read it to the string
            $data = $zip->getFromIndex($index);
            // Close archive file
            $zip->close();
            // Load XML from a string
            // Skip errors and warnings
            $xml = DOMDocument::loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
            // Return data without XML formatting tags
            return strip_tags($xml->saveXML());
        }
        $zip->close();
    }

    // In case of failure return empty string
    return "";
}

echo odt2text("test.odt");

Convert DOCX to TEXT with PHP

First, you have to use PHP 5.2+ and enable the ZIP (ZipArchive) extension for PHP.
function docx2text($filename) {
    return readZippedXML($filename, "word/document.xml");
}

function readZippedXML($archiveFile, $dataFile) {
    // Create new ZIP archive
    $zip = new ZipArchive;

    // Open received archive file
    if (true === $zip->open($archiveFile)) {
        // If done, search for the data file in the archive
        if (($index = $zip->locateName($dataFile)) !== false) {
            // If found, read it to the string
            $data = $zip->getFromIndex($index);
            // Close archive file
            $zip->close();
            // Load XML from a string
            // Skip errors and warnings
            $xml = DOMDocument::loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
            // Return data without XML formatting tags
            return strip_tags($xml->saveXML());
        }
        $zip->close();
    }

    // In case of failure return empty string
    return "";
}

echo docx2text("test.docx"); 

Wednesday, April 6, 2011

Convert DOC to TEXT with PHP and Linux

$file     = $directory.'/'.$filename;
$fileinfo = pathinfo($filename);
$content  = "";

// doc to text
if($fileinfo['extension'] == 'doc')
{
   $content = shell_exec("antiword -m UTF-8.txt -t $file");
}

Convert PDF to TEXT with PHP and Linux

To install pdftotext, use: apt-get install xpdf
$file     = $directory.'/'.$filename;
$fileinfo = pathinfo($filename);
$content  = "";

// pdt to text
if($fileinfo['extension'] == 'pdf')
{
   $outpath = preg_replace("/\.pdf$/", "", $file).".txt";
   system("pdftotext -enc UTF-8 ".escapeshellcmd($file), $ret);
   if($ret == 0) {
      $content = file_get_contents($outpath);
      unlink($outpath);
   }
}

Thursday, August 12, 2010

Old Nusoap Syntax can cause SOAP Error in PHP5

It is related to PHP5, which object names collides with the new soapclient() syntax (the PHP SOAP extension uses the same object name). If you change your syntax in the constructor from "new soapclient()" to "new nusoap_client()", the collision won't happen - and everything will be happy. Nusoap keeps the old syntax for legacy support ("new soapclient"). But PHP5 won't like it and give you a nice error:

Warning: SoapClient::SoapClient() expects parameter 2 to be array, boolean
given in /var/www/userdetails.php
on line 76

Fatal error: Uncaught SoapFault exception: [Client]
SoapClient::SoapClient() [soapclient.soapclient]: Invalid
parameters in
/var/www/userdetails.php:76 Stack
trace: #0
/var/www/userdetails.php(76):
SoapClient->SoapClient('https://195.228...', true) #1
/var/www/index.php(48): include('/var/www/i...') #2
{main} thrown in
/var/www/userdetails.php on line 76

Tuesday, August 3, 2010

Validating Integers without Regular Expression in PHP

ctype_digit checks if all of the characters in the provided string are numerical. Therefore, you must convert variables to string first, then you check them with ctype_digit.
$array = array(5, 5.2, "456", "564-223", "5.2", "673");
foreach($array as $item) {
   if(ctype_digit((string)$item)) {
      echo "int: ".$item."\n";
   } else {
      echo "not int: ".$item."\n";
   }
}