Category: PHP

  • How to install PHP from Source on Ubuntu

    How to install PHP from Source on Ubuntu

    Compiling PHP from source code can be essential when you require a specific PHP version that isn’t available through your Ubuntu distribution or a Personal Package Archive (PPA). This approach is particularly useful if you need to enable custom modules, such as pcntl, which is disabled by default on Ubuntu. By compiling PHP yourself, you gain the flexibility to customize your PHP environment to meet your exact requirements.

    Install Requirements

    Installing PHP from source code requires many packages and libraries installed. You can install it with the command

    apt-get install -y build-essential autoconf automake pkgconf re2c libbz2-dev libcurl4-openssl-dev libxml2-dev libpng-dev libjpeg-dev libssl-dev libzip-dev libmcrypt-dev libreadline-dev libonig-dev libsodium-dev bison libsqlite3-dev libfreetype-dev libsystemd-dev libwebp-dev libxslt1-dev libkrb5-dev libldap2-dev

    Download and extract PHP source code

    cd /usr/local/src/
    wget https://www.php.net/distributions/php-8.3.8.tar.gz
    tar -xzvf php-8.3.8.tar.gz
    cd php-8.3.8

    Configure PHP

    This step allows you to enable or disable PHP modules.

    ./configure \
    	--with-pic \
    	--enable-embed \
    	--prefix=/usr/serverok/php \
    	--with-config-file-scan-dir=/usr/serverok/php/lib/php.conf.d \
    	--enable-pcntl \
    	--enable-fpm \
    	--with-fpm-systemd \
    	--with-curl \
    	--enable-gd \
    	--with-gettext \
    	--with-jpeg \
    	--with-freetype \
    	--with-kerberos \
    	--with-openssl \
    	--with-mhash \
    	--with-mysql-sock=/var/lib/mysql/mysql.sock \
    	--with-mysqli=mysqlnd \
    	--with-pdo-mysql=mysqlnd \
    	--with-pear \
    	--with-sodium \
    	--with-webp \
    	--with-xsl \
    	--with-zlib \
    	--with-zip \
    	--enable-bcmath \
    	--enable-calendar \
    	--enable-exif \
    	--enable-ftp \
    	--enable-sockets \
    	--enable-soap \
    	--enable-mbstring \
    	--enable-intl \
    	--with-ldap

    Compile and Install PHP

    make
    make install
    cp ./php.ini-production /usr/serverok/php/lib/php.ini
    cp /usr/serverok/php/etc/php-fpm.conf.default  /usr/serverok/php/etc/php-fpm.conf

    Create php-fpm pool file

    Create file

    vi /usr/serverok/php/etc/php-fpm.d/www.conf

    Add following content

    [www]
    user = www-data
    group = www-data
    listen = /run/php/php-fpm.sock
    listen.owner = www-data
    listen.group = www-data
    pm = dynamic
    pm.max_children = 5
    pm.start_servers = 2
    pm.min_spare_servers = 1
    pm.max_spare_servers = 3
    catch_workers_output = yes
    php_flag[display_errors] = on
    php_admin_value[error_log] = /var/log/fpm-php.log
    php_admin_flag[log_errors] = on

    Start php-fpm on boot

    Create a service file

    vi /etc/systemd/system/php-fpm.service

    Add following content

    [Unit]
    Description=PHP FastCGI Process Manager (ServerOK)
    After=network.target
    
    [Service]
    Type=forking
    PIDFile=/run/php/php-fpm.pid
    ExecStart=/usr/serverok/php/sbin/php-fpm --daemonize --pid /run/php/php-fpm.pid
    ExecReload=/bin/kill -USR2 $MAINPID
    ExecStop=/bin/kill -QUIT $MAINPID
    PrivateTmp=true
    
    [Install]
    WantedBy=multi-user.target

    Start php-fpm service

    systemctl daemon-reload
    systemctl enable php-fpm
    systemctl start php-fpm
    systemctl status php-fpm

    Install PHP modules from PECL

    To install PHP modules from PECL, run

    apt install -y libmagick++-dev
    /usr/serverok/php/bin/pecl install APCu
    /usr/serverok/php/bin/pecl install redis
    /usr/serverok/php/bin/pecl install imagick

    To enable the PHP modules, edit

    vi /usr/serverok/php/lib/php.ini

    add

    extension=imagick.so
    extension=apcu.so
    extension=redis.so

    Restart php-fpm service

    systemctl resart php-fpm

    Enable php-fpm for your website

    To enable php-fpm for Apache, add the following code in the Apache VirtualHost entry.

    <FilesMatch \.php$>
    	SetHandler proxy:unix:/run/php/php-fpm.sock|fcgi://127.0.0.1
    </FilesMatch>

    For nginx, use socket

    /run/php/php-fpm.sock

    Back to PHP

  • How to get Contents of a Webpage using PHP curl

    How to get Contents of a Webpage using PHP curl

    PHP cURL module allows you to connect to remote websites and API endpoints to exchange data. To see if you have php-curl enabled, you can check phpinfo() page or run the command “php -m’ and look for curl.

    boby@sok-01:~$ php -m | grep curl
    curl
    boby@sok-01:~$ 
    

    If php-curl module is not installed, you can install it on Ubuntu/Debian with the command

    apt-get install php-curl
    

    To access the content of a remote web server or API endpoint, you can use the following PHP code.

    
    

    To make script work with invalid or self signed SSL, add following

    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    

    If you want to make a POST request, you can use the following code

     'Yujin Boby',
        'email' => '[email protected]'
    );
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 11.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3');
    $response = curl_exec($ch);
    curl_close($ch);
    

    Back to PHP

  • Laravel supported ciphers are AES-128-CBC and AES-256-CBC

    Laravel supported ciphers are AES-128-CBC and AES-256-CBC

    On a Laravel application, I get the following error message

    The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths.
    
    Laravel error

    To fix the error, run the command

    php artisan key:generate

    This will generate a new key and add to the .env file.

    Back to Laravel

  • How To Install ionCube on Ubuntu 20.04

    How To Install ionCube on Ubuntu 20.04

    ionCube is PHP extension that is used to load ionCube encoded PHP files. ionCube is used to protect commercial PHP scripts by encoding it, so no one can read the actual PHP code.

    First, download ioncube loader from

    https://www.ioncube.com/loaders.php

    cd /usr/local/src
    wget https://downloads.ioncube.com/loader_downloads/ioncube_loaders_lin_x86-64.tar.gz
    tar xvf ioncube_loaders_lin_x86-64.tar.gz
    cd ioncube/
    

    Find extension directory and copy .so file to PHP extension directory. To find PHP extension directory run

    php -i | grep  extension_dir
    

    On my installation, i have PHP extension_dir set to /usr/lib/php/20190902. If it’s different for you, change the path in the following command.

    For PHP 7.4, run

    cp /usr/local/src/ioncube/ioncube_loader_lin_7.4.so /usr/lib/php/20190902
    

    Enable ioncube

    echo "zend_extension=ioncube_loader_lin_7.4.so" > /etc/php/7.4/mods-available/ioncube.ini
    ln -s /etc/php/7.4/mods-available/ioncube.ini /etc/php/7.4/cli/conf.d/01-ioncube.ini
    

    for Apache, run

    ln -s /etc/php/7.4/mods-available/ioncube.ini /etc/php/7.4/apache2/conf.d/01-ioncube.ini
    systemctl restart apache2
    

    for php-fpm, run

    ln -s /etc/php/7.4/mods-available/ioncube.ini /etc/php/7.4/fpm/conf.d/01-ioncube.ini
    systemctl restart php7.4-fpm
    
  • How to install PHP PECL Extension

    How to install PHP PECL Extension

    PECL is a repository for PHP extensions. To install PHP extensions from PCEL, you can use the command

    pcel install EXTENSTION_NAME_HERE
    

    To install a specific version, you can specify version after extension name as follows.

    pecl install pecl_http-3.2.3
    

    Once an extension is installed, you need to edit PHP configuration and add a line to load the PHP module.

    extension=EXTENSTION_NAME_HERE.so
    

    Back to PECL

  • Monitoring APCu with APCu Panel

    Monitoring APCu with APCu Panel

    apcu-panel provide GUI to monitor APCu cache. To install apcu-panel on CentOS, run

    yum install apcu-panel
    

    The package provides following files

    [root@localhost ~]# rpm -q --filesbypkg apcu-panel
    apcu-panel                /etc/apcu-panel
    apcu-panel                /etc/apcu-panel/conf.php
    apcu-panel                /etc/httpd/conf.d/apcu-panel.conf
    apcu-panel                /usr/share/apcu-panel
    apcu-panel                /usr/share/apcu-panel/index.php
    [root@localhost ~]# 
    

    To enable GUI, edit file

    vi /etc/httpd/conf.d/apcu-panel.conf
    

    Modify it as follows

    # APC Control Panel
    Alias /apcu-panel /usr/share/apcu-panel
    
    
       
         Require all granted
       
    
    

    Restart Apache

    systemctl restart httpd
    

    Now you should be able to access APCu panel at

    http://your-server-ip/apcu-panel/
    
  • NextCloud APCu not available for local cache

    NextCloud APCu not available for local cache

    When trying to upgrade nextcloud, I get the following error

    www-data@mail:/www/nextcloud$ php7.3 occ upgrade
    An unhandled exception has been thrown:
    OC\HintException: [0]: Memcache \OC\Memcache\APCu not available for local cache (Is the matching PHP module installed and enabled?)
    www-data@mail:/www/nextcloud$ 
    

    To fix this, you need to install APC cache.

    apt install php7.3-apcu
    

    For CLI, you need to edit PHP configuration file

    vi /etc/php/7.2/cli/php.ini
    

    at the end of the file, add

    apc.enable_cli = 1
    

    You can also enable apc for the current command with option

    php7.3 -d apc.enable_cli=1 occ upgrade
    
  • How to clear Laravel cache

    To clear the Laravel cache, run the command

    php artisan cache:clear

    You can also delete compiled files from

    rm -rf bootstrap/cache/*

    Back to Laravel

  • PHP Script to verify private key matches SSL certificate?

    OpenSSL command can be used to verify if an SSL certificate matches a private key file. You need to find the checksum for the SSL certificate and Private key, if both checksums are the same, then the key matches.

    To make this process easier, I created a PHP script to verify if the SSL certificate matches the private key provided.

    Create a file

    mkdir ~/bin/
    vi ~/bin/ssl-verify
    

    Add following content

    #!/usr/bin/php
    
    

    Make it executable

    chmod 755 ~/bin/ssl-verify
    

    To verify an SSL and key file, go to the folder where the SSL certificate and key file are present, then run the command

    ssl-verify
    
  • Codeigniter 3 session not working

    On a web application, session not working. I verified PHP session is working with script

    https://gist.github.com/serverok/8c504205ae0357e0c6488eab880a77bf

    When refreshing the script, the number start increasing, that confirms PHP session works fine on the server.

    As for Codeigniter, we need to check the session settings in file application/config/config.php

    $config['sess_driver'] = 'files';
    $config['sess_cookie_name'] = 'ci_session';
    $config['sess_expiration'] = 7200;
    $config['sess_save_path'] = FCPATH.'ci_sessions';
    $config['sess_match_ip'] = FALSE;
    $config['sess_time_to_update'] = 300;
    $config['sess_regenerate_destroy'] = FALSE;
    

    That looks good. Session will be saved in folder

    FCPATH.'ci_sessions';
    

    FCPATH will be replaced with web application root folder where index.php is present. I verified ci_session folder exists and changed its permisison to 777, but that did not fixed the session problem.

    To verify session is working, i added 2 function to controller

    public function set-session()
    {
        $newdata = array(
            'username'  => 'johndoe',
            'email'     => '[email protected]',
            'logged_in' => TRUE
        );
        $this->session->set_userdata($newdata);
        die("test");
    }
    
    public function read-session()
    {
        $this->load->library('session');
        $name = $this->session->userdata();
        echo "
    ";
        var_dump($name);
        var_dump($_SESSION);
        exit;
    }
    

    I can call these functions to verify is session is setting properly with url like yourdomain/controller-name/function-name

    The problem was due to PHP 7. To fix it, edit file

    system/libraries/Session/Session.php
    

    Find

    ini_set('session.name', $params['cookie_name']);
    

    Replace with

    ini_set('session.id', $params['cookie_name']);
    

    You can find more about Codeigniter session at https://codeigniter.com/userguide3/libraries/sessions.html

  • Redirect a site to www using PHP

    To redirect a site to URL with www using PHP, you can use the following PHP code

    <?php
    
    $domainName = $_SERVER['HTTP_HOST'];
    
    if (strpos($domainName, 'www') === false) {
        header("HTTP/1.1 301 Moved Permanently");
        $urlNew = 'https://www.' . $domainName .  $_SERVER['REQUEST_URI'];
        Header("Location: $newUrl");
        exit;
    }

    Add this code in your index.php file or another file included by index.php

    See Redirect

  • PHP script to test IMAP

    Here is a PHP Script to login to IMAP server.

    Mailboxes\n";
    
    $folders = imap_listmailbox($mbox, "{imap.example.org:143}", "*");
    
    if ($folders == false) {
        echo "Call failed
    \n"; } else { foreach ($folders as $val) { echo $val . "
    \n"; } } echo "

    Headers in INBOX

    \n"; $headers = imap_headers($mbox); if ($headers == false) { echo "Call failed
    \n"; } else { foreach ($headers as $val) { echo $val . "
    \n"; } } imap_close($mbox);

    See PHP