Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Tuesday, September 20, 2011

PHP mail()

No email was sent

1. check if sendmail server is running
[root]# service sendmail status

Configuring Linux Mail Servers
http://www.linuxhomenetworking.com/wiki/index.php/Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers#Starting_Sendmail


Thursday, February 17, 2011

PHP Memcache

PHP Memcache Manual
http://php.net/manual/en/book.memcache.php
Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.

Note: there are two *distinct* memcache PHP implementations
1) pecl-memcache
2) pecl-memcached

Using Memcache vs Memcached with PHP
http://stackoverflow.com/questions/1442411/using-memcache-vs-memcached-with-php

Memcache vs Memcached
http://stackoverflow.com/questions/1825256/memcache-vs-memcached


Comparison
http://code.google.com/p/memcached/wiki/PHPClientComparison

Install on Fedora
yum install php-pecl-memcache
fedora 100% |=========================| 2.1 kB 00:00
http://rpm.livna.org/fedora/7/i386/repodata/repomd.xml: [Errno 12] Timeout:
Trying other mirror.
http://livna.cat.pdx.edu/fedora/7/i386/repodata/repomd.xml: [Errno 14] HTTP Error 404: Not Found
Trying other mirror.


Check
ps -eaf | grep memcache

Check if memcache installed
phpinfo();

Check if memcache is running
telnet localhost 11211

Connection Refused


10 baby step to install Memcached Server and access it with PHP
http://www.webdeveloperjuice.com/2010/01/25/10-baby-steps-to-install-memcached-server-and-access-it-with-php/
Step1 Install libevent ,libmemcached and libmemcached devel (dependency)
yum install libevent
Setting up Install Process
Parsing package install arguments
Package libevent - 1.3b-1.fc7.i386 is already installed.
Nothing to do

yum install libmemcached libmemcached-devel
Setting up Install Process
Parsing package install arguments
No package libmemcached available.
No package libmemcached-devel available.
Nothing to do

Step2 Install Memcached Server
yum install memcached
Setting up Install Process
Parsing package install arguments
Resolving Dependencies
--> Running transaction check
---> Package memcached.i386 0:1.2.3-7.fc7 set to be updated
--> Finished Dependency Resolution

Dependencies Resolved

=============================================================================
Package Arch Version Repository Size
=============================================================================
Installing:
memcached i386 1.2.3-7.fc7 updates 50 k

Transaction Summary
=============================================================================
Install 1 Package(s)
Update 0 Package(s)
Remove 0 Package(s)

Total download size: 50 k
Is this ok [y/N]: y
Downloading Packages:
(1/1): memcached-1.2.3-7. 100% |=========================| 50 kB 00:00
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
Installing: memcached ######################### [1/1]

Installed: memcached.i386 0:1.2.3-7.fc7
Complete!

Step3 Start Memcached server
memcached -d -m 512 -l 127.0.0.1 -p 11211 -u nobody
(d = daemon, m = memory, u = user, l = IP to listen to, p = port)

Step4 Check your memcached server is running successfully
ps -eaf | grep memcached
nobody 1888 1 0 07:29 ? 00:00:00 memcached -d -m 512 -l 127.0.0.1 -p 11211 -u nobody
root 1897 1827 0 07:30 pts/1 00:00:00 grep memcached

Step 5: Connect Memcached server via telnet
telnet 127.0.0.1 11211
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.

Step 6: Check current status of Memcached Server on telnet prompt
stats
STAT pid 1888
STAT uptime 153
STAT time 1297945907
STAT version 1.2.3
STAT pointer_size 32
STAT rusage_user 0.054991
STAT rusage_system 0.027995
STAT curr_items 0
STAT total_items 0
STAT bytes 0
STAT curr_connections 1
STAT total_connections 2
STAT connection_structures 2
STAT cmd_get 0
STAT cmd_set 0
STAT get_hits 0
STAT get_misses 0
STAT evictions 0
STAT bytes_read 7
STAT bytes_written 0
STAT limit_maxbytes 536870912
STAT threads 4
END

Step 7: Exit telnet
quit
Connection closed by foreign host.

Step 8: Install PHP client to access Memcached Server
pecl install memcache
It will make “memcache.so”, you have to just put it on your /etc/php.ini file.

WARNING: channel "pecl.php.net" has updated its protocols, use "channel-update pecl.php.net" to update
Skipping package "pecl/memcache", already installed as version 3.0.2
No valid packages found
install failed

Step 9: Restart your apache server
service httpd restart

Step 10: Open your favorite editor to type below code and execute it, it will cache your data into Memcached server and access it back for you

$memcache = new Memcache;
$memcache->connect('127.0.0.1', 11211) or die ("Could not connect"); //connect to memcached server
$mydata = "i want to cache this line"; //your cacheble data
$memcache->set('key', $mydata, false, 100); //add it to memcached server
$get_result = $memcache->get('key'); //retrieve your data
var_dump($get_result); //show it

Wednesday, May 19, 2010

Symfony Tips

1. Add Timer (symfony 1.0)

/**** init timer *****/
$timer = sfTimerManager::getTimer('myTimer');
/**********/


/**** display timer *****/
$timer->addTime();
$elapsedTime = $timer->getElapsedTime();
echo $elapsedTime;
die();
/**********/


2. Unit Test (symfony 1.4)
http://www.symfony-project.org/jobeet/1_4/Doctrine/en/08
Create test.php file under ProjectName/test/unit/test

// test/unit/JobeetTest.php
require_once dirname(__FILE__).'/../bootstrap/unit.php';

$t = new lime_test(1);
$t->pass('This test always passes.');


To launch the test
$ php test/unit/test.php

Sample

require_once dirname(__FILE__).'/../bootstrap/unit.php';
$t = new lime_test(6); // display 1..6

$t->comment('::slugify()'); // display #::slugify()
$t->is(Jobeet::slugify('Sensio'), 'sensio', '::slugify() converts all characters to lower case'); // display ok 1 - ::slugify() converts all ...


3. User Flash (symfony 1.4)
http://www.symfony-project.org/jobeet/1_4/Doctrine/en/13
A flash is an ephemeral message stored in the user session that will be automatically deleted after the very next request. It is very useful when you need to display a message to the user after a redirect.

setFlash(): The first argument is the identifier of the flash and the second one is the message to display. You can define whatever flashes you want, but notice and error are two of the more common ones.
// apps/frontend/modules/job/actions/actions.class.php
public function executeExtend(sfWebRequest $request)
{
    $request->checkCSRFProtection();

    $job = $this->getRoute()->getObject();
    $this->forward404Unless($job->extend());

    $this->getUser()->setFlash('notice', sprintf('Your job validity has been extended until %s.', $job->getDateTimeObject('expires_at')->format('m/d/Y')));

    $this->redirect($this->generateUrl('job_show_user', $job));
}

Include the flash message in the templates
// apps/frontend/templates/layout.php
<?php if ($sf_user->hasFlash('notice')): ?>
  <div class="flash_notice"><?php echo $sf_user->getFlash('notice') ?></div>
<?php endif ?>
 
<?php if ($sf_user->hasFlash('error')): ?>
  <div class="flash_error"><?php echo $sf_user->getFlash('error') ?></div>
<?php endif ?>


4. User Attribute (symfony 1.4)
http://www.symfony-project.org/jobeet/1_4/Doctrine/en/13
getAttribute(), setAttribute()

// apps/frontend/modules/job/actions/actions.class.php
class jobActions extends sfActions
{
    public function executeShow(sfWebRequest $request)
    {
    $this->job = $this->getRoute()->getObject();

    // fetch jobs already stored in the job history
    $jobs = $this->getUser()->getAttribute('job_history', array());

    // add the current job at the beginning of the array
    array_unshift($jobs, $this->job->getId());

    // store the new job history back into the session
    $this->getUser()->setAttribute('job_history', $jobs);
    }
}

myUser class
The myUser class overrides the default symfony base sfUser class with application specific behaviors

// apps/frontend/modules/job/actions/actions.class.php
class jobActions extends sfActions
{
    public function executeShow(sfWebRequest $request)
    {
    $this->job = $this->getRoute()->getObject();

    $this->getUser()->addJobToHistory($this->job);
    }
}
// apps/frontend/lib/myUser.class.php
class myUser extends sfBasicSecurityUser
{
    public function addJobToHistory(JobeetJob $job)
    {
    $ids = $this->getAttribute('job_history', array());

    if (!in_array($job->getId(), $ids))
    {
        array_unshift($ids, $job->getId());
        $this->setAttribute('job_history', array_slice($ids, 0, 3));
    }
    }
}

remove attribute
User's attributes are managed by an object of class sfParameterHolder. The getAttribute() and setAttribute() methods are proxy methods for getParameterHolder()->get() and getParameterHolder()->set().

// apps/frontend/lib/myUser.class.php
class myUser extends sfBasicSecurityUser
{
    public function resetJobHistory()
    {
        $this->getAttributeHolder()->remove('job_history');
    }
}



5. i18n and l10n (symfony 1.4)
http://www.symfony-project.org/jobeet/1_4/Doctrine/en/19
User Culture
The language French is ‘fr’, English is ‘en’; the country Canada is ‘CA’, United States is ‘US’; the culture for a user speaking French from Canada is ‘fr_CA’
setCulture()and getCulture()

// in an action
$this->getUser()->setCulture('fr_BE');
echo $this->getUser()->getCulture();

The preferred user culture can be configured in the settings.yml configuration file

#apps/frontend/config/settings.yml
all:
    .settings:
       default_culture: en_CA

Internationalization
set i18n setting to true in settings.yml

# apps/frontend/config/settings.yml
all:
   .settings:
       charset: utf-8
       i18n: true

The I18N helper group is not loaded by default, you need to either manually add itin each template with use_helper(‘I18N’) or load it globally by adding to the standard_helpers setting

# apps/frontend/config/settings.yml
all:
   .settings:
      standard_helpers: [Partial, Cache, I18N]

Sample template of how to use the __() helper

    // apps/frontend/templates/layout.php

      <a href=""><?php echo __('About Jobeet') ?></a>

      <?php echo link_to(__('Full feed'), 'job', array('sf_format' => 'atom')) ?>

    Create catalogue using i18n:extract

    $ php symfony i18n:extract frontend fr --auto-save

    Each translation is managed by a trans-unit tag which has a unique id attribute. A lot of tools exist to ease the translation process. (check out Open Language Tools https://open-language-tools.dev.java.net/)

    <!-- apps/frontend/i18n/fr/messages.xml -->

    <xliff version="1.0">
      <file source-language="EN" target-language="fr" datatype="plaintext"
          original="messages" date="2008-12-14T12:11:22Z"
          product-name="messages">
        <header/>
        <body>
          <trans-unit id="1">
            <source>About Jobeet</source>
            <target>A propos de Jobeet</target>
          </trans-unit>
          <trans-unit id="2">
            <source>Feed</source>
            <target>Fil RSS</target>
          </trans-unit>
        </body>
      </file>
    </xliff>

    How to use format_date
    sfDateFormat::getPattern()
    http://fellipeeduardo.com/blog/symfony-helper-format_date-how-to-use/en/

    6. autoload.yml (symfony 1.4)
    http://www.symfony-project.org/reference/1_4/en/14-Other-Configuration-Files
    The autoload.yml configuration determines which directories need to be autoloaded by symfony

    7. Authentication (symfony 1.4)
    entire application require the user to be authenticated

    # apps/backend/config/security.yml
    default:
       is_secure: true

    when an un-authenticated user tries to access a secured action, symfony forwards the request to the login action

    # apps/backend/config/setting.yml
    all:

      .actions:
         login_module: default
         login_action: login


    By default, the myUser class extends sfBasicSecurityUser, and not sfUser. sfBasicSecurityUser provides additional methods to manage user authentication and authorization.

    To manage user authentication, use the isAuthenticated() and setAuthenticated() methods:

    if (!$this->getUser()->isAuthenticated())
    {
        $this->getUser()->setAuthenticated(true);
    }


    8. Basic File Structure (1.2)
    http://www.symfony-project.org/book/1_2/19-Mastering-Symfony-s-Configuration-Files

    sf_root_dir # myproject/
    sf_apps_dir # apps/
    sf_app_dir # frontend/
    sf_app_config_dir # config/
    sf_app_i18n_dir # i18n/
    sf_app_lib_dir # lib/
    sf_app_module_dir # modules/
    sf_app_template_dir # templates/
    sf_cache_dir # cache/
    sf_app_base_cache_dir # frontend/
    sf_app_cache_dir # prod/
    sf_template_cache_dir # templates/
    sf_i18n_cache_dir # i18n/
    sf_config_cache_dir # config/
    sf_test_cache_dir # test/
    sf_module_cache_dir # modules/
    sf_config_dir # config/
    sf_data_dir # data/
    sf_doc_dir # doc/
    sf_lib_dir # lib/
    sf_log_dir # log/
    sf_test_dir # test/
    sf_plugins_dir # plugins/
    sf_web_dir # web/
    sf_upload_dir # uploads/


    9. Use Helper in Action
    http://snippets.symfony-project.org/snippet/69
    In PrjectConfiguration file

    # ProjectName/config/ProjectConfiguration.class.php
    include_once('/opt/symfony/symfony14/lib/helper/DateHelper.php');

    In Action
    format_date(time(), 'D', 'fr');

    Format
    http://trac.symfony-project.org/wiki/formatDateHowTo

    Wednesday, January 20, 2010

    PHP Tips

    PHP String Functions
    http://www.w3schools.com/PHP/php_ref_string.asp

    1.  Contain String

    int strpos ( string $haystack, mixed $needle [, int $offset = 0 ])  - Find position of first occurrence of a string

    int strstr ( string $haystack, mixed $needle [, bool $before_needle = false ]) Find first occurrence of a string

    2. Array
    array_merge( array1, array2 ...)  - merge array
    array_intersect(array1,array2,array3...) - compares array values, and returns the matches
    array_diff(array1,array2,array3...)  - compares array values, and returns the difference

    array_unique(array) - remove duplicate value
    in_array(search,array,type) - searches an array for a specific value (true or false)

    Remove an item from array base on the value

    foreach($myArray as $key => $item) {
       if($item->getValue() == $remove_value) {
          unset($myArray[$key]);
       }
    }


    explode — Split a string by string
    implode — Join array elements with a string

    array explode ( string $delimiter , string $string [, int $limit ] )
    string implode ( string $glue , array $pieces )


    3. Input & Output
    $user_input = $this->getRequestParameter('query');
    $user_input = htmlentities($user_input, ENT_QUOTES, 'UTF-8'); 

    $output = html_entity_decode($value, ENT_QUOTES, 'UTF-8');

    Test

    Iñtërnâtiônàlizætiøn
    ®™©&'/"\"¤¶>%?


    $name = html_entity_decode($name, ENT_QUOTES, 'UTF-8');
    $name = truncate_text($name, 40, '..');
    $name= htmlentities($name, ENT_QUOTES, 'UTF-8');

    4.php.ini

    phpinfo();

    such as /etc/php.ini

    Friday, January 15, 2010

    Web Development Special Characters


    1. Suvivial Guide to i18n
    Testing:
    Iñtërnâtiônàlizætiøn


    2. PHP UTF-8 Cheatsheet
    Encodes HTML safely for UTF-8 
    
    htmlentities($var, ENT_QUOTES, 'UTF-8')
    

    3. PHP: htmlentities - Manual
    http://php.net/manual/en/function.htmlentities.php
     
    4. The Absolute Minimum Every Software Developer Absolutely, 
    Positively Must Know About Unicode and Character Sets 
    (No Excuses!) - Joel on Software
    http://www.joelonsoftware.com/articles/Unicode.html