[PHP] Normalization of strings – Upper and lower case


today again a small task to do in PHP. The following situation:

We have a text-string in which is (obviously) a text. Lets say the content is:
HERE you’ll get today CHEAP cucumber DIRECT from the farmer.
We would like to change this string now like we want to change all words which consist only uppercase letters in: first letter uppercase and the rest lowercase. Like it should be.
Of course we should check now as well which really start with an uppercase letter, if they are in the middle of the sentence. Else we would mess up badly the orthography.
But if you don’t have a good dictionary (database) and a good routine lying around… then we need to be happy with my routine for now like it is.

So, the task is clear. Letter only in uppercase shall be converted in first letter uppercase and the rest lowercase. Like for the example above: HERE -> Here

There is no ready solution for it. We need to make our own function. The first thought is to split each word of the text, to check each word if it is consist only capitals. If yes, then convert, if not… then not. After all putting everything together again and finish.

As far, as good. Is working very well. Just one thing I’ve mentioned. I’ve used to convert first the function ucfirst(). This is doing exactly that. First letter capital and the rest lower case. We just need to convert everything before into small letters with strtolower().
And here I got the problem. By accident I used a string with German umlauts. And the function strtolower() messed up the umlauts. Which is probably not important for the English languages, as there are no such umlauts… but maybe it is interesting as well for Turkish or Spanish or French (as example).
So, what can we do? I found the solution with: mb_strtolower($String,’UTF-8′)

As you can see you can specify the charset (in this case ‘UTF-8’). That works very well and the umlauts are correct.

And here the whole code snippet:

function NormalizeString($String) {
		$StrA = explode(" ", $String);
		$StrAc = count($StrA);
		$Out = "";
		for($i=0;$i<$StrAc;$i++) {
			$tmp = preg_replace('/[^a-zA-ZäÄöÖüÜß]/', '', $StrA[$i]);
			if(!empty($tmp) && strtoupper($tmp) == $tmp) {
				//Alles groß
				$StrA[$i] = ucfirst(mb_strtolower($StrA[$i],'UTF-8'));
			$Out .= $StrA[$i]." ";
		return $Out;

First of all we create an array with all single words, using explode(). Then we pass through every single word with an For-Loop. We copy the word in a temporary variable to clean it up to compare it better. If the word is upper case, then we convert it. And finally we put the string together again and give it back. That’s it.

Best regards

[PHP] Date and date functions


let’s talk today about date functions in PHP.

If you are looking for an interactive clock for your homepage, then you should look into Javascript functions. That is not possible with PHP. PHP is a server side language and can’t interact direct with the browser. Ok, you could try to play around with AJAX and reloads, but this is hard and why not using easier things…

But back to the subject. Date and PHP. I’ll show you some functions of the date class of PHP. The most important is date().

Date() return an formated date. It can be the current date or a date from an variable. For example it can be a timestamp from an database field. Also can be provided a format for the date. Just date or just time or both… and in various formats.
string <strong>date</strong> ( string <code>$format [, int $timestamp = time() ] )

Another, often used, function is mktime(). This command simply returns a UNIX timestamp. This timestamp can be saved in a database or can be used for whatever. You can provide also a date to get the timestamp for it, for example 01-03-1998.
I use it mostly without, to get the current timestamp.

int <strong>mktime</strong> ([ int <code>$hour = date(“H”) [, int $minute = date(“i”) [, int $second = date(“s”) [, int $month = date(“n”) [, int $day = date(“j”) [, int $year = date(“Y”) [, int $is_dst = -1 ]]]]]]] )

And with strtotime() you get the timestamp of a date which is saved in a variable. For example you got from somewhere the string “2000-07-01T00:00:00+00:00” and you need the timestamp for this date (in a string variable). Then use strtotime() and you’ll get it and can be saved into a database or whatever.

int <strong>strtotime</strong> ( string <code>$time [, int $now ] )

These are my 3 most used date function in PHP. There are at all 50 and more. If you like to know more about them, please have a look at php.net.

I hope that could help you a bit.

Best regards

[PHP] Automatical redirect


today I would like to talk quick about the subject “Redirection with PHP”. Quick, because there is not much to say :)

The code for a redirect in PHP looks like that:

	header("Location: http://www.domain.de/seite.php"); 

header() is sending the HTML-header. With “Location:” you’re telling it that it is an redirect. After it you provide the URL to which the redirect it pointing to. And with exit(); we tell the script to abort, not to execute any other code.

But I also have to mention to thing about what you do before you set an redirect. Is it a permanent redirect, because something changed in the webpage structure (for example a page got a new URL), then you should “say” that in the redirect, else it can occur problems with the search engine rankings.

A permanent redirect looks then like that:

	header("Status: 301 Moved Permanently");
	header("Location: http://www.domain.de/seite.php"); 

The line header("Status: 301 Moved Permanently"); is sending the status code that the redirect is permanent. There are also other status codes, like the 302 code, which is for temporarily redirects.
If e.g. the Google bot comes around and gets an 301 status code for a URL, then it will save the URL change and is crawling next time straight the new page. Like that the new page gets the ranking of the old page and it doesn’t get lost.

The good thing on PHP redirection is that it happened on the server side and will always work. On the other side you can make it dynamically. Redirection with the .htaccess can be also dynamic, but not as good as with PHP. Redirects in the HTML-Header are totally underground. The same for Javascript redirects. They doesn’t work at all for spider and user without Javascript.

I hope it’s helping. If not, let me have a comment :)

Best regards

[PHP] Round numbers with PHP


today again a bit PHP. A small tip about handling with numbers in PHP. Or more explicit, round off numbers.

PHP comes already with several functions to handle numbers. Four of them are number_format, ceil, floor and round. My personal favorite is  number_format. Why?

Because this function does not just round, it is also formatting the number. The syntax is:

Syntax: string <strong>number_format</strong> (float number [, int <code>decimals [, string decimal separator, string thousands separator]])

This function can be called with 2 or 4 parameter, but not with 3. So

number_format (<code>number);
number_format (<code>number, <code>decimals)
number_format (<code><code>number, <code>decimals, decimal separator, thousands separator);

An example:

number_format (15329.6956, 2, ",", ".");

The output will be: 15.329,70

The next function, resp. functions are ceil and floor. This functions simply round up (ceil) or down (floor). The syntax is float ceil (float $number) reps. float floor (float $number). In both cases will be the number rounded up- or down on the next integer.

Last but not least the round function. It’s the middle way between the last 3 functions. It rounds a floating-point number up or down and you can provide a decimal place. The syntax is:
float <strong>round</strong> ( float <code>$number[, int $<code><code><code>decimals = 0 [, int $mode]] )

An example:

round(15.1698, 2) results: 15.17

Please note that you’re working always with the English number format while you’re programming. Decimal places are separated with a dot “.” and the thousands separator (if they have a separator) with a comma “,”.

Best regards

[PHP] Comments in PHP scripts

Hello together.

Lets talk today about comments :)
When you start coding a script then is it useful to comment your code. So a small documentation in the script. Because as long as you are working on the script and it is in a relative small size, then you know still which line of source code is doing what.

But latest when you source code is growing bigger and/or you need to work on it after a few weeks or months… then is everything gone. How was it? What is this line doing? Where do I find this and this now? Everything gone… the code is just a big pile of confusing.
Latest now you’ll kick your ass that you haven’t commented the code.

Of course it takes a bit longer if you write also comments in the code… but some when it will pay back. Also (and especially) if the code will be handed over to another programmer is it important that the code is commented.

And it is soooo simple ;) 2 slashes (//) for one line and a slash with a star for a multiple-line comment (/* at the beginning and */ at the end). And it will look like that:

echo "vor dem Kommentar";
// Hier ein Einzeiliger Kommentar
echo "nach dem Kommentar";

And a multiple line comment:

echo "vor dem Kommentar";
/* Dieser Kommentar
   geht über mehrere
   Zeilen */
echo "nach dem Kommentar";

Best regards

[PHP] Delete a file with PHP

Hi together,

today I wand to answer the question how to delete a file with PHP.

First of all we have to separate. Files on the web server or files on the local hard disk. First yes, second no.
PHP doesn’t have access to files of the local file system of a visitor. No server side programming language can do it. Also client side languages (like Javascript) can’t do it. Else it would be easy for every single webpage to delete randomly files from your computer. That would be an disaster.

But on the web server is it – partly – possible to delete files. Partly means that you can’t delete every file. Also this would be a disaster.

The PHP-Script needs the right to delete files or at least specific files. Under Linux is the right system very strict.

But in the normal situation is it not so complicated like it sounds like. Because usually you delete a file which you created with the script. Like a temporary file or a file from a user upload (a picture for example). Such a file was created by the PHP script and inherit it’s user rights. And also the script has the right to delete this file again.

But how?
Very simple. All we need is the PHP command for deleting a file and the path of the file itself. It fits all in one code line.

$res = unlink("testdatei.hm");

That’s it. In $res we get a return value. 1 = successful deleted or 0 = Couldn’t delete the file.

You can use relative as well as absolute paths.

That’s it. Hope it was helpful :)

[PHP] How to add a line break in PHP


today I’ll like to talk about the subject line breaks with PHP. I guess this article will be not very long, because it’s done with a few lines of code. :) Read more

Integrate affiliate tracking codes in Prestashop


I’ve opened now my first online shop and quickly the question came up… how to find customer. Or who could help me with it.
Quickly I found one possible answer… affiliate marketing. It’s anyway my preferred method from all I know and for which my wallet is big enough. Everything else is not economical or just to expensive… most both.

So, I started a campaign at my favorite affiliate network. And then the big question… how to integrate the tracking code in my Presta shop system? :o
That is not so easy, because there are variables to send.

Luckily we have the internet. :) And I found the answer in a forum. Here the quote summary of PaoloPinkel:


1.) Add this to the init.php:

  $_SESSION['belboonSession'] = Tools::getValue('belboon');

2.) And this to the order-confirmation.php:


3.) The code from Belboon has to be added into the order-confirmation.tpl. In this sniped you need to replace NETTOWARENWERT (sorry, don’t know what is written in the english version ‘Net value’?) with {$belboon}, ORDERCODE with {$id_order} and xxxx,yyyy with {$belboonSession}.

That’s it. If you have to transfer VAT then you have to reduce it from getTotalProductsWithTaxes() somehow. Else they pay to much commission.

(Quote from http://www.homepage-community.de/…)

PaoloPinkel is using the affiliate network Belboon. I use a different network. But the concept is the same. You just need to customize the variables.

Thank you to PaoloPinkel and Chris.

Best wishes

[PHP] Show/print all variables in use.


today I asked myself how the variables look like at the end of my script. I mean I use variables, include scripts, make database requests… and I always try to care to unset the variables again when I don’t need them anymore. But to I get all… or does my script use more and more memory? And how can I control it?

PHP have also for this question a solution. get_defined_vars() shows all variables which are currently in use.


Call this function at the end (or somewhere between) and you know exactly which variables are in use and where you have to clean up.

Very nice :-)

Best regards

[PHP] Generate a random password


because I need that from time to time and always looking again for a good function… here my memory aid. :-)

$pwZeichen = 'wertzupasdfghkyxcvbnmWERTZUPLKJHGFDSAYXCVBNM23456789';
srand ((double)microtime()*1000000);
for($i = 0; $i < 5; $i++) {
$passwort .= substr( $pwZeichen, (rand()%(strlen ($pwZeichen) ) ), 1);

In the variable $pwZeichen are all signs which can be used in the password. ‘srand’ starts the random generator (else the password would include always the same signs) ;-)
The ‘for’ loop set how long the password will be. Here 5 digits. You can change the value of course. And last but not least are the signs added to the variable $passwort.

That’s it :)