Latest News: (loading..)

Archived

This topic is now archived and is closed to further replies.

burt

Useful Snippets of Code

50 posts in this topic

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!

 

 

 

 

.

Juto likes this

Share this post


Link to post
Share on other sites

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);

EchoGuns, Biancoblu and alc1dz like this

Share this post


Link to post
Share on other sites

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');

Biancoblu likes this

Share this post


Link to post
Share on other sites

@@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.

Share this post


Link to post
Share on other sites

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");

John W likes this

Share this post


Link to post
Share on other sites

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

Biancoblu likes this

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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 ) );

Share this post


Link to post
Share on other sites

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).

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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);
   }
 }

katapofatico likes this

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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..

Share this post


Link to post
Share on other sites

a great tool for that : github gist.https://gist.github.com/

(and maybe a future integration in osCommerce Website?)

Share this post


Link to post
Share on other sites

for .htaccess

 

 

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

Share this post


Link to post
Share on other sites

for .htaccess

 

 

 

# Eliminates duplicate home page i.e.: www.domain.com/index.php and www.domain.com appear as duplicate home page

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php\ HTTP/
RewriteRule ^index\.php$ http://www.domain.com/ [R=301,L]

Share this post


Link to post
Share on other sites

for .htaccess

 

# Disable http track for PCI compliance
RewriteCond %{REQUEST_METHOD} ^TRACK
RewriteRule .* - [F]

Share this post


Link to post
Share on other sites

@@cannuck1964

 

In addition to your last post this works pretty well for the same purpose in your .htaccess:

 

#only allow GET, POST, HEAD requests
<LimitExcept GET POST HEAD>
Deny from all
</LimitExcept>

Share this post


Link to post
Share on other sites

for htaccess

 

 

Add this in to stop scripts from running in folders that should not have scripts in them ie images, downloads, tmp, etc

 

This adds a layer of security to the folder (s) to stop some hacking techniques employed.

 


# stop scripts from running from the folder
IndexIgnore *
Options All -Indexes
# Secure directory by disabling script execution
AddHandler cgi-script .php .php2 .php3 .php4 .php5 .php6 .php7 .php8 .pl .py .jsp .asp .htm .html .shtml .sh .cgi
Options -ExecCGI
# Don't show this file, that would be bad as well!
<Files .htaccess>
order allow,deny
deny from all
</Files>

Share this post


Link to post
Share on other sites

alternate .htaccess rules, simular to Peters, but with no need to input the actual FQD.

# Option 1:
# Rewrite "www.example.com -> example.com"
<IfModule mod_rewrite.c>
 RewriteCond %{HTTPS} !=on
 RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
 RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>

# Option 2:
# To rewrite "example.com -> www.example.com" uncomment the following lines.
# Be aware that the following rule might not be a good idea if you
# use "real" subdomains for certain parts of your website.
#<IfModule mod_rewrite.c>
#  RewriteCond %{HTTPS} !=on
#  RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
#  RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
#</IfModule>

Share this post


Link to post
Share on other sites