Banner

Sponsor

Login


Welcome Back!
Guest
Guest

Register

Lost your password?

37 users online



In Depth Tutorials [May 30, 2004]

In Depth Tutorials [May 30, 2004]

Currently viewing this thread: 1 (0 members and 1 guests)


Thread closed

Closed by Noel on August 24th, 2005 03:41 PM

Not discussion.

Page 2 out of 4
Adam

Adam

Status: Offline!

Tutorial: Auto Parse URLS

Like on vBulletin when posting, this is a script to automatically parse URL's.

We'll assume that the string is $string.

PHP:

<?
$string 
preg_replace("#(http)?(s)?(ftp)?:\/\/(.+?)#si""<a href=\"$1$2$3://$4\">$1$2$3://$4</a>"$string);
?>


What this section does is check what's before ://. It could be:
http ($1)
https ($2)
ftp ($3)
It then gets whatever is after :// and sets it to $4.
Then it echoes out everything.

PHP:

<?
$string 
preg_replace("#www\.(.+?)#si""<a href=\"http://www.$1\">[url]www.[/url]$1</a>"$string);
?>


This section is pretty self eplanitory. It looks for [URL]www.[/URL] and sets whatever is after that to $1. It then echoes out [URL]http://www.[/URL]$1

PHP:

<?
$string 
preg_replace("#\[nolink\](.+?)\[/nolink\]#si""$1"$string);
?>


This one is also pretty self-explanitory. It's if you don't want to parse the URL as a link. You simply put [NOLINK] [/NOLINK] around the URL that you don't want to parse, and it won't parse it for you. Instead it just echoes out the URL you typed.

I hope that helped someone with something. Smile
By the way, for those of you who don't know, I used Regular Expressions in the preg_replace() functions. Smile

By Byran

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Last edited by Noel, May 7th, 2005 10:11 PM (Edited 1 times)

Adam

Adam

Status: Offline!

Tutorial: Stock Ripper

I have written a very small PHP script that some of you guys might find useful.
Feel free to use it change it etc as you want, and if you improve it, make it smaller, faster etc please let me know!!

Basically, I have stock in different companies, so keeping an eye on the prices interests me. I mainly invest in one company, so I am only interested in that one stock, so this is why it is written like this.

If I want to see how all my stocks are performing I just go to a site that has portfolio management Wink Thats not why I wrote this...

I know the stock's hard-coded, but hey, I ain't gonna be changing all my stock, so it stays for me Shocked

I'll step through it in a tutorial style, so that you can all understand now it works!

Code:


<?
// Define the symbol that you are interested in here...
$symbol = "LLOY.L" ;

$open = fopen("http://quote.yahoo.com/d/quotes.csv?s=$symbol&f=sl1d1t1c1ohgv&e=.csv", "r");
$read = fread($open, 2000);
fclose($open);


OK this reads the information from Yahoo! finance, for the given ticker. I found this URL on the web somewhere, so just used it! It stores it in the variable $read.

Code:


$read = str_replace("\"", "", $read);
$read = explode(",", $read);


This next bit remove's all the double quote characters ("), and splits the read in information into comma seperated chunks..

Code:

[i]e.g.[/i]
$temp = "hello this is an example" ;
$temp = explode(" ",$temp);


$temp will now be an array which looks like this...
$temp[0] = hello
$temp[1] = this
$temp[2] = is
$temp[3] = an
$temp[4] = example

OK now we seperated out the data, we can do stuff with it.
First of all, check that the read of the data produced some actual data that we can be playing with. Simple check to do this is to see if there is anything in data position 1. If there was no data read in this would be empty.

Code:


IF ($read[1] == 0)
{
echo ("The symbol you provided (\"$symbol\") doesn't exist.<BR>");
}
ELSE
{
?>


Here we have spewed out an error message if there isn't any data to be delayed. If there is, we have to show it. Close the PHP code block as there is going to be some HTML formatting.

Code:


<div align="center">
<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=0>
<TR>
<TD width=150><div align="center"><b>SYMBOL </b></div></TD>
<TD width=150><div align="center"><b>PRICE </b></div></TD>
<TD width=150><div align="center"><b>CHANGE </b></div></TD>
<TD width=150><div align="center"><b>STARTED</b></div></TD>
</TR>
<TR>
<TD><div align="center"><? echo ("$read[0]"); ?></div></TD>
<TD><div align="center"><? echo ("$read[1]"); ?></div></TD>
<TD><div align="center"><? echo ("$read[4]"); ?></div></TD>
<TD><div align="center"><? echo ("$read[5]"); ?></div></TD>
</TABLE>
</div>


This shows the information that I am interested in, i.e. The symbol name, the price, what price it started trading at, and the change in price. See how we're using the $read variable here, we can reference bits of data, by referencing it with the [nPos] operator.

Finally, remember to finish off by closing the else bracket!!

Code:


<?}?>


OK other information that you can use in this order will be...
Use the number to get it i.e. 0 = Symbol, so use $read[0] to get the symbol!

    [*]0 = Ticker Symbol [*]1 = Price of Last Trade [*]2 = Date of Last Trade [*]3 = Time of Last Trade [*]4 = Change (points) [*]5 = Opening Price [*]6 = Days High [*]7 = Days Low [*]8 = Volume of Stock

Hope you found this interesting,
Steve

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Adam

Adam

Status: Offline!

Tutorial: Variable Scope

Just a few tutorials to help people, and to help make it so the same questions aren't asked over and over again.

Variable Scope

In PHP, there are 4 scopes - normal, variable, global, and superglobal.

When you set a variable, it is automatically put in a certian scope. Think of scopes as the ends of a telescope - when looking through it, you can see some things, but not everything.

Say you set a variable in the middle of your script; ie:

PHP:

<?php

# some code
$currentSong 'Mest - Jaded.mp3';
print 
$currentSong;
# more code

?>

Variable $currentSong is set in the normal scope. This means its generally accessable everywhere except inside functions and classes. For example, say you have a function that stores our $currentSong.

PHP:

<?php

function storeCurrentSong() {
     if(isset(
$currentSong)) {
          
mysql_query("insert into 'storedSongs' set song = $currentSong");
     else {
          print 
'variable $currentSong is not set!';
     }
}

?>

If you were to run this function (assuming database was connecting and table structure was made) it would tell you 'variable $currentSong is not set!'.

This is because functions have a different variable scope then the normal scope. Variables from outside the function (ie from the rest of the script) aren't accessable by default. Also, variables set in functions aren't accessable outside of the functions. That means if i do

PHP:

<?php

function set() {
    
$v 'set';
}

set();
print 
$v;
?>

it will return Notice: Undefined variable: v in e:\server\test.php on line 8 because it isn't accessable by default. Also, variables set inside functions are NOT accessable by default inside other functions.

So, how do we solve this? We need to put the variable we need into the global scope. Php has a construct called 'global' (hah - its simple!) that will do this for you. For example, we can add this line to our storeCurrentSong function to global our variable.

PHP:

<?php

function storeCurrentSong() {
     global 
$currentSong;
     if(isset(
$currentSong)) {
          
mysql_query("insert into 'storedSongs' set song = $currentSong");
     else {
          print 
'variable $currentSong is not set!';
     }
}

?>

Thats it - we moved the variable into the global scope, which is the third php scope. A note about the global scope, as pointed out by Jerome:

Quote:


Just a little note Ares,

you run into problems modifying global variables (in some situations)

so its safer to use $GLOBALS['varname'] if you plan to modify the variable.

-Jerome

Finally, theres the superglobal scope. PHP sets these automatically - you dont have to do anything. They are actually superglobal arrays that PHP sets. They can be used ANYWHERE in your script without any previous globaling.

These are the superglobal variables.

Quote:


$GLOBALS
Contains a reference to every variable which is currently available within the global scope of the script. The keys of this array are the names of the global variables. $GLOBALS has existed since PHP 3.

$_SERVER
Variables set by the web server or otherwise directly related to the execution environment of the current script. Analogous to the old $HTTP_SERVER_VARS array (which is still available, but deprecated).

$_GET
Variables provided to the script via HTTP GET. Analogous to the old $HTTP_GET_VARS array (which is still available, but deprecated).

$_POST
Variables provided to the script via HTTP POST. Analogous to the old $HTTP_POST_VARS array (which is still available, but deprecated).

$_COOKIE
Variables provided to the script via HTTP cookies. Analogous to the old $HTTP_COOKIE_VARS array (which is still available, but deprecated).

$_FILES
Variables provided to the script via HTTP post file uploads. Analogous to the old $HTTP_POST_FILES array (which is still available, but deprecated). See POST method uploads for more information.

$_ENV
Variables provided to the script via the environment. Analogous to the old $HTTP_ENV_VARS array (which is still available, but deprecated).

$_REQUEST
Variables provided to the script via any user input mechanism, and which therefore cannot be trusted. The presence and order of variable inclusion in this array is defined according to the variables_order configuration directive. This array has no direct analogue in versions of PHP prior to 4.1.0. See also import_request_variables().

Note: When running on the command line , this will not include the argv and argc entries; these are present in the $_SERVER array.

$_SESSION
Variables which are currently registered to a script's session. Analogous to the old $HTTP_SESSION_VARS array (which is still available, but deprecated). See the Session handling functions section for more information.

Just a few notes - $_GET is from the query string (ie page.php?var=1) and $_POST is from forms with method set to post.

You should never have to use $_REQUEST - use alternatives let $_GET/POST/SESSION/COOKIE/ETC - its much better coding practice.

These are the variables in the $_SERVER superglobal array - your values for the vars may be different, this is from my machine.

Code:

Array
(
[COMSPEC] => C:\\WINDOWS\\COMMAND.COM
[DOCUMENT_ROOT] => e:/server
[HTTP_ACCEPT] => */*
[HTTP_ACCEPT_ENCODING] => gzip, deflate
[HTTP_ACCEPT_LANGUAGE] => en-us
[HTTP_CONNECTION] => Keep-Alive
[HTTP_COOKIE] => lastview=1055257218
[HTTP_HOST] => localhost
[HTTP_USER_AGENT] => Mozilla/4.0 (compatible; MSIE 6.0; Windows 98)
[PATH] => C:\\WINDOWS;C:\\WINDOWS\\COMMAND
[REDIRECT_STATUS] => 200
[REDIRECT_URL] => /test.php
[REMOTE_ADDR] => 127.0.0.1
[REMOTE_PORT] => 1053
[SCRIPT_FILENAME] => d:/php/php.exe
[SERVER_ADDR] => 127.0.0.1
[SERVER_ADMIN] => server@aesthetic-theory.com
[SERVER_NAME] => localhost
[SERVER_PORT] => 80
[SERVER_SIGNATURE] => <ADDRESS>Apache/1.3.27 Server at localhost Port 80</ADDRESS>

[SERVER_SOFTWARE] => Apache/1.3.27 (Win32)
[WINDIR] => C:\\WINDOWS
[GATEWAY_INTERFACE] => CGI/1.1
[SERVER_PROTOCOL] => HTTP/1.1
[REQUEST_METHOD] => GET
[QUERY_STRING] =>
[REQUEST_URI] => /test.php
[SCRIPT_NAME] => /php/php.exe
[PATH_INFO] => /test.php
[PATH_TRANSLATED] => e:\\server\\test.php
[PHP_SELF] => /test.php
[argv] => Array

(
)

[argc] => 0
)

To access "INSERT_SOMETHING_HERE" you would do $_SERVER['INSERT_SOMETHING_HERE'] in your script.

Variable Variables
You can think of Variable Variables as a variable set with the name of a different variable. For example, say you have a variable with your name.

PHP:

<?php
$myName 
'Phil';
?>


Now, for some reason, you want to set a variable with the value of $myName as the name of it. Doing this is using variable variables. You do it like this

PHP:

<?php
$myName 
'Phil';
$
$myName 'This is a variable variable that is named the value of myName! WOW!';
?>


Then you could simply do something like

PHP:

<?php
$myName 
'Phil';
$
$myName 'This is a variable variable that is named the value of myName! WOW!';
print 
$Phil;
?>

Sure, this may seem completely useless, but in many advanced scripts it has its uses.

Example from php.net

PHP:

<?php 

$required 
= array("username""password"); 

for  (
$i 0$i count($required); $i++) 
 { 
    if (($
$required[$i] == "") || (!$$required[$i])) 
    { 
     echo (
"Umm... we need $$required[$i]"); 
    } 

  
 exit(); 

?>

And finally...

Sessions
Sessions are a way to store data from one php page to the next without necessarily using cookies. I'm going to use superglobals (Smile). Using them is the newer, preffered, and simpler way of doing them.

Note - Sessions are kind of like cookies in a few way. You need to start the session on EVERY page and put it above all html/output to browser or you will get a header already sent error.

The easiest way to do this is with a simple example scripts.

PHP:

<?php
# sessions.php

# lets start the session
session_start();

# lets make a simple page view counter

# have we ever viewed this page before?
if (!isset($_SESSION['count'])) {
    
# we haven't, so lets set a variable called count and start it at 0
    
$_SESSION['count'] = 0;
} else {
    
# we have! lets move the count up one
    
$_SESSION['count']++;
}
?>


Go to that script and reload it a few times.

And thats all there is to the basics of sessions - we started a sessions with session_start, created the variable, and used it on future hits. For more on sessions, check out the session page at php.net.

By Phil

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Last edited by Noel, May 7th, 2005 10:26 PM (Edited 1 times)

Adam

Adam

Status: Offline!

Tutorial: index.php?Page=news

Hopefully, this will cut down on the incredible number of requests we get for this. First, a couple of key terms: 'query string' is the ?page=blah part in 'page.php?page=blah'. page=blah is called a variable=value pair. You can seperate them by doing 'page.php?var1=bob&var2=tom'.

Now, something that will cause many of you problems is register_globals. If its off (which it is by default in the last few php distrubs), using $queryStringVar when going to page.php?queryStringVar=tom wont print out anything. In fact, chances are it will give you an unset / undefined variable error... whcih isnt good! But we have a soultion.

Remember the variable=value pairs?

We can get things from the query string through the $_GET array, no matter what. So since $queryStringVar doesnt work, we have to get it through $_GET['queryStringVar'].

The general idea is this:
If you go to 'page.php?color=red&money=37&var1337=sure', then we DONT get it by this:

PHP:

<?php

print $color '<br />';
print 
$money '<br />';
print 
$var1337 '<br />';

?>


Instead, we use the $_GET array!

PHP:

<?php

print $_GET['color'] . '<br />';
print 
$_GET['money'] . '<br />';
print 
$_GET['var1337'] . '<br />';

?>

This works, and is proper coding. HAPPY DAY.

Now, we have the all to oft template/ include problem:

Things that DONT work"

PHP:

<?php

if($page == 'one') {
    include 
'page1.php';
}

?>


AND

PHP:

<?php

include $page;

?>

Instead, were going to use the switch statement and the $_GET array!

PHP:

<?php

switch( $_GET['page'] ) {
    case 
'news' 
        include 
'news.php';
        break;
    case 
'portfolio' :
        include 
'portfolio.php';
        break;
    case 
'bush' :
        include 
'go_to_war_with_iraq_for_no_reason.php';
        break;
    case 
'me' :
        print 
'war sucks... GO ANTI WAR ME';
    default:
        include 
'news.php';
        break;
}

?>

Isnt that easy to read? It is, isnt it. Thats why you should use it. Feel free to ask questions...here.

new as of june 15:

Now, you may ask - what about index.php?news / index.php?portfolio means of navigation? This actually isn't that hard. You see, when you go to index.php?variable, variable is initialized but not given a value. That means you can do this:

Way one, if you intend to have other query string variables besides just ?page

PHP:

<?php

if( isset($_GET['news']) and !defined('PAGE_LOADED') ) {
     include 
'pages/news.php';
     
define ('PAGE_LOADED''');
}
if( isset(
$_GET['portfolio']) and !defined('PAGE_LOADED') ) {
     include 
'pages/portfolio.php';
     
define ('PAGE_LOADED''');
}
if( isset(
$_GET['forum']) and !defined('PAGE_LOADED') ) {
     
define ('PAGE_LOADED''');
     
header("Location: forum.php");
}
?>

And if you don't intend to have other query string variables:

PHP:

<?php

if(isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] == 'news') {
     include 
'pages/news.php';
}
if(isset(
$_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] == 'portfolio') {
     include 
'pages/portfolio.php';
}
if(isset(
$_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] == 'forum') {
     
header("Location: forum.php");
}
?>

And thats how you do index.php?news

links:
switch control structure
Register globals

By Phil

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Last edited by Noel, May 7th, 2005 10:27 PM (Edited 1 times)

Adam

Adam

Status: Offline!

Tutorial: BBCode

been fondling around with regex and here's what i came up with. feel free to copy it. It's quite easy to add more tags.

PHP:

<?php

$str 
'[B]How cool this is bold[/B] but this is not Sad.  However this is [I]Italic..yay!![/I]';
$bold '/(\[B\])(.+)(\[\/B\])/';
$italic '/(\[I\])(.+)(\[\/I\])/';

$str preg_replace($bold,'<b>\\2</b>',$str);
$str preg_replace($italic,'<i>\\2</i>',$str);
print 
$str;

?>

if you want to add more, simply copy $bold or $italic and rename it. let's say i want to center certain text. I copy $bold and replace B with CENTER

PHP:

<?php

$center 
'/(\[CENTER\])(.+)(\[\/CENTER\])/';

?>

then you copy one of the replace string, see the <b>\\2</b> ??? just change the tag to center, so for centering, you'll have <center>\\2</center>

now you have

PHP:

<?php

$str 
preg_replace($cemter,'<center>\\2</center>',$str);

?>

cool eh? just keep doing it for every tags you want. I've worked on one for [IMG] [URL] tags but it's not easy to modify. The only tags i could think of is. <p> <center> <i> <b> <marquee> <blink> <small> <large>. So on...

By CDude

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Last edited by Noel, May 7th, 2005 10:28 PM (Edited 1 times)

Adam

Adam

Status: Offline!

Tutorial: Alternating Row Colors

In order to do alternating Row Colors, all you need to do is have a Counter variable and decided whether it is odd or even. Then if is odd or even, change a color variable.

I'll start off with a general query, 'SELECT * FROM users'. Note that the fields used in this examples will NOT match up to yours unless you have the exact same table.

PHP:

<?php

$sql 
'SELECT * FROM users';
$Result mysql_query($sql) or die(mysql_error());

$K 1;  //Initaize the counter variable.
while($Record mysql_fetch_array($result)){
 
$Color $K 1  'color1' 'color2'
 
echo $Color '<br>';
 
$K++;
}

?>

All leave it up to you to figure out how to implement the $Color variable.

Edit: Deleted CDudes post and put the faster method in this post. Thanks CDude!

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Last edited by Adam, July 30th, 2003 02:59 AM (Edited 1 times)

Adam

Adam

Status: Offline!

Tutorial: Intorduction to GD

Images with PHP can be daunting at first - Look at the manual; theres a TON of functions. Where to start?

It's actually very easy. The first thing to do is to check if you have gd and if you CAN create images.

Run this script:

PHP:


<?php
imagecreate
(1,1);
?>

If you get fatal errors, it doesn't work. Obviously. If it isn't working you need to check your gd extension, make sure its loaded. PHP's phpinfo() function may be helpful here. I was able to install it on PHP5 in all of 5 seconds; I haven't been able to get it with PHP4. Someone who knows more about configuring servers then I do can probally do it, but this tutorial WILL work for PHP4 if gd is enabled on your server.

The hardest part of using images is knowing what functions to use. The PHP manual (link) will come in handy.

In this tutorial, were going to do a case study on how to make those anti-robotic registration forums are using these days. If your not familiar, its a image with a randomly generated string inside it.

Lets get to it then!

First, we need to define some constants that we'll use during the script. We define them as constants so we can easily modfiy at a later time without changing the actual script - this is good coding practice and has many uses.

PHP:

<?php

    define
('X_SIZE'125);
    
define('Y_SIZE'50);
    
define('BORDER_THICKNESS'5);
    
define('FONT''arialbd.ttf');
    
define('FONTSIZE'15);
    
define('LEGNTH'8);

?>

    [*]X_SIZE is going to be the horizontel length of our image in pixels. [*]Y_SIZE is going to be the vertical length of our image in pixels. [*]BORDER_THICKNESS is going to be the thickness of the "frame" of our image in pixels. For those of you that care about boxmodels, the frame is put on the INSIDE of the box defined by X and Y sizes, not the outside. [*]FONT is the path and filename of the font we'll use. I stuck 'arialbd.ttf' (arial bold) in the same directory as my script, but you could have it anywhere. Make sure the path is correct! (Examples = 'D:\fonts\arialbd.ttf', 'misc/fonts/arialbd.ttf'). [*]FONTSIZE is the size of our font! [*]LEGNTH is the legnth of our random string in characters.

If you change these values, it may take expirementation to make sure everything fits.

The next step is to create a image, although realisticly its like making a new canvas in photoshop. PHP function imagecreate takes 2 arguments - the first one is X-Axis size and the second one Y-Axis. We'll use this:

PHP:

<?php

 $image 
imagecreate(X_SIZE,Y_SIZE) or die ('Cannot Initialize new GD image stream');

?>

Now we need to let PHP know what colors we'll be using. You'll need to know the Red, Green, and Blue values for each color we'll use. Photoshop does this quite nicely, and this is a online sheet (link)

The first color we allocate (let PHP know about) will be set as the image background color and any colors after have no special importance.

Nows as good as time as any to tell the theory of how I will be making the frame. Theres no frame() command, I'm afraid. Say you a 4'x4' piece of red plywood, and on top of that, in the middle, you put a 2'x2' piece of brown plywood. Now, the brown plywood has a 1' red border around it . Thats how were going to make our border/frame - put a smaller box (colored our desired BG) on top of the bigger bpx (colored border color).

Back to the colors, we'll use a function called imageColorAllocate. It takes 4 arguments - image handle, red, green, blue.

PHP:

<?php

    $grey 
imageColorAllocate($image,170,170,170); # background - its actually going to be our border!
    
$lightBlue imageColorAllocate($image,102,153,255); # this will be our real background
    
$black imageColorAllocate($image,0,0,0); # text color

?>

Now lets make our border. We'll draw a rectangle on top of our grey colored image. We use this function - imageFilledRectangle. It takes these arguments - image handle, start X position, start Y position, end X pos, end Y pos, color.

Assuming border thickness of x we should start it x pixels away from the top and x pixels away from the left. That indicates our first x/y arguments will be x. The end positions our reverse that - kind of. The code explains better then words, IMO.

PHP:

<?php

imageFilledRectangle
($imageBORDER_THICKNESSBORDER_THICKNESS, (X_SIZE-BORDER_THICKNESS), (Y_SIZE-BORDER_THICKNESS), $lightBlue);

?>

Well, now we need our random string. The code we'll use for this gets a random number (note that the high integer I used in rand() is NOT a random number; its the highest some operating systems can go (see php.net comments)) and divides the current time by the number we just generated. We then MD5 it to get a mix of letters and numbers and finish off by using substr to get it to the desired legnth.

PHP:

<?php

$word 
substr(md5((time()/rand(1,2147483647))), 0LEGNTH);

?>


Now, to make it easier on visitors that get confused by 'o's and zeros, we'll make everything capitalized and replace all 'o's with 0s. Then you can just note to the user that there are no 'o's; only zeros.

PHP:

<?php
$w 
str_replace('O'0strtoupper($word));
?>

Now, we want to put our random string in the middle of our image. I stole this from php.net; no need to reinvent the wheel. It does some simple arithmetic with the image size and the legnth of the string (in pixels - takes into account the font and fontsize) and decides where we should start putting the text.

PHP:

<?php
    $text_bbox 
ImageTTFBBox(FONTSIZE0FONT$w);
    
$text_pos_x = (X_SIZE - ($text_bbox[2] - $text_bbox[0])) / 2;
    
$text_pos_y = (Y_SIZE - ($text_bbox[1] - $text_bbox[7])) / 2;
    
$text_pos_y -= $text_bbox[7];

?>

Now, lets actually add the text to the image. We'll use the function imageTTFText which takes these arguments: image handle, font size, angle of rotation (0 for normal ltr text), start position x-axis, start position y-axis, color (which you allocated to a var), font, and text. Remember that we previous got our start positions into $text_pos_x and $text_pos_y.

PHP:

<?php

imageTTFText
($imageFONTSIZE0$text_pos_x$text_pos_y$blackFONT$w);
?>

Now lets actually send the image to the browser:

PHP:

<?php
imagePNG
($image);
?>


Note that if you wanted to save the image (although it wont show it) you could do something like

PHP:

<?php
imagePNG
($image'randImage'.$w.'.png');
?>


That will save it as randImageRANDOMSTRINGHERE.png in the same directory as the script.

Now lets free up the memory from creating this operation.

PHP:

<?php

imageDestroy
($image);

?>

Our final script may look like this:

PHP:


<?php

    define
('X_SIZE'125);
    
define('Y_SIZE'50);
    
define('BORDER_THICKNESS'5);
    
define('FONT''arialbd.ttf');
    
define('FONTSIZE'15);
    
define('LEGNTH'8);
    
    
# let the browser know its getting a image, not a text file or something
    
header("Content-type: image/png");
    
    
# lets make the image
    # First Argument is X Axis, Second is Y
    
$image imagecreate(X_SIZE,Y_SIZE) or die ('Cannot Initialize new GD image stream');
    
    
# now we have to specify the colors we'll use
    # the first color is background color (automatically)
    
$grey imageColorAllocate($image,170,170,170); # background - its actually going to be our border!
    
$lightBlue imageColorAllocate($image,102,153,255);
    
$black imageColorAllocate($image,0,0,0);
    
    
# int ImageFilledRectangle (int im, int x1, int y1, int x2, int y2, int col)     
    
imageFilledRectangle($imageBORDER_THICKNESSBORDER_THICKNESS, (X_SIZE-BORDER_THICKNESS), (Y_SIZE-BORDER_THICKNESS), $lightBlue);
    
    
# word
    
    
$word substr(md5((time()/rand(1,2147483647))), 0LEGNTH);
    
    
# thats nice, but people get confused with 0 and O and o so0O
    
    
$w str_replace('O'0strtoupper($word));
    
    
# Now this is a bit of code I stole from the PHP manual, but it works Smile
    
    
$text_bbox ImageTTFBBox(FONTSIZE0FONT$w);
    
$text_pos_x = (X_SIZE - ($text_bbox[2] - $text_bbox[0])) / 2;
    
$text_pos_y = (Y_SIZE - ($text_bbox[1] - $text_bbox[7])) / 2;
    
$text_pos_y -= $text_bbox[7];
    
    
# ImageTTFText (int im, int size, int angle, int x, int y, int col, string fontfile, string text) 
    
imageTTFText($imageFONTSIZE0$text_pos_x$text_pos_y$blackFONT$w);
    
    
# send the image
    
imagePNG($image);
    
# free memory
    
imageDestroy($image);
?>

And we could use it like

Code:


<html>
<head>
<title> random words on image </title>
</head>
<body>
<img src="SCRIPT.php" />
<p> All 'O's and zeros are ZEROS. All leters are capitalized.</p>
</body>
</html>

One more note - if your trying to steal fonts out of your system-fonts category, I had to go to edit->copy, not right-click. ALso, if the fotns were outside of my system font dir, they were invisible no matter what, but they were still where I pasted them to (i could check by pasting again and getting 'Do you want to overwrite me?')

Thats it folks.

Read the stickies or die.

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Adam

Adam

Status: Offline!

Tutorial: Working with Files

Files are a great way of storing data, and the best part about them is that they do not require any external extensions or other programs. In PHP dealing

with files is very easy. There are a vew basic functions, fopen, fclose, fread, and fwrite. Now that you are familarized with all basic functions, let

consult the php manul for an explantion of each:

fopen: int fopen ( string filename, string mode [, int use_include_path [, resource zcontext]] )

fopen() binds a named resource, specified by filename, to a stream. If filename is of the form "scheme://...", it is assumed to be a URL and PHP will search

for a protocol handler (also known as a wrapper) for that scheme. If no wrappers for that protocol are registered, PHP will emit a notice to help you track

potential problems in your script and then continue as though filename specifies a regular file.

If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to

ensure that the file access permissions allow this access. If you have enabled safe_mode, or open_basedir further restrictions may apply.

If PHP has decided that filename specifies a registered protocol, and that protocol is registered as a network URL, PHP will check to make sure that

allow_url_fopen is enabled. If it is switched off, PHP will emit a warning and the fopen call will fail.

mode specifies the type of access you require to the stream. It may be any of the following:

'r' - Open for reading only; place the file pointer at the beginning of the file.
'r+' - Open for reading and writing; place the file pointer at the beginning of the file.
'w' - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to

create it.
'w+' - Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist,

attempt to create it.
'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

fclose: bool fclose ( int fp )

The file pointed to by fp is closed.

Returns TRUE on success or FALSE on failure.

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().

fread: string fread ( int fp, int length )

fread() reads up to length bytes from the file pointer referenced by fp. Reading stops when length bytes have been read or EOF (end of file) reached,

whichever comes first.

fwriteint fwrite ( int fp, string string [, int length] )

fwrite() writes the contents of string to the file stream pointed to by fp. If the length argument is given, writing will stop after length bytes have been

written or the end of string is reached, whichever comes first.

fwrite() returns the number of bytes written, or FALSE on error.

Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.

When you are working with files, you nee
That should have answered any questions you might have had on them. One of the most basic file operation is a simple counter file. Think about what a

counter program does. You need to

    [*]Open A File [*]Read File [*]Output the hits [*]Add 1 to the number of hits [*]Write the data into the file [*]Close the file

Simple enough? Check out the code:

PHP:


<?
//counter.php
$File 'hits.txt';
$fp fopen($File'w+');
$Hits fread($fpfilesize($File));
echo 
$Hits;
$Hits++:
fwrite($fp$Hits);
fclose($fp);
?>

Note that filesize returns the size of the file in bytes so we can use that to tell fread() how far to read to.

Now you know how to store one single peice of information in a file and manipulate it. Lets say you have a file that looks like this:

Code:


Adman||Mod||1337||PHP<--NEXT-->
CDude||Moderator||2342||Programming<--NEXT-->
Epyon||Mod||23||PHP<--NEXT-->

Now you want to know what we are going to with it. This is like a flat file datbase. Each entry has 4 colums and colums are seperated by || and entries are

seperated by <--NEXT--> So we have a format like this:

Code:


Name||Status||Posts||Hobby

We have 3 entries one for me, CDude and Epyon. Each one holds the apporiate data on each person. In order to fully manipulate this example you need to have

a understanding of arrays and loops. I'm not going to go into that right now. So in order to get the data we have to first:

    [*]Open A File [*]Read File [*]Get Each Entry [*]Get Each Colum [*]Output

Simple enough? It is if you think about it =colgate. I'll give you the code first and you can look at the code and try to figure it out and if you can't you

can read the review.

PHP:


<?php
$fp 
fopen('php.txt','r');
$Contents fread($fpfilesize('php.txt'));
fclose($fp);

$Data explode('<--NEXT-->',$Contents);

foreach(
$Data as $Val){
    
$Info explode('||',$Val);
    if(
sizeof($Info) > ){
        echo 
'<p>';
        echo 
'Name : ' $Info[0] . '<br \>';
        echo 
'Status : ' $Info[1] . '<br \>';
        echo 
'Posts : ' $Info[2] . '<br \>';
        echo 
'Hobby : ' $Info[3] . '<br \>';
        echo 
'</p>';
    }
}
?>

So the first we read the whole file in a string with all the seperators in that string, so we have the first step done. Now we need to explode the string

according to what seperates an entry. In this example <--NEXT--> seperates entries. So we explode it. Explode returns an array. You need to understand

what it looks like. This is what a print_r would return:

Code:


Array
(
[0] => Adman||Mod||1337||PHP
[1] => CDude||Moderator||2342||Programming
[2] => Epyon||Mod||23||PHP
[3] =>
)

Now we have to loop through that array. I find that a foreach array is the simplest way to do--and to understand. Foreach element in the array use it as

$Val and apply this code to it. So we loop through $Data and each element will be called $Val. Now each $Val is an entry in the file. Remember each entry

has colum seperated by || so we want to explode $Val using that. But there is a minor problem. At the last line of the file there is a <--NEXT--> which

would leave us with an empty array, so we need to check that. Then if we have a full array we can display the data. Again we have an array that comes from

explode with looks like:

Code:


Array
(
[0] => Adman
[1] => Mod
[2] => 1337
[3] => PHP
)

Now we simply echo out that data.

I hope this tutorial helped you out alot. This should give you a baisc understanding of file and how to work with them.

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Adam

Adam

Status: Offline!

Tutorial: Random String

This tutorial will show you to generate a compelelty random string. The main part of this tutorial is the chr() function. It will return a character based on the give input number. All we have to do is feed it a random number and x amount of times.

PHP:


<?php

$Length 
5//length of string
$Start 65;  //Where to start from on ascii table
$End 90;   //where to end on the table

for($K 0$K $Length$K++){
    
$Str .= chr(round(rand($Start$End)));
}

echo 
$Str;

?>

Consult http://www.asciitable.com for ascii values to customize the string.

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Adam

Adam

Status: Offline!

Tutorial: Image Counter

Here is a tutorial that will show you to create a graphical image counter. In this tutorial I will leave it up to you how to accquire the $Hits variable. The key concecpt is to display an image for each character in the number. You accomplish this via substr() which returns a character or characters in a string. So if we have a number that is 10 digits long, we have a loop that will go through 10 times--a for loop. Then in the loop, each time through the loop can be considered a different character. So we tell substr() to start at that character and read the one after it.

PHP: