namespaces in PHP and autoloader

References

About namespaces:

About autoloading:

About SPL:

When the autoloader is located in the folder holding your classes, then use the relative namespace for the class. For instance, if all your classes are in a Vendor folder and you want to load the User class with the path Vendor/Model/user.php, then the classname to load is ‘Model\User’. In the example below the myautoloader.php file is held in the Vendor directory.

namespace Vendor;

class MyAutoloader
{
public static function autoload(){

    spl_autoload('Model\User');

}
}
spl_autoload_register('Classes\MyAutoloader::autoload');


$conn= new Connect\Connect;

Now we would need to recursively fetch the classes in the directory to load them automatically.

File System Iterator

References:

$pathTop = __DIR__; //pathTop because we will recursively loop through directory starting from the current file directory at the top most category. Check get_url snippet to change that or use substr()

$directory = new RecursiveDirectoryIterator($pathTop, RecursiveDirectoryIterator::SKIP_DOTS); // this return an iterator sarting in the current file directory
var_dump($directory);
echo $directory;

$fileIterator = new RecursiveIteratorIterator($directory,RecursiveIteratorIterator::LEAVES_ONLY);

var_dump($fileIterator);
	
foreach($fileIterator as $file){
	echo $file.'<br>';
	$path_array=explode('\\',$file);
	echo $path_array[count($path_array)-2];
	echo '<br>';
	echo $path_array[count($path_array)-1];
}

Get a form input field value with javascript

You can use document.getElementById("input_field_id"); or you can use:

var form=document.forms["form_name"];
var input_value= form["input_field_id"].value;

Note that the typeof(input_value) will be string even if the type of the input field is “number”.

So even if you enter an integer in the field Number.isInteger(input_value) will return false and typeof(input_value) will return string.

Incorrect integer value: ” for column …

Error message: Incorrect integer value: ” for column

Error description: the error occurs when inserting an empty value in a column.

Solution: This behavior is normal and shows that your sql-mod is set to strict. To change that access your server and look for the my.ini file. Locate the sql-mode line and set it as sql-mod=””

Set a dedicated 404 page in .htaccess

In the redirect section of your .htaccess file just add the following line:

ErrorDocument 404 https://example.com/404/

Replace the url by the actual url of your dedicated 404 page as you would do for any other redirect.

Now all what’s left to do is to create the page in your CMS back end (or code one in html if you are running a static site).

Get the time it takes to run a given function in PHP

To get the time in microsecond you will need to use microtime() instead of time().

You will need microtime() to return a float so set $getAsFloat to true like this:

microtime(true);

Most of the function are really fast so to get something measurable you might need to run them several thousands time within a loop:

$start=microtime(true);
for( $i=0;$i<100000;$i++){
  //the function you want to test
}
$end=microtime(true)
$total_runtime=$end-$start;

You might want to use this method to compare two functions and verify which one is the fastest. You can then compare the time it took to run each of your function and pick the smallest one.

Get the category archive name and description in a wordpress theme

If you need to access your achive title and or description, you can the code below. I used it to take the description as meta description. A better policy would be to write a custom metadesciption. But that’s a quick fix while you are working on a better solution.

    $title=get_the_archive_title();
    echo(explode('<',explode('>',$title)[1])[0]);
    if(get_the_archive_description()){
	echo '<meta name="description" content="'.preg_replace('/\<.*\>/',' ',get_the_archive_description()).'">';
    }

Change number of product displayed in woocommerce

Add this code in you theme functions.php. Make a child theme if you are using someone else theme to avoid your changes being overwritten during the next update.

/**
 * Change number of products that are displayed per page (shop page)
 */
add_filter( 'loop_shop_per_page', 'new_loop_shop_per_page', 20 );

function new_loop_shop_per_page( $cols ) {
  // $cols contains the current number of products per page based on the value stored on Options -> Reading
  // Return the number of products you wanna show per page.
  $cols = 9; //Enter the number of products you want per page here
  return $cols;
}
https://docs.woocommerce.com/document/change-number-of-products-displayed-per-page/

Add open graph meta to your virtuemart and joomla template.

Facebook usually does a good job at picking up all the required information from your web page but there is some instance where you might want to have better control on what image is displayed as thumbnails or have a customize description for Facebook sharing. In that case you will need to use facebook open graph.

List of basic properties: https://ogp.me/

  • og:title
  • og:type
  • og:image
  • og:url

The required meta properties for open graph are the following according to facebook Sharing Debugger :

  • og:url
  • og:type
  • og:title
  • og:image
  • og:description
  • fb:app_id

og:url

We will need to get the URL of the page currently displayed. Joomla doc gives us the solution here: https://docs.joomla.org/URLs_in_Joomla

In index.php simply add:

use Joomla\CMS\Uri\Uri;
$uri = Uri::getInstance();
$url = $uri->toString();

And within your <head> element:

<meta property="og:url" content="<?php echo $url; ?>"/> 

og:title

To get the current page title, Joomla documentation gives us again the answer: https://docs.joomla.org/Add_Static_Text_In_Title_Of_Page

<?php
$title = $this->getTitle();
?>

and within the <head> element:

<meta property="og:title content="<?php echo $title; ?>"/>

og:image

Automated this task will be a bit more challenging as the URL of the image will change from page to page. For instance, images from home page, post and product and category pages won’t be called the same so you have to check the type of page you are displaying to call the right type of image.

For the home page, you can set the og:image content manually. You will need to check first if the user is currently viewing the front page:

https://docs.joomla.org/How_to_determine_if_the_user_is_viewing_the_front_page

<?php 
$app = JFactory::getApplication(); 
$menu = $app->getMenu(); 
$lang = JFactory::getLanguage(); 
if ($menu->getActive() == $menu->getDefault($lang->getTag())) 
 { 
  echo 'This is the front page'; 
 } 
else 
 { 
  echo 'Accueil'; 
 } 
?>

It seems there is a bug in Facebook Open Graph for the image property in website requiring https. We speak about it here. On my side the issue is only present in messenger. Sharing a page as a post is working as expected.

og:type

The default is ‘website’ but there exists a ‘product’ type that can be of interest in product pages

<meta property="type" content="website" />

Facebook OpenGraph doesn’t diplay the image set into the og:image meta and pick another

Issue: Facebook OpenGraph doesn’t diplay the image set into the og:image meta and pick another one instead.

It seems to be an issue with https URL in open graph. There is a closed bug report in facebook without answer from facebook.

developers.facebook.com

Some people in stackoverflow have found a work around.

stackoverflow.com

Work around 1: upload all your picture in a non https domain and use these URL for your og:image content property.

Work around 2: use og:image:secure_url and use the facebook sharing debugger to lint your page. https://developers.facebook.com/tools/debug/ [Work around currently in test]

Code end up on one line after Filezilla upload.

Issue description:

End of line are removed from file after uploading a file to your server through filezilla or any other FTP software.

https://trac.filezilla-project.org/ticket/3830

One of the answer on the bug report above describe the issue clearly:

For the benefit of anyone like me who finds this after having experienced exactly the same issue, I believe I have a more rigorous explanation for exactly what’s going on. Codesquid posted a link on #5486 that provides all of the relevant information, which I shall re-post here for convenience:

​http://wiki.filezilla-project.org/Data_Type

The bug appears to lie in the standard itself, rather than Filezilla specifically. That is, the actions defined to ensure that \r\n line endings are always transmitted and then converted by the receiver to whatever is appropriate for that platform may fail if the source file itself has the wrong line endings for the client platform. For example (assuming one transfers the file using the ASCII data type):

IF: a file with CR-only line endings is uploaded
FROM: a windows client
TO: a linux server
THEN: the transmitted file will only feature CRs, which will be deleted
RESULTING: in a file with no newlines

Which is very bad news if your file contains line comments, since this will effectively change its meaning. Similarly,

IF: a file with Windows line endings (CR+LF) is downloaded
FROM: a Linux/Mac server
TO: a Windows or Mac/Linux client
THEN: additional unwanted CR/LFs will be inserted
RESULTING: in a file with mixed or double newlines

Other scenarios of this type can clearly be concocted, but I would have thought these two would be the most common. As codesquid pointed out, the data type can be specified for transfers. In the absense of a parser in Filezilla to handle malformed newlines, the only safe answer appears to be to use the binary type for all transfers.

More infor about Data type available here:

https://wiki.filezilla-project.org/Data_Type

To check the type of carriage return used in your file, you can turn that on in notepad ++ in View->Show Symbol->Show End of Line.

In my case, once downloaded via ftp from the linux server to my windows machine, the file showed CR for mark the end of the line. Other files not causing issue are making use of both CR and LF.

When reuploading the file using only CR on the linux server. All CR are removed and the file open in a single line when I open it for edit through FTP. As it is an executable file including comment, some code are commented out and the script don’t execute properly anymore.

Solution: To solve the issue, you can open use find and replace extended mode in Notepad++ and, in my case, replace \r by \r\n and save.