Home     Wordpress     Codex

Posts Tagged ‘php’

Learning PHP (5) – Using built-in functions

June 12th, 2009 by admin | No Comments | Filed in Learning PHP

I had promised myself that I would post every second day, but I didn’t know exactly where to go from what we have built up and I also became engaged, she said yes! So it has been crazy days.
But I’m happy, at least :-D

I am going to continue with showing how to take use of some of the built-in string fuctions. These can be used to manipulate text variables that you might receive from the $_GET and $_POST variables.

Find occurrence of text in strings
You can for example use the function strstr() or stristr() if you want a cast-insensitive matching style.

Example

$mystring = 'this websites owner is nice';
if (strstr($mystring, 'website')) {
 echo 'I found the word "website" in the string.';
}

I can use double quotes in the string because I have it enclosed in single quotes.
If I were to use single quotes it would unquote the string and generate a syntax error.

If you replace strstr with stristr in the example, it would
also give a match if $mystring contains the word ‘Website’ with an upper case W.

explode() strings
If you get a string such as “one,two,three,four,five,six” and you would rather have
it indexed in an array you can use the function explode() to achieve this.

The build-in function explode() will parse a string and split it based on the
argument you give the function. An example will follow:

$mystring = "one,two,three,four;five,six,seven";
$myarray = explode(",", $mystring);

var_dump($myarray);

The first argument to explode is the delimiting character, while the other
is the string that will be split into an array. The result of this would be:

array(6) {
[0]=>
string(3) “one”
[1]=>
string(3) “two”
[2]=>
string(5) “three”
[3]=>
string(9) “four;five”
[4]=>
string(3) “six”
[5]=>
string(5) “seven”
}

Notice that $myarray[3] contains four;five, this is due to a common
mistake.. it can be hard to overlook, so can you figure out why it does that? :-D

Anyways, you should check out the documentation and try out some
of the functions, because they are really easy to use and implement.

Good luck!

Tags: , , , , , , , ,

Learning PHP – Part two; Arrays

May 26th, 2009 by admin | 1 Comment | Filed in Learning PHP

Here’s my follow up on my PHP articles, this time I am going to talk a bit about arrays. They are so important that you should learn about them sooner than later.

What are arrays?
This quote is from wikipedia.org

An array is a systematic arrangement of objects, usually in rows and columns. Specifically, it may refer to several things.

That’s exactly what it is, it’s a variable (see previous post) containing several values (like a shelf with several compartments) that can be retrieved by a key (the number on the compartment). Array keys are per default a number, but it can also be an associative array with text strings for keys.

So make an array and fill it with data
Here is an example on how to declare an array:

<?php
$bookshelf = array(
‘old books’,
‘new books’,
‘cooking books’
);
?>

The variable name is $bookshelf, it is set to be an array(). The contents is put in between the (), but you can also declare an empty array by doing this:

$bookshelf = array();

By default, the first value will have the key 0, the second will have 1, etc.
To refer to a value within an array and echo it out to display:

<?php
$bookshelf = array(
‘old books’,
‘new books’,
‘cooking books’
);

echo $bookshelf[0];

?>

The result outputted from this script will be:

old books

By using the [ and ] signs behind a variable you are referring to it as an array, what you put between them is the key you are using. Try to change the value between them to 1 and check the result.

Adding values to a PHP array
You can make use of the array_push() function to insert more variables to a previously declared array.

<?php
$bookshelf = array(
‘old books’,
‘new books’,
‘cooking books’
);

array_push($bookshelf, ‘dvds’);

echo $bookshelf[3];

?>

You can also set a variable directly by using the key

<?php
$bookshelf = array(
‘old books’,
‘new books’,
‘cooking books’
);

$bookshelf[3] = ‘dvds’;

echo $bookshelf[3];

?>

Deleting a value from a PHP array
Several ways to this also, you can use array_pop() to unset the last value in the array.
The unset() function can be on the array value to unset it.
You can set it to null by referring to the key

array_pop($bookshelf);
unset($bookshelf[3]);
$bookshelf[3] = null;

While these are regular arrays, there are other possible ways to use this. A string variable like $name = “Espen”; in my previous article is actually an array of characters. $name[0] will refer to ‘E’, 1 will refer to ’s’ so on and so forth.

Associative Arrays in PHP
You can use keys which are not numbers in an array, those are called associative arrays.
Here is an example, I bet you understand most of the basics now, and in case NOT – drop me a comment!

$bookshelf['favourite'] = ‘Marketing 911′;
echo $bookshelf['favourite'];

In my next article you will get magic behind the array variables $_GET, $_POST and $_SERVER to finally be able to handle user input from forms and every secret of the request. Want to know when I post it? Get Learning by RSS.

Tags: , ,

Learning PHP – Part one

May 24th, 2009 by admin | 4 Comments | Filed in Learning PHP

Do you want to learn PHP?

I’ve been coding (or scripting if you want) PHP actively for myself for probably 10 years now, over the years I’ve had a lot of questions about it and have done a lot of small favours for people. I would be happy to give away some of my knowledge, so please ask if there is anything.

I am going to teach PHP from basic to advanced, I will try to keep it to one article every other day.
Subscribe to my feed if you don’t want to miss out on this chance.

Basic Introduction
What is PHP? It is a scripting language that resides on the server-side as opposed to javascript which is downloaded and ran by the client (which is called client-side).

To be able to execute PHP scripts, you need access to a webserver that runs PHP scripts – there are a lot of alternatives.
I am not going to explain them here, but I am sure it is possible to arrange something if you need a place and is into learning.
It is also possible to run an Apache server locally with PHP.

My First PHP Script
Create a file named first.php and this is the contents

<?php
echo “hello (word)”;
?>

Save this file somewhere on the webserver and try to go to the url.
It will display: hello (world)

Explanation
The first line is <?php, this tells the webserver that it is about to parse PHP scripting. You need this before every piece PHP script for it to be executed as PHP.

The second line is echo “hello (world)”;, this is actually the PHP script line.
It uses the built-in function ‘echo’ to display a string, the string needs to be contained within quotes.
And notice that the ending of the line is ;, this finishes off the statement.
If you were to forget the ; and had several lines of code the server will continue to feed the rest of the code into the echo function, which would probably not work or give really really unexpected results.

The third line is ?>, this tells the webserver that the PHP script is over.
When it reaches this tag, it will continue to output the rest of the page to the browsing user. This means that you can use PHP in between HTML to generate dynamic responses.

My Second PHP Script
Heck, since it’s the first post and the first script was so easy.. I will show you another script and teach how variables work.
I will move on to more advanced things later, so keep watching if this is way too basic for you. There will be more blood! :D

<?php
$name = “Espen”;
$age = 23;
$twice = $age * 2;
echo “My name is ” . $name . ” and my age is ” . $age . “, if I had lived twice as long I’d be ” . $twice;
?>

Explanation
The first line of PHP script is $name = ‘Espen’;.
The dollar sign ($) indicates that this is a variable, variables are used to contain dynamic information like if you want to display it at several places in your document.

The variable name is actually ‘name’, and it is set to contain anything behind the equal (=).
The string behind the equal sign is “Espen”, notice the ; ending again.
Because it is contained within quotes, PHP automatically identifies it as a string, it will not work without quotes.
I will show some examples between the difference in double and single quotes later.

The second line is $age = 23;.
As before, notice the dollar sign and also notice the ; ending.
Because age is an integer, you don’t need quotes. If you use quotes around the age like ‘23′, PHP will identify it as a string and doing calculations on it can fail.

The third line is $twice = $age * 2;
This sets the variable named $twice to contain whatever is in the variable $age and multiply it with two.
We know from before that $age is set to 23, so this will yield a result of 46. $twice now contains 46.

The fourth line is:
echo “My name is ” . $name . ” and my age is ” . $age . “, if I had lived twice as long I’d be ” . $twice;

One of the methods of combining variables into another is the usage of the period character (.) There are other and better ways to do it, but that may be to complicated for a beginner for now.
Some if you may relate this to javascript where they use + to combine variables.
So this actually feeds a lot of parts of information to the echo function to display it:
“My name is ” is the first part, the next variable will be printed right after it – so notice the white space before the last qutoe.
Then the period character is used to append the variable $name to it.
The string ” and my age is ” is appended by . again, notice white spaces before and after the string.
You probably understand the rest of it now.
Notice that any white space added that is not contained within quotes will not be displayed either.

If anything is unclear or completely wrong, feel free to drop me a comment!
More learning is coming: Subscribe to my feed.

Tags: , , , ,

HOWTO: Creating the Simplest Twitter API Client in PHP

May 21st, 2009 by admin | No Comments | Filed in Twitter

Do you run a website? Heard about the Twitter API? Try it!

I have been playing around with the Twitter API lately, all though the OpenAuth is a bit more hassle they still support the ‘old’ API for a bit longer. Twitter has not set a definitive date on when these applications will stop working but it will happen.
In the mean time, it’s a good way to learn how to play with the API without dealing with all the openauth stuff.

I have created an example function that you can use to create your own Twitter applications, it does not support or have any sense of sessions but if you intend to play, check it out! Extend it, tell me about your changes!

You need Zend for this example to work, and more specifically the Zend Json decoder part. It helps parsing the JSON information sent from Twitter.

<?php
/* Simple Twitter API Client Example utilizing Zend/Json
* http://www.cfg.no/ – Espen Holm Nilsen 20090521
*/
require_once ‘Zend/Json.php’;

function twitterJsonGet ($strUser, $strPassword, $strUrl) {
$strBasicAuth = base64_encode($strUser . ‘:’ . $strPassword);
$strRequest = “GET ” . $strUrl . “.json HTTP/1.1\nAuthorization: Basic ” . $strBasicAuth . “\nUser-Agent: PHPTwitter 1.0 (http://www.cfg.no)\nHost: twitter.com\nAccept: */*\r\n\r\n”;
$fd = fsockopen(‘twitter.com’, 80);
if (!$fd)
die(“Could not connect to Twitter”);
fputs($fd, $strRequest);
while (!feof($fd)) $buf .= fgets($fd, 1024);

$res = explode(“\r\n\r\n”, $buf);

if (!preg_match(“/^HTTP\/1\.1\s200\sOK/”, $res[0]))
return FALSE;

return Zend_Json::Decode($res[1]);
}

if ($_POST['twitteruser'] && $_POST['twitterpass']) {
$user = twitterJsonGet($_POST['twitteruser'], $_POST['twitterpass'], ‘/account/verify_credentials’);
print “You are <a href=’http://twitter.com/” . $user['screen_name'] . “‘>” . $user['screen_name'] . “</a><br>”;
print “You follow ” . $user['friends_count'] . ‘ people and have ‘ . $user['followers_count'] . ” followers.<br>”;
}

?>

<form action=’?’ method=’POST’>
Twitter username<br><input type=”text” name=”twitteruser”><br>
<br>
Twitter password<br><input type=”password” name=”twitterpass”><br>
<input type=”submit” value=”Who am I?”>
</form>

The application example runs live here: http://arpa.no/twitter.php
Since it’s Twitter specific, you should Tweet it, or retweet if you saw it in a Tweet! :D

Good luck, let me know how you do!

Tags: , ,