PHP For Beginners

Code samples and code snippets for new php programmers

PHP For Beginners header image 4

Mac OS X How to Clean Desktop - Clear Desktop Icons

July 9th, 2009 by Esa
Respond

OK, this post is unrelated to php, but I figured I’d blog it anyway for the possible benefit of other Mac OS X users.

If you’re like me, your desktop will accumulate clutter very fast. At the end of a workday, it looks messy, uses up memory and things become difficult to find.

An easy way to clean your Mac desktop - I do this every day - is to use the Terminal application (shell), and type these commands:

(everything between ~ and $ represents the prompt so don’t type this. Type only the text I’ve written in italic. The ~ sign means you’re in your home folder)

~$ cd desktop

~/desktop$ mkdir desktop090709

~$desktop$ mv * desktop090709

That’s it. Your desktop becomes magically clean in a split second, and all files are stored in a folder named ‘desktopDDMMYY’. This way you’ll only ever have two icons on your desktop: The main hard drive and the latest desktop backup folder.

Since Mac OS X has the incredibly efficient Spotlight search feature, you don’t need to worry about where your files are stored. This leads me to another tip: Always name your files descriptively, so you can easily find them with the Spotlight ‘in file name’ search. For instance, if you write a travel diary entry about your day at the beach, name the file ‘travel-diary-june-2009-Santa-Monica-beach-with-kids-surfing-and-ice-cream.rtf’. It doesn’t matter that the file name is long. What matters is that it’s intuitive to find.

Anyway, next time, back to PHP.

Tags:   · · · No Comments.

PHP Absolute Path

November 5th, 2008 by Esa
Respond

For MYSQL and many other applications, it’s necessary sometimes to figure out the absolute path to a certain file.

Here’s how to find absolute path using a simple PHP script:

<?php
$path = getcwd();
echo “Your Absolute Path is: “;
echo $path;
?>

Just create the file ‘absolute.php’ in the directory that you wish to find the absolute path for, and copy-paste the above code to the file, save it and run it.

Tags: 2 Comments

How to parse XML with PHP using preg_match

November 3rd, 2008 by Esa
Respond

I was creating the Estibot.com API, and ended up with a nice standard XML output. I have php4, so it doesn’t have the nice XML functions, and I spent a good chunk of time searching for XML parsing tips on the Web, but everything I found was pretty complex and never quite got the job done. In the end, I decided to make a really simple XML parser for myself using preg_match. I know it’s not very versatile, more of a single-purpose parser, but nevertheless gets the job done with minimal coding and minimal fuss, so it works for me.

All it does, it retrieves the XML document, in this case using cURL, then does a preg_match to grab the data inside certain tags, and stores that data into a variable. Here’s the code:

<?php

//Get the XML document loaded into a variable
$ch = curl_init(”http://example.com/example.xml”);

curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$xml = curl_exec($ch);
curl_close($ch);

// match everything between <tag> and </tag> (replace ‘tag’ with whatever tag you’re interested in)

preg_match(’/<tag(.*)?>(.*)?<\/tag>/’, $xml, $match);
$result=$match[0];

echo $result;

?>

If you don’t get any output, use

print_r($match);

to display the contents of the $match array, this way you’ll see whether $match[0] or $match[1] or something else works in your particular case

Tags:   · 8 Comments

Keyword parsing: separating words by capital letters in PHP

November 3rd, 2008 by Esa
Respond

I was trying to create a simple routine for separating the keywords within a domain name based on user input of capitalized words. For example, the user might input:

MyDomainName.com

This should be parsed into the term “my domain name” based on the capital letters signifying the first letters of each word.

As usual, I Googled to see if someone had already done this, no use reinventing the wheel. However, I did not really find anything good, so I decided to tackle the problem myself. Here’s the code I came up with:

<?php

$ctype_test = preg_replace(’/[^a-zA-Z]/’, ”, $domain_name);

// the above line gets rid of everything except letters
if (!ctype_lower($ctype_test) and !ctype_upper($ctype_test)) {

// check whether there are BOTH upper and lowercase letters in the domain name

// otherwise there is no sense in continuing with the routine
for ($i=0;$i<strlen($domain_name); $i++){     // loop as many times as the string is long
$string_split[$i]=$domain_name[$i];
if (ctype_upper($string_split[$i]) AND $i>0){  // if there is an uppercase letter
$string_split[$i]=” “.$string_split[$i];         // then add a space in front of the letter
}
}

foreach($string_split as $value){     // loop through all the letters
$term=$term.$value;                // add each letter to the TERM to make up the parsed term
}

$term=strtolower($term); // finally, make the term all lowercase

?>

Maybe there’s a better way to do it, but I though this was nice & simple.

Tags:   · · · 3 Comments

PHP/MySQL headaches: Disk Full, Errcode 28

October 27th, 2008 by Esa
Respond

I was running a large MySQL query and got Errcode:28, which basically means that there is no diskspace left. It seems MySQL server used the directory /var/tmp as the directory for putting temporary stuff in. That partition did not have much space.

I found out that you can change the default MySQL temp directory by editing a file called my.cnf - how to find this file: Log on to your server. Go to /etc, then edit the file my.cnf, for instance with nano:

root@se [/etc]# nano my.cnf

now, add this line under [mysqld]:

tmpdir=/chosendirectory/mysqltemp

Hit control-X to exit, then answer “y” to whether to save. Then you have to restart the mysql server. You can achieve this also via Webhost Manager (WHM) - Restart Services - MySQL server.

Then you have to change permissions to enable mySQL to write to your new directory. From shell, you can do it like this:

chmod 777 mysqltemp

Fact is I still haven’t had success with my large query, something’s still going wrong, but at least the above steps got me through the initial problems.

Tags: No Comments.

PHP MySQL Headaches: Permissions, No Privileges

October 27th, 2008 by Esa
Respond

If, like me, you use MySQL with PHP a lot, you’re bound to bang your head against a wall quite a bit.

Here’s todays adventure.

I wanted to create a new table - well, phpMyAdmin said, “No Privileges”.

The only way I could find to grant myself privileges to create a new MySQL table was to log on to my server as root, then log on to the MySQL server as root. Here’s what that looks like (I’m assuming you know how to SSH to your server as root):

First, login to the mysql server as root:

[root@server ~]# mysql —user=root mysql

Next, grant privileges to the desired user (the username and password you use to log onto your cPanel and PhpMyAdmin)

mysql> grant all privileges on *.* to username@localhost identified by ‘password’;

Now you can go ahead and create the database.

Tags: No Comments.

How to combine two arrays into one and three arrays into one in PHP

October 27th, 2008 by Esa
Respond

I found a nice snippet for combining two arrays into one. I’d love to credit the original source, but unfortunately I can’t remember it and I can’t seem to find it in Google anymore. If you are the original author or know who they are, please let me know so I can credit accordingly.

Here is the code for combining two arrays into one:

<?php

function array_combine($arr1, $arr2) {
$out = array();

$arr1 = array_values($arr1);
$arr2 = array_values($arr2);

foreach($arr1 as $key1 => $value1) {
$out[(string)$value1] = $arr2[$key1];
}

return $out;
}

?>

That’s all well and good, but I had three arrays that I needed to combine into one. So I modified the above code to come up with this, it combines three arrays into one multidimensional array:

<?php

function double_array_combine($arr1, $arr2, $arr3) {
$out = array();

$arr1 = array_values($arr1);
$arr2 = array_values($arr2);
$arr3 = array_values($arr3);

foreach($arr1 as $key1 => $value1) {
$out[(string)$value1][0] = $arr2[$key1];
$out[(string)$value1][1] = $arr3[$key1];
}

return $out;
}?>

So that’s pretty simple. If you want to combine four arrays into one and so on, just add more arrays to the code according to the above example. So how do you use these functions? Well, let’s say you have these three arrays: $name, $address, $phone. You want to combine the three into one array. Just include the above code in your script, and then use this script to call the function:

<?php

$new_array=double_array_combine($name, $address, $phone);

print_r($new_array); // this will print out the contents of your new array

?>

Tags: No Comments.

Welcome to PHP For Beginners!

October 27th, 2008 by Esa
Respond

Just a quick welcome before we get down to business. I’m Esa, the creator of Estibot.com the domain tool suite and free domain appraisal engine. I started coding PHP just a little more than a year ago, and did end up coding a pretty popular script site, which is a testimony not to my genius but to the versatility and simplicity of the PHP programming language. If I can do it, anyone can do it!

I have spent countless hours searching the web for solutions to my PHP programming problems. I want to share stuff I’ve learned, and found, so in this blog I will publish useful code snippets, links, as well as tips&tricks aimed for the beginner level PHP programmer. Thanks for looking, hope you find something useful here.

Tags: 1 Comment