PHP Solution For Persistent Timeout Error

PHP Solution For Persistent Timeout Error

Perhaps you came across a message such as “Maximum execution time of 180 seconds exceeded” and went googling for a solution. The solution would probably be one of the following

By editing .htaccess

php_value max_execution_time -1

By editing php.ini 

max_execution_time=-1

By editing your PHP code

set_time_limit(-1); 
// OR
ini_set ('max_execution_time', -1);

But even after trying all these.. you are still getting the same error.

Here’s some possible reasons and solutions why.

    1. Your script is getting timed-out by Apache/LiteSpeed/Other Similar Web Server TechnologyIn your httpd.conf (in server config or vhost config), edit the TimeOut variable. The default should be 300.
      TimeOut 600
      
    2. Your using PHP-FastCGI or PHP-FPMThe error you are seeing is from apache’s fastcgi proxy who killed connection to php-fpm pool because your script did not outputted anything for 30 seconds.You can change idle-timeout in your apache config to extend it (cannot be 0):
      FastCgiExternalServer /usr/lib/cgi-bin/php7-fcgi -socket /run/php/php7.0-fpm.sock -idle-timeout 1800 -pass-header Authorization
    3. Apache or PHP isn’t resetting the execution time counter for unknown reasons
      Finally, if you still are not able to get it to work, simply try putting the code

      set_time_limit(-1)

      around different parts of your script/code. This is because each time you call set_time_limit it resets the timer / counter for the script. An example as shown below – I faced a problem with hashing large files and had to consistently make calls to set_time_limit

      $bytesToRead = 1024;
      $fp = fopen($filepath, "r");
      $ctx = hash_init('sha256');
      while (!feof($fp)) {
          hash_update($ctx, fgets($fp,$bytesToRead));
          set_time_limit(-1);  
      }
      $sha256 = hash_final($ctx);  
      fclose($fp);

Conclusion

Hopefully what I’ve shared will be useful for you in solving your issues. Should you need any help, feel free to let me know in the comments below.

Enjoyed the content ? Share it with your friends !

PHP WordPress Print List Of Categories And Their Information

PHP WordPress Print List Of Categories And Their Information

A quick copy-paste function to print all your categories and dump some of their crucial information out.

function print_all_categories_html()
{
    $categories = get_categories( array(
        'orderby' => 'name',
        'order'   => 'ASC'
    ) );
     
    foreach( $categories as $category ) {
        $category_link = sprintf( 
            '<a href="%1$s" alt="%2$s">%3$s</a>',
            esc_url( get_category_link( $category->term_id ) ),
            esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ),
            esc_html( $category->name )
        );
         
        echo '<p>' . sprintf( esc_html__( 'Category: %s', 'textdomain' ), $category_link ) . '</p> ';
        echo '<p>' . sprintf( esc_html__( 'Description: %s', 'textdomain' ), $category->description ) . '</p>';
        echo '<p>' . sprintf( esc_html__( 'Post Count: %s', 'textdomain' ), $category->count ) . '</p>';
    } 
    
    return $categories;
}

 

Enjoyed the content ? Share it with your friends !

PHP Prevent Multiple Instances Of The Same Script

PHP Prevent Multiple Instances Of The Same Script

Using flock, you are able to lock a file and hence only allow one instance of your script to run. If your script terminates abruptly, or you fail to release the lock, the OS will automatically release the locks when the process holding them terminates. Hence, this is a much better alternative to using for example, a text file or database record.

<?php

$lock_file = fopen('path/to/yourlock.pid', 'c');
$got_lock = flock($lock_file, LOCK_EX | LOCK_NB, $wouldblock);
if ($lock_file === false || (!$got_lock && !$wouldblock)) {
    throw new Exception(
        "Unexpected error opening or locking lock file. Perhaps you " .
        "don't  have permission to write to the lock file or its " .
        "containing directory?"
    );
}
else if (!$got_lock && $wouldblock) {
    exit("Another instance is already running; terminating.\n");
}

// Lock acquired; let's write our PID to the lock file for the convenience
// of humans who may wish to terminate the script.
ftruncate($lock_file, 0);
fwrite($lock_file, getmypid() . "\n");

/*
    The main body of your script goes here.
*/
echo "Hello, world!";

// All done; we blank the PID file and explicitly release the lock 
// (although this should be unnecessary) before terminating.
ftruncate($lock_file, 0);
flock($lock_file, LOCK_UN);

 

Enjoyed the content ? Share it with your friends !

PHP WordPress Delete Duplicate Post By Title And Category

PHP WordPress Delete Duplicate Post By Title And Category

I have been looking online for a code solution that is able to check through specific categories for duplicate posts and never been able to found a solution good enough for me. Solutions online were slow and memory-consuming which was a major reason why I couldn’t use them. So I wrote my own.

For the code below to work, you need to ensure that you sort your posts in alphabetical order. The logic is that you have a inner-loop that checks from the given post (Post A) till the last post for any duplicate titles. The logic at the same time ensures that Post A will never be deleted, ensuring you have at least 1 copy of the post.

$args = [
    'post_type'     => 'post',
    'post_status'   => 'publish',
    'category_name' => $category->name,
    'orderby'   => 'post_title', 
    'order' => 'ASC',
    'post_per_page' => -1,
    'nopaging' => true,
];
$my_query = new WP_Query( $args );
$posts = $my_query->posts;

    $num_of_posts = count($posts);
    echo "category : {$category->name} <br/>";
    echo "num_of_posts : {$num_of_posts} <br/>";
    
    for($j = 0; $j < $num_of_posts; $j++)
    {
        $post = $posts[$j]; // this post will be the post that doesnt get deleted, if any duplicates exist down the line //
        $current_title = $post->post_title;
        
        for($k = $j+1; $k < $num_of_posts; $k++)
        {
            $next_post = $posts[$k];
            $next_title = $next_post->post_title;
            $next_id = $next_post->ID;
            
            if( strcmp($current_title, $next_title) == 0 ) {
                echo "Duplicate for {$current_title} with ID {$next_id} will be deleted <br/>";
                wp_delete_post($next_id, false); // move to trash first
            }
        }
    }	
}

 

Enjoyed the content ? Share it with your friends !

HostSlick BLACKFRIDAY2019-2 OVZ7 Review

HostSlick BLACKFRIDAY2019-2 OVZ7 Review

For $35/year, you get 4 cores, 6gb ram and swap, 100gb ssd and 3tb bandwidth and ipv6 connectivity. A really good deal I must say, even if it is an OpenVZ vps.

The benchmark results I have done so far shows the vps to be performing rather well. If the performance stays the same a few months down the road, this will definitely be a steal for $35

Here’s a nench.sh

-------------------------------------------------
 nench.sh v2019.07.20 -- https://git.io/nench.sh
 benchmark timestamp:    2019-11-30 18:35:43 UTC
-------------------------------------------------

Processor:    Intel(R) Xeon(R) CPU E5-2690 0 @ 2.90GHz
CPU cores:    4
Frequency:    750.000 MHz
RAM:          6.0G
Swap:         6.0G
Kernel:       Linux 3.10.0-957.12.2.vz7.96.21 x86_64

Disks:
ploop43458    100G  HDD

CPU: SHA256-hashing 500 MB
    3.646 seconds
CPU: bzip2-compressing 500 MB
    6.550 seconds
CPU: AES-encrypting 500 MB
    2.120 seconds

ioping: seek rate
    min/avg/max/mdev = 204.3 us / 281.6 us / 44.3 ms / 777.5 us
ioping: sequential read speed
    generated 3.48 k requests in 5.00 s, 870.2 MiB, 696 iops, 174.0 MiB/s

dd: sequential write speed
    1st run:    663.76 MiB/s
    2nd run:    638.96 MiB/s
    3rd run:    582.70 MiB/s
    average:    628.47 MiB/s

IPv4 speedtests
    your IPv4:    1.1.1.xxxx

    Cachefly CDN:         77.30 MiB/s
    Leaseweb (NL):        42.81 MiB/s
    Softlayer DAL (US):   10.92 MiB/s
    Online.net (FR):      34.56 MiB/s
    OVH BHS (CA):         12.86 MiB/s

IPv6 speedtests
    your IPv6:    xxxx::

    Leaseweb (NL):        20.94 MiB/s
    Softlayer DAL (US):   1.77 MiB/s
    Online.net (FR):      12.19 MiB/s
    OVH BHS (CA):         2.45 MiB/s
-------------------------------------------------

 

Enjoyed the content ? Share it with your friends !