Jump to content



Photo
* * * * * 3 votes

Useful Snippets of Code


  • Please log in to reply
49 replies to this topic

#1   burt

burt

    I drink and I know things

  • Community Team
  • 12,438 posts
  • Real Name:G Burton
  • Gender:Male
  • Location:UK/DEV/on

Posted 22 October 2012 - 06:06

A thread for useful snippets of code, mainly one liners, please don't post entire pages of code.
If you have a useful snippet please post it!




.

Edited by burt, 22 October 2012 - 06:10.

This is a signature that appears on all my posts.  It is not specifically aimed at you.

 

IF YOU MAKE A POST REQUESTING HELP...please state the exact version of osCommerce that you are using. THANKS
 
If you are still on the old style osCommerce, it is time to move to Responsive.

 


#2   burt

burt

    I drink and I know things

  • Community Team
  • 12,438 posts
  • Real Name:G Burton
  • Gender:Male
  • Location:UK/DEV/on

Posted 22 October 2012 - 06:09

Update all prices in Database to 1 cent under the $/£ etc

Eg, 14.50 becomes 14.99

Backup your DB and run this in PHPMyAdmin.

UPDATE `products` SET `products_price` = (ceil(`products_price`)-0.01);

This is a signature that appears on all my posts.  It is not specifically aimed at you.

 

IF YOU MAKE A POST REQUESTING HELP...please state the exact version of osCommerce that you are using. THANKS
 
If you are still on the old style osCommerce, it is time to move to Responsive.

 


#3   Harald Ponce de Leon

Harald Ponce de Leon

    Healthy Giraffe

  • Core Team
  • 5,346 posts
  • Real Name:Harald Ponce de Leon
  • Gender:Male
  • Location:Solingen, Germany

Posted 22 October 2012 - 11:29

Hide deprecated PHP 5.3 notices by setting the error report level. In includes/application_top.php and admin/includes/application_top.php:

// set the level of error reporting
  error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);

Even better, don't display error messages and log them instead to a file:


ini_set('display_errors', false);
ini_set('log_errors', true);
ini_set('error_log', '/path/to/errors.txt');

:heart: , osCommerce


#4   14steve14

14steve14
  • Members
  • 4,361 posts
  • Real Name:Steve
  • Gender:Male
  • Location:Dorset UK

Posted 22 October 2012 - 11:54

Even better get the errors sorted so the dont appear.

REMEMBER BACKUP, BACKUP AND BACKUP

 

Find information about the bootstrap community version here

 

Success is the ability to go from one failure to the next without any loss of enthusiasm


#5   Biancoblu

Biancoblu

    1291 Giger's Alien

  • Members
  • 752 posts
  • Real Name:Isabella
  • Gender:Female
  • Location:Switzerland

Posted 22 October 2012 - 18:38

@burt
Thanks for starting this thread Gary, and for the tip :thumbsup:

@Harald Ponce de Leon
Thanks for sharing this :)
~ Don't mistake my kindness for weakness ~

#6   mattjt83

mattjt83
  • Members
  • 515 posts
  • Real Name:Matt Toste
  • Gender:Male
  • Location:CA, USA

Posted 22 October 2012 - 22:38

@Harald Ponce de Leon

I found this other solution for error logging...

Setting error logging with ini_set() is not an ideal solution because it will not log any errors if the script has parse errors and cannot be run at all.

-instead-

Set error logging in .htaccess and virtual host directives. This is a better option because it will log the errors even if there's a parsing error in your script.

php_value log_errors 1
php_value error_log /path/to/php-error.log

The error log will be written to as the user the web server runs as so it must be writeable by that user. In most cases you'll probably need to make it world-writeable to be able to do this. On a *nix server this is 0666 file permissions.

A couple of example lines from an error log are as follows:

[13-May-2009 21:54:04] PHP Notice:  Undefined variable: x in /common/websites/test/error-log.php on line 6
[13-May-2009 21:54:09] PHP Parse error:  syntax error, unexpected '}' in /common/websites/test/error-log.php on line 5

Source: electrictoolbox.com

Seems like both solutions have their pros and cons depending on what stage you are at with your sites development.

Matt


#7   burt

burt

    I drink and I know things

  • Community Team
  • 12,438 posts
  • Real Name:G Burton
  • Gender:Male
  • Location:UK/DEV/on

Posted 23 October 2012 - 07:50

Scan through all your product descriptions and update mis-spellings...

Eg, replace the word "Matrox" with the word "Matrocks" (silly example, but you get the idea).

Backup your DB and run this in PHPMyAdmin.

UPDATE `products_description` SET `products_description` = REPLACE(`products_description`, "Matrox", "Matrocks");

This is a signature that appears on all my posts.  It is not specifically aimed at you.

 

IF YOU MAKE A POST REQUESTING HELP...please state the exact version of osCommerce that you are using. THANKS
 
If you are still on the old style osCommerce, it is time to move to Responsive.

 


#8   foxp2

foxp2

    strong as a Twig

  • Banned
  • 310 posts
  • Real Name:Laurent
  • Gender:Male
  • Location:France

Posted 23 October 2012 - 12:19

Some SQL queries for Stats

avg age by genre :

SELECT customers_gender as Gender,
COUNT(CASE WHEN customers_gender LIKE 'm' THEN 'male' ELSE 'female' END) as numberByGender,
AVG(TIMESTAMPDIFF(YEAR,(customers_dob), now())) AS avg_age
FROM customers group by Gender


percentage for genre (male/female)

SELECT customers_gender as Gender,
COUNT(CASE WHEN customers_gender LIKE 'm' THEN 'male' ELSE 'female' END) / COUNT(*) * 100 AS numberByGender
FROM customers group by Gender


percentage for genre (male/female/unknow)

SELECT SUM( IF( customers_gender LIKE 'm', 1, 0 ) ) / COUNT(*) * 100 AS male,
SUM( IF( customers_gender LIKE 'f', 1, 0 ) ) / COUNT(*) * 100 AS female,
SUM( IF( customers_gender LIKE '', 1, 0 ) ) / COUNT(*) * 100 AS nogenre
FROM customers order by customers_gender


number of customers gender

SELECT SUM( IF( customers_gender LIKE 'm', 1, 0 ) ) AS male,
SUM( IF( customers_gender LIKE 'f', 1, 0 ) ) AS female,
SUM( IF( customers_gender LIKE '', 1, 0 ) ) AS nogenre
FROM customers order by customers_gender


percentage account created by year

SELECT
YEAR(customers_info_date_account_created) as years,
((COUNT(*)/(SELECT COUNT(*) FROM customers))*100) as percentage
FROM customers_info group by years


Breakdown by avg age and genre (number + percent)

SELECT CASE WHEN customers_gender LIKE 'm' THEN 'male' WHEN customers_gender LIKE 'f' THEN 'female' ELSE 'unknow' END as Gender,
COUNT( customers_gender ) as numberByGender,
ROUND(((COUNT(*)/(SELECT COUNT(*) FROM customers))*100),2) AS numberByGenderPerCent,
ROUND(AVG(TIMESTAMPDIFF(YEAR,(customers_dob), now())),0) AS avgage
FROM customers group by Gender

-------------------

#9   burt

burt

    I drink and I know things

  • Community Team
  • 12,438 posts
  • Real Name:G Burton
  • Gender:Male
  • Location:UK/DEV/on

Posted 23 October 2012 - 21:43

Get a list of products ordered including customers email address so that you can email the customer. Eg, a seasonal promotion.

SELECT DISTINCT op.products_name, o.customers_name, o.customers_email_address FROM orders o LEFT JOIN orders_products op ON o.orders_id = op.orders_id ORDER BY op.products_name

This is a signature that appears on all my posts.  It is not specifically aimed at you.

 

IF YOU MAKE A POST REQUESTING HELP...please state the exact version of osCommerce that you are using. THANKS
 
If you are still on the old style osCommerce, it is time to move to Responsive.

 


#10   burt

burt

    I drink and I know things

  • Community Team
  • 12,438 posts
  • Real Name:G Burton
  • Gender:Male
  • Location:UK/DEV/on

Posted 25 October 2012 - 06:53

Get a list of all the files in the base of your shop, as an array;

$files_array = array_map('basename', glob(DIR_FS_CATALOG . '*.php'));

Now you could make a "site map" for example, or do 1000 other things with this.

This is a signature that appears on all my posts.  It is not specifically aimed at you.

 

IF YOU MAKE A POST REQUESTING HELP...please state the exact version of osCommerce that you are using. THANKS
 
If you are still on the old style osCommerce, it is time to move to Responsive.

 


#11   Gergely

Gergely

    Json Juggler

  • Community Team
  • 2,112 posts
  • Real Name:Gergely Tóth
  • Gender:Male
  • Location:Budapest

Posted 25 October 2012 - 20:09

The most unbelievable fastest silly useful codes in windows system command prompt when create a developing file :D

copy con>myfile.php (enter)
ctrl+z (enter)

or

Notepad++ myfile.php

Next PHP changes will kill the current codes on the following years. We should do programing for the future and never stick in the present.

My addons: Conversion Tools::Hungarian Translation::Email Templates::URL redirection
 
Development Works: Setup Languages::Email Templates::Languages from ini files::Parcel Shops::Facebook App
 
What core codes have been complained?

In orders table payment_methods value would be better if payment class name used than payment's language name.
In the orders class we found order status does not contains $order->info['orders_status'] but instead there is $order->info['orders_status_name'], and that property is language dependant.
We can not identify in order the customer language.


#12   Gergely

Gergely

    Json Juggler

  • Community Team
  • 2,112 posts
  • Real Name:Gergely Tóth
  • Gender:Male
  • Location:Budapest

Posted 25 October 2012 - 20:41

when cant delete file from FTP layer or in php code by character problems:

$myfile= "images/papirtĂĄlca.jpg";
unlink($myFile);
result: false


Be very carefull with this code because a really effective file killer snippets!
$mask = "images/papirt*lca.jpg";
array_map( "unlink", glob( $mask ) );

Next PHP changes will kill the current codes on the following years. We should do programing for the future and never stick in the present.

My addons: Conversion Tools::Hungarian Translation::Email Templates::URL redirection
 
Development Works: Setup Languages::Email Templates::Languages from ini files::Parcel Shops::Facebook App
 
What core codes have been complained?

In orders table payment_methods value would be better if payment class name used than payment's language name.
In the orders class we found order status does not contains $order->info['orders_status'] but instead there is $order->info['orders_status_name'], and that property is language dependant.
We can not identify in order the customer language.


#13   burt

burt

    I drink and I know things

  • Community Team
  • 12,438 posts
  • Real Name:G Burton
  • Gender:Male
  • Location:UK/DEV/on

Posted 26 October 2012 - 09:35

You can use rtrim to get rid of things on the end of a string...


$rick = "Never Gonna Give You Up.......";
echo rtrim($rick, '.');

If you have no parameter (example above: , '.' ), then whitespace is stripped (which can be very useful).

This is a signature that appears on all my posts.  It is not specifically aimed at you.

 

IF YOU MAKE A POST REQUESTING HELP...please state the exact version of osCommerce that you are using. THANKS
 
If you are still on the old style osCommerce, it is time to move to Responsive.

 


#14   Juto

Juto
  • Members
  • 369 posts
  • Real Name:Sara
  • Gender:Female

Posted 26 October 2012 - 10:33

htaccess secure your admin side, put this in your admin folder:

# check admissible IP-address
<FilesMatch "...">
Order deny,allow
Deny from all
# allow your ip address:
allow from 12.34.56.789
</FilesMatch>

Sara

#15   Harald Ponce de Leon

Harald Ponce de Leon

    Healthy Giraffe

  • Core Team
  • 5,346 posts
  • Real Name:Harald Ponce de Leon
  • Gender:Male
  • Location:Solingen, Germany

Posted 08 November 2012 - 17:29

or if you have a dynamic IP address and can't use Sara's rule, this will block automatic intrusion tools:

<LocationMatch "^(.*)/admin/(.*/)+login\.php(.*)$">
  deny from all
</LocationMatch>

That doesn't work in .htaccess though and must be added to your server configuration in Apache's httpd.conf file.

Edited by Harald Ponce de Leon, 08 November 2012 - 17:29.

:heart: , osCommerce


#16   bruyndoncx

bruyndoncx

    osCommerce Teenager

  • Members
  • 3,770 posts
  • Real Name:Carine Bruyndoncx
  • Gender:Female
  • Location:Belgium/ Antwerp/ Turnhout/ Arendonk

Posted 18 November 2012 - 23:59

Storing the configuration in APC cache for 1hr

in application_top

replace

	   $configuration_query = tep_db_query('select configuration_key as cfgKey, configuration_value as cfgValue from ' . TABLE_CONFIGURATION);
	  while ($configuration = tep_db_fetch_array($configuration_query)) {
	    define($configuration['cfgKey'], $configuration['cfgValue']);
	  }
with
// set the application parameters
/* in APC Cache */
  if (($configurationArr = apc_fetch('configuration')) === false) {
	 $configuration_query = tep_db_query('select configuration_key as cfgKey, configuration_value as cfgValue from ' . TABLE_CONFIGURATION);
	  while ($configuration = tep_db_fetch_array($configuration_query)) {
	    define($configuration['cfgKey'], $configuration['cfgValue']);
	    $configurationArr[$configuration['cfgKey']] = $configuration['cfgValue'];
	  }
	  apc_store('configuration', serialize($configurationArr), 3600);
  } else {
    $configurationArr = unserialize($configurationArr);
    while ( list ($apckey, $apcval) = each($configurationArr)){
	  define($apckey,$apcval);
    }
  }

KEEP CALM AND CARRY ON
FYI Just upgraded from PHP 5.3 to PHP 5.5  and saw big performance improvement.
But be aware php 5.5 is more strict about things.
UTF8-without BOM, no extra spaces allowed at the beginning or end of your php file, or your redirects wont work.
No double declarations of functions allowed - used to slip through the cracks ...

#17   burt

burt

    I drink and I know things

  • Community Team
  • 12,438 posts
  • Real Name:G Burton
  • Gender:Male
  • Location:UK/DEV/on

Posted 05 December 2012 - 08:39

You can use rtrim to get rid of things on the end of a string...


I had to use this in a osCommerce context yesterday. A site I am updating uses "QPBPP" (Quantity Price Breaks Per Product). Some price breaks go to the 3rd decimal place, which osCommerce can't display very well using the $currencies class.

So, I stripped the prices (priceformatter.php) out of the $currencies class and instead used the "raw". I then rtrimmed the 0's off the end of the prices, so (for example), this: 0.0750 would display 0.075

If this has been left in the $currencies class, that 0.0750 would have displayed as 0.08 (no good!).

--

And here is another useful snippet, for looking at arrays of information

echo '<pre>';
print_r($cart);
echo '</pre>';

This will show the available information from the $cart class.

This is a signature that appears on all my posts.  It is not specifically aimed at you.

 

IF YOU MAKE A POST REQUESTING HELP...please state the exact version of osCommerce that you are using. THANKS
 
If you are still on the old style osCommerce, it is time to move to Responsive.

 


#18   jaysh4922

jaysh4922
  • Members
  • 26 posts
  • Real Name:Sanjay Sharma
  • Gender:Male

Posted 10 December 2012 - 07:19

i am a developer and i think everydeveloper should have a tool to store their code snippets to speed up their daily work. If you have just started your programming journey, there might not be any code snippets you might want to keep. However, it's will be great to have a tool ready, in case when you come across certain code snippets that you want to add into your library, you can stuff as a right way..

Having many more benefits of storing code snippets like sving time on typing decrease search time etc etc..

Thanku
Sanjay..

#19   foxp2

foxp2

    strong as a Twig

  • Banned
  • 310 posts
  • Real Name:Laurent
  • Gender:Male
  • Location:France

Posted 10 December 2012 - 10:57

a great tool for that : github gist.https://gist.github.com/
(and maybe a future integration in osCommerce Website?)
-------------------

#20   cannuck1964

cannuck1964

    Contract Coder

  • Partner
  • 1,145 posts
  • Real Name:Peter McGrath
  • Gender:Male
  • Location:Ontario, Canada

Posted 03 January 2013 - 18:23

for .htaccess


# Eliminates www vs. non-www
RewriteCond %{HTTP_HOST} ^domain\.com
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=permanent,L]

Peter McGrath
-----------------------------

See my Profile (click here) for more information and to contact me for professional osCommerce support that includes SEO development, custom development and security implementation