<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Webcodez - The database of web programming tutorials &#187; functions</title>
	<atom:link href="http://www.webcodez.net/tag/functions/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.webcodez.net</link>
	<description>Archive of tutorials on php,mysql,Javascript,html,css and other coding languages as well as code-snippets.</description>
	<lastBuildDate>Tue, 18 May 2010 16:43:49 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Creating a simple Blog System &#8211; Part 1</title>
		<link>http://www.webcodez.net/php-mysql/creating-a-simple-blog-system-part-1/</link>
		<comments>http://www.webcodez.net/php-mysql/creating-a-simple-blog-system-part-1/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 18:56:44 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[Blog]]></category>
		<category><![CDATA[CMS]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[mysql_connect]]></category>
		<category><![CDATA[mysql_select_db]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[project]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=435</guid>
		<description><![CDATA[Part 1 – Overview of Functions, Database &#38; Files
Overview
In this tutorial we’ll be creating a very simple blog system. We won’t be using OOP yet in this tutorial. For creating a Blog using OOP in PHP, another more advanced tutorial will be written and posted as well. The same goes for creating a more advance [...]]]></description>
			<content:encoded><![CDATA[<h2>Part 1 – Overview of Functions, Database &amp; Files</h2>
<p><h3>Overview</h3>
<p>In this tutorial we’ll be creating a very simple blog system. We won’t be using OOP yet in this tutorial. For creating a Blog using OOP in PHP, another more advanced tutorial will be written and posted as well. The same goes for creating a more advance CMS. However in this tutorial will just be creating a simple Blog system with php functions. Functions will be created for:</p>
<ul>
<li>Connecting to Host &amp; DB</li>
<li>Adding posts</li>
<li>Deleting posts</li>
<li>Adding replies</li>
<li>Deleting replies</li>
<li>Creating categories</li>
<li>Retrieving &amp; Displaying Posts</li>
<li>Add user</li>
<li>Edit user profile</li>
<li>Display user profile</li>
<li>Search</li>
</ul>
<p>Also a simple 2 rows div layout will be created with a side-menu and main content div. </p>
<p><h3>Database</h3>
<p>Let’s start with creating the database for our simple blog. We’ll call it ‘simple_blog’. However you can call it anything you like as long as you set it correctly in the script later on. Now let’s create the tables inside this database.</p>
<p><strong>Table: posts</strong></p>
<p>The fields that need to be created:</p>
<p>[TABLE=6]</p>
<p><strong>SQL:</strong></p>
<pre name="code" class="php:nogutter">
CREATE TABLE IF NOT EXISTS `posts` (
  `id` int(250) NOT NULL AUTO_INCREMENT,
  `title` varchar(50) NOT NULL,
  `author` int(250) NOT NULL,
  `message` longtext NOT NULL,
  `timestamp` int(250) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
</pre>
<p><strong>Table: replies</strong></p>
<p>[TABLE=9]</p>
<pre name="code" class="php:nogutter">
CREATE TABLE IF NOT EXISTS `replies` (
  `id` int(250) NOT NULL AUTO_INCREMENT,
  `postid` int(250) NOT NULL,
  `author` int(250) NOT NULL,
  `message` mediumtext NOT NULL,
  `timestamp` int(250) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
</pre>
<p><strong>Table: categories</strong></p>
<p>[TABLE=10]</p>
<pre name="code" class="php:nogutter">
CREATE TABLE IF NOT EXISTS `categories` (
  `id` int(250) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
</pre>
<p><strong>Table: members</strong></p>
<p>[TABLE=11]</p>
<pre name="code" class="php:nogutter">
CREATE TABLE IF NOT EXISTS `members` (
  `id` int(250) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  `email` varchar(250) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
</pre>
<p><h3>Files</h3>
<p>Now we’ve created our database, so let’s start with an overview of the files we’ll be creating now.</p>
<ul>
<li>functions.php</li>
<li>config.php</li>
<li>profile.php</li>
<li>index.php</li>
<li>post.php</li>
<li>	includes/header.php</li>
<li>	includes/footer.php</li>
<li>	includes/sidebar.php</li>
<li>admin/index.php</li>
<li>admin/functions.php</li>
</ul>
<p> </p>
<p>Let’s start with creating our function to connect  to the database we just made.</p>
<p><strong>File: functions.php</strong></p>
<pre name="code" class="php:nogutter">
&lt;?php

function connect($connection) {

  $host = $connection[‘host’];
  $user = $connection[‘user’];
  $pass = $connection[‘pass’];
  $db    = $connection[‘db’];
  $conn =  mysql_connect($host, $user, $pass);

  If(!$conn)
    die(“Couldn’t connect to host.”);

  $db = mysql_select_db($db);

  If(!$db)
     die(“Couldn’t connect to database.”);

}

?&gt;
</pre>
<p>Allright so first you see we set an argrument variable ‘$connection’ for the function. This variable should be given when calling the function and should contain all host &amp; database info required to connect to the host &amp; database. As you can see inside the function it seperates the sub-variables of the $connection variable into 4 new variables. These are for the host, user, password and database (db). As these are the data required to connect to the host &amp; database and should be set in an array $connection and given to this function with sub-variable ‘host’, ‘user’, ‘pass’ and ‘db’.</p>
<p>We’ll be offering the $connection variable to the function as an array. It will use the sub-variable named ‘host’,  ‘user’, ‘pass’ and ‘db’ to try to establish a connection to the host and database. So these we’ll need to set in our config.php file. We’ll shorten the name of the variable $connection to $conn. As the name of it doesn’t really matter as long as we give it to the function ‘connect’ when calling it.</p>
<p><strong>File: config.php</strong></p>
<pre name="code" class="php:nogutter">
&lt;?php

####CONNECTION CONFIGURATION###
$conn[‘host’] = “localhost”;        // database host (name/IP)
$conn[‘user’] = “root”;                // database host username
$conn[‘pass’] = “password”;      // database host password
$conn[‘db’]    = “simple_blog”; //database name

?&gt;
</pre>
<p>With this info our function ‘connect’ should be able to establish a connection to the host &amp; database.</p>
<p>We set each sub-variable for the $conn array. So we’ve got one variable ( array ) that contains all sub-variables, all info required for establishing a connection to the database. Which our function <strong>connect</strong> will accomplish.</p>
<p>Let’s include these files to the index file already.</p>
<p><strong>File: index.php</strong></p>
<pre name="code" class="php:nogutter">
&lt;?php

include(“functions.php”);

include(“config.php”);

?&gt;
</pre>
<p>We can already use our function to connect to the host &amp; database:</p>
<p><strong>File: index.php</strong></p>
<pre name="code" class="php:nogutter">
&lt;?php

include(“functions.php”);

include(“config.php”);

connect($conn);

?&gt;
</pre>
<p>We provide the array variable $conn to the function which contains all the sub-variables data of host &amp; database ( as we set it in config.php ) required for establishing a connection.</p>
<p><h3>End of part 1</h3>
<p>That’s it so far! In this part we’ve createn the structure of the script for both files, functions &amp; database purpose. And also we’ve made our first function to establish a connection to the database &amp; host using the configurations for the  connection set in our config.php file we created. In the second part we’ll be creating a basic CSS, Div based 2 columns layout. With a side-bar menu and a main content area where all posts will be appearing. Hope to see you in the next part!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/creating-a-simple-blog-system-part-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Object Oriented Programming Basics &#8211; Extending Classes</title>
		<link>http://www.webcodez.net/php-mysql/object-oriented-programming-basics-extending-classes/</link>
		<comments>http://www.webcodez.net/php-mysql/object-oriented-programming-basics-extending-classes/#comments</comments>
		<pubDate>Mon, 22 Feb 2010 09:33:59 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[classes]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=361</guid>
		<description><![CDATA[Extending classes
It&#8217;s also possible to have a second class which extends the main class. This make the class able to use the (public) functions (methods) &#038; properties of the main class inside the other class. To extend a class we use extends.
Example:

class BasicClass {

}

class Class2 extends BasicClass {

}

Here Class2 extends the class &#8216;BasicClass&#8217; which means [...]]]></description>
			<content:encoded><![CDATA[<h3>Extending classes</h3>
<p>It&#8217;s also possible to have a second class which <strong>extends </strong>the main class. This make the class able to use the (public) functions (methods) &#038; properties of the main class inside the other class. To extend a class we use <strong>extends</strong>.</p>
<p><strong>Example</strong>:</p>
<pre name="code" class="php:nogutter">
class BasicClass {

}

class Class2 extends BasicClass {

}
</pre>
<p>Here Class2 extends the class &#8216;BasicClass&#8217; which means it will be able to use all the functions and variables/constabnts of this class. However in this example those are none. </p>
<h3>Using parent functions inside extending class</h3>
<p>[b]Note:[/b] The examples in this tutorial are just to show how extending classes works and what possiblities it has, what it&#8217;s cappable of.</p>
<p>As mentioned above it&#8217;s possible to use functions of the basic class ( parent class ) inside the extending class ( which extends the basic class ). Here we&#8217;ll be doing this. Let&#8217;s say we&#8217;ve got a basic class which has functions to set the name, age and gender of a human (/colleagues for example). Now we could have multiple other classes which make use of these functions ( extend the basic class ), each representing ne colleague/human.</p>
<p><strong>Note</strong>: this is just an example to show how it works and how extending classes can make use of functions set in a basic class.</p>
<p><strong>Example:</strong></p>
<pre name="code" class="php:nogutter">
class Colleague {

   protected function setName($name) {

       $this->name = $name;

   }

   protected function setGender($gender) {

       $this->gender= $gender;

   }   

   protected function setAge($age) {

       $this->age= $age;

   }   

}

class Colleague1 extends Colleague{

     parent::setName("Peter");
     parent::setGender("Male");
     parent::setAge("22");

}

class Colleague2 extends Colleague{

     parent::setName("Kim");
     parent::setGender("Female");
     parent::setAge("20");

}
</pre>
<p>However this might not be such practical to do, a more practical use  ( example ) is shown below. But this example is though a good example to easily understand what it&#8217;s cappable of ( extending classes ) theoretical and how it can be used.</p>
<p>Ok, so here we created one basic class which indicate the basic functions and properties for a colleage. Each colleague was made a class for ( 2 colleagues in this example ) using these functions to set the basic properties for each colleague. Let&#8217;s first have a look at the &#8217;setName&#8217;  function of the basic ( parent ) class &#8216;Colleague&#8217;:</p>
<pre name="code" class="php:nogutter">
   protected function setName($name) {

       $this->name = $name;

   }
</pre>
<p>It&#8217;s a protected function so only the extending class can use it. It sets the variable &#8216;name&#8217; which will also be able to be used in the extending class ( as that one makes use of all functions AND properties/variables of the parent/basic class ). You could as well make it a public function so that the user can use it outside the class to set the name of the colleague manually ( as done in the 2nd example/part of this tutorial ). Here though we made it a protected function so we&#8217;ll use it inside the extending class which brings us to the extending class &#8216;Colleague1&#8242; which sets the name with the following code:</p>
<pre name="code" class="php:nogutter">
     parent::setName("Peter");
</pre>
<p>Or mainly:</p>
<pre name="code" class="php:nogutter">
     parent::setName("name");
</pre>
<p>This uses the parent and :: symbols to access the parent class ( the class that it extends: &#8216;Colleague&#8217; ). This method works like this:</p>
<pre name="code" class="php:nogutter">
     parent::functionName();
</pre>
<p>To access a function of the parent class and:</p>
<pre name="code" class="php:nogutter">
     parent::$variablename;
</pre>
<p>to access a variable of the parent class.</p>
<p>The parent class just uses $this->variableName to set the variables as they&#8217;re &#8220;global&#8221; &#8211; able to being used in any other class that extends this class.</p>
<p><strong>Example of output from object:</strong></p>
<pre name="code" class="php:nogutter">
&lt;?php

class Colleague {

   protected function setName($name) {

       $this->name = $name;

   }

   protected function setGender($gender) {

       $this->gender= $gender;

   }   

   protected function setAge($age) {

       $this->age= $age;

   }   

}

class Colleague1 extends Colleague{

     parent::setName("Peter");
     parent::setGender("Male");
     parent::setAge("22");

}

class Colleague2 extends Colleague{

     parent::setName("Kim");
     parent::setGender("Female");
     parent::setAge("20");

}
########CREATE OBJECT (OUTPUT EXAMPLE)########
     $coll1 = new colleague1;
     $coll1->name; //outputs the name which is set using the parent function setName and is set to 'Peter' in this class
     $coll2 = new colleague2;
     $coll2->name; //outputs the name which is set using the parent function setName and is set to 'Kim' in this class

?>
</pre>
<h3>Using parent functions outside the extending class ( as object )</h3>
<p>It&#8217;s also possible to have a basic class set the functions that the extending class needs to be cappable of. For example: SHOWING the name, instead of SETTING the name. Then we could have the class that extends it, create a function to set the name. So when an object of the class is created, we can set the name and use the function of the parent class as well to show the name. However we do need to make the functions of the basic class ( parent ) public as we want to use it outside the class ( wih the object, to show the name ).</p>
<pre name="code" class="php:nogutter">
class Colleague{

    public function showName() {

       return $this->name;

   }

}

class Colleague1 extends Colleague{

     public function setName($name) {

              $this->name = $name;

     }

}
</pre>
<p>So the extending class has his function to set the name, and uses the function of the basic class to be cappable of showing the name. We could create an object that shows us that it&#8217;s cappable of this:</p>
<pre name="code" class="php:nogutter">
$coll = new colleague1;
$coll->setName("Peter"); //set name, uses the function set in this extending class
echo $coll->showName(); //show name, uses the function set in the parent class (basic class: Colleague)
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/object-oriented-programming-basics-extending-classes/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PHP Smilies System</title>
		<link>http://www.webcodez.net/php-mysql/php-smilies-system/</link>
		<comments>http://www.webcodez.net/php-mysql/php-smilies-system/#comments</comments>
		<pubDate>Mon, 15 Feb 2010 21:29:51 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[foreach loop]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[str_replace]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=375</guid>
		<description><![CDATA[In this tutorial we&#8217;ll be creating a system which will convert messages including text smilies into messages including icon smilies ( text => smilie icons ). 
Preknowledge
For this tutorial it&#8217;s prefered that you&#8217;ve got some preknowledge about php variables, arrays, functions and the foreach loop. If not, I&#8217;d recommend you to have a look at [...]]]></description>
			<content:encoded><![CDATA[<p>In this tutorial we&#8217;ll be creating a system which will convert messages including text smilies into messages including icon smilies ( text => smilie icons ). </p>
<h3>Preknowledge</h3>
<p>For this tutorial it&#8217;s prefered that you&#8217;ve got some preknowledge about php variables, arrays, functions and the foreach loop. If not, I&#8217;d recommend you to have a look at the following tutorials which apply well to this tutorial:</p>
<ul>
<li><a href="http://www.webcodez.net/php-mysql/variables-in-php/">PHP Variables</a></li>
<li><a href="http://www.webcodez.net/php-mysql/arrays/">PHP Arrays</a></li>
<li><a href="http://www.webcodez.net/php-mysql/foreach-loop/">Foreach Loop</a></li>
</ul>
<h3>Functions &#038; Loops used</h3>
<p>The functions/loops used in this tutorial:<br />
<strong></p>
<ul>
<li>str_replace(&#8216;part to replace&#8217;, &#8216;value to replace by&#8217;, $str)</li>
<li>foreach($array as $key => $value)</li>
</ul>
<p></strong></p>
<h3>Creating the function</h3>
<p>Let&#8217;s first create a function which will do this job &#8211; replacing all smiley tags by smiley images. The only thing the function needs to do this task is a string ( text ) to do this for and an array of all smiley tags &#038; corresponding smiley images to replace them with inside the string.</p>
<pre name="code" class="php:nogutter">
function replaceSmilies($str, $smilies) {

}
</pre>
<p>We gave them as argruments for the function, we called the string that needs to be given: &#8216;$str&#8217;, and the array with smiley tags &#038; images that need to be set: &#8216;$smilies&#8217;.</p>
<h3>Setting up smilies syntaxes &#038; images</h3>
<p><strong>Note</strong>: This part should be put outside the function as it&#8217;s just for setting up the smiley tags &#038; images ( example ) and an example string to replace them in. In other words: setting up the variables that are required for the function to do his task. The variables that we&#8217;ll be working with inside the function to replace the smileys.</p>
<p>The first thing we&#8217;re going to do is set up a list of smiley &#8216;tags&#8217;, syntaxes ( such as : ) and : D, etc. ) and the corresponding image icons (smilies) for those tags. We&#8217;re going to create an array to do this.</p>
<p>An array can be created like this:</p>
<pre name="code" class="php:nogutter">
$myArr = array("key" => "value", "key2" => "value2");
</pre>
<p>In our case we&#8217;ll set the keys equal to the smilie tags and the values equal to the smilie images ( icons ) with which these tags need to be replaced with.</p>
<p><strong><br />
Example:</strong></p>
<pre name="code" class="php:nogutter">
$smilies = array(":)" => "smile.jpg",
                 ":P" => "thongue.jpg");
</pre>
<p>Here I just set up 2 smilies but setup as many as you want. The image names I used (&#8217;smile.jpg&#8217; and &#8216;thongue.jpg&#8217;) can be any image that contains the smiley icon you want to show up for this smiley tag.</p>
<p>What we&#8217;ll want to do inside the replaceSmilies function is replace the keys (smiley tags) of the array by the images of the values (smilies) of the array.</p>
<p>Now let&#8217;s as well create an example text ( string ) in which these smiley tags occur and need to be replaced by the smiley icons/images:</p>
<pre name="code" class="php:nogutter">
$str = "Hi there! <img src='http://www.webcodez.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Example text <img src='http://www.webcodez.net/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ";
</pre>
<p>So now we&#8217;ve setup the argruments ( variables/arrays ) that are needed for our function that we&#8217;ll be creating. So let&#8217;s put <strong>everything </strong>together for so far:</p>
<pre name="code" class="php:nogutter">
&lt;?php
function replaceSmilies($str, $smilies) {

}

$smilies = array(":)" => "smile.jpg",
                 ":P" => "thongue.jpg");
$str = "Hi there! <img src='http://www.webcodez.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Example text <img src='http://www.webcodez.net/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ";
?>
</pre>
<h3>Creating the loop</h3>
<p>Now we&#8217;re going to create a foreach loop which we&#8217;ll let it put the keys ( smiley tags ) of the array into a variable &#8216;$tag&#8217; and the values ( smiley images ) into a variable &#8216;$image&#8217;. However it will do this for only 1 couple of a key and a value per time and execute the loop for that couple of a smiley tag and a smiley image. We&#8217;ll put the loop inside the function as the function will need to do the replacing of these smiley tags by these smiley images.</p>
<p><strong>Structure of a foreach loop:</strong></p>
<pre name="code" class="php:nogutter">
foreach($array as $keyvariable => $valuevariable) {

}
</pre>
<p>becomes =></p>
<p><strong>Our foreach loop:</strong></p>
<pre name="code" class="php:nogutter">
foreach($smilies as $tag => $image) {

}
</pre>
<p>$smilies is the array we created to put all smiley tags ( keys ) and smiley images ( values ) into. As mentioned above for each couple of a smiley tag and a smiley image, the foreach loop will be ran with the smiley tag put in $tag and the smiley image put in $image. So for example $tag = &#8216;:)&#8217; and $image = &#8217;smile.jpg&#8217;. This is the first variable of our example array ($smilies) &#8211; our first couple of a smiley tag ( key ) and a smiley image ( value ). </p>
<p>So let&#8217;s put it inside the function.</p>
<pre name="code" class="php:nogutter">
function replaceSmilies($str, $smilies) {

   foreach($smilies as $tag => $image) {

   }

}
</pre>
<h3>Replacing the smilies</h3>
<p>So what will it need to do with this smiley tag and smiley image? It will need to replace the smiley tag by the smiley image inside the string which is set in $str ( see the function argruments &#038; the example $str message set in the beginning ).<br />
Before we&#8217;ll do this we&#8217;ll first create a new variable &#8216;$new_str&#8217; which we&#8217;ll set equal to &#8216;$str&#8217; in the first place but which will change as the smiley tags get replaced by the smiley images in there.</p>
<pre name="code" class="php:nogutter">
function replaceSmilies($str, $smilies) {

   $new_str = $str; //set the new string equal to the string given in the first place
                        //the foreach loop will be replacing the smilies inside this string
                       //so $new_str will contain the new string with images of the smilies (icons) inside

   foreach($smilies as $tag => $image) {

   }

}
</pre>
<p>Now we&#8217;ll be replacing the smiley tags by the smiley images. This will be done inside the foreach loop as there we got the smiley tags inside $tag and smiley images inside $images so we can easily replace them. Therefore we&#8217;ll use the <strong>str_replace</strong> function. So how does this function work?</p>
<pre name="code" class="php:nogutter">
str_replace("thing to replace", "value to replace it by", "string to do this inside");
</pre>
<p>so in our case;</p>
<pre name="code" class="php:nogutter">
str_replace($tag, $image, $new_str);
</pre>
<p>Which will replace $tag by $image inside $new_str. Which is correct: $tag contains the smiley tag and $image contains the smiley image and $new_str the string to replace these inside ( which will contain the new string ). Now it will return $new_str but then with the smiley tag replaced by the smiley image. But we do want to save this new (replaced) string it returns inside the variable $new_str to update it:</p>
<pre name="code" class="php:nogutter">
$new_str = str_replace($tag, $image, $new_str);
</pre>
<p>However now it will replace for example like &#8216;:)&#8217; by &#8217;smile.jpg&#8217;. Which won&#8217;t give us the image of &#8217;smile.jpg&#8217; yet!<br />
So instead we need to replace it by:</p>
<blockquote><p>
&lt;img src=&#8217;smile.jpg&#8217;></p></blockquote>
<p>or in general:</p>
<blockquote><p>
&lt;img src=&#8217;&#8221;.$image.&#8221;&#8216;></p></blockquote>
<p>So let&#8217;s change this inside the replace function:</p>
<pre name="code" class="php:nogutter">
$new_str = str_replace($tag, "&lt;img src='".$image."'>", $new_str);
</pre>
<p>And let&#8217;s put it inside the loop.</p>
<pre name="code" class="php:nogutter">
function replaceSmilies($str, $smilies) {

   $new_str = $str; 

   foreach($smilies as $tag => $image) {

     $new_str = str_replace($tag, "&lt;img src='".$image."'>", $new_str);

   }

}
</pre>
<p>The last thing the function needs to do is return the new string, which is put in $new_str.</p>
<pre name="code" class="php:nogutter">
function replaceSmilies($str, $smilies) {

   $new_str = $str; 

   foreach($smilies as $tag => $image) {

     $new_str = str_replace($tag, "&lt;img src='".$image."'>", $new_str);

   }

   return $new_str; //return the new, updated string containing the smiley images

}
</pre>
<h3>Smilies Directory Updating</h3>
<p>It could be that you&#8217;ve put the smiley images inside another map/directory. In that case you can easily update the path of the image inside the loop. Better said: inside the <strong>str_replace</strong> function of the loop.</p>
<p>To do this, this part needs to be changed:</p>
<blockquote><p>
&lt;img src=&#8217;&#8221;.$image.&#8221;&#8216;></p></blockquote>
<p>As that&#8217;s the html image that all smileys will be replaced by. And we used a foreach loop for the smileys array which put all smiley images, one per time, inside $image and executed the foreach loop for each smiley the same way. So we only need to change this part as it uses this for each smiley and each smiley image. As they all will be set inside $image and replaced the same way inside the foreach loop.</p>
<p>So,<strong> for example</strong>, we could update the path like this:</p>
<blockquote><p>&lt;img src=&#8217;yourpath/&#8221;.$image.&#8221;&#8216;></p></blockquote>
<pre name="code" class="php:nogutter">
     $new_str = str_replace($tag, "&lt;img src='images/".$image."'>", $new_str);
</pre>
<p>Where we set the path to images/, so all smilies will be replaced by &#8216;images/smiley_image_name.jpg&#8217; instead of just &#8217;smiley_image_name.jpg&#8217;.</p>
<h3>Using the function</h3>
<p>To use the function we simply call the function and give the string ($str) and smiley tags &#038; images array ($smilies) which we set in the beginning of this tutorial.</p>
<pre name="code" class="php:nogutter">
&lt;?php

function replaceSmilies($str, $smilies) {

   $new_str = $str; 

   foreach($smilies as $tag => $image) {

     $new_str = str_replace($tag, "&lt;img src='".$image."'>", $new_str);

   }

   return $new_str; //return the new, updated string containing the smiley images

}

$smilies = array(":)" => "smile.jpg", ":P" => "thongue.jpg");
$str = "Hi there! <img src='http://www.webcodez.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Example text <img src='http://www.webcodez.net/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ";

echo "<b>Input string:</b> {$str} &lt;p>
          <b>Output string:</b> ".replaceSmilies($str, $smilies);

?>
</pre>
<h3>Download Full Script (function &#038; smilies pack)</h3>
<p>I&#8217;ve created a sample script of this tutorial which includes a ready to use function for replacing smilies in a text by the smiley images (icons). The smiley icons/images are provided within the zip file and the function automaticly uses these smiley images by default unless you provide another set of smilies to the function.</p>
<p><b>How to use</b></p>
<pre name="code" class="php:nogutter">
&lt;?php

    include("function.php"); //include the smilies function to your file      

    $str = "the message with smilies <img src='http://www.webcodez.net/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' />  <img src='http://www.webcodez.net/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> "; //setup a variable that contains the message that needs to be converted

    echo replaceSmilies($str); //replace he smilie tags with the default smiley images

    //or: echo replaceSmilies($str, $smilies, $dir); where $smilies is the array with smiley tags &#038; image filenames as done in this tutorial

?>
</pre>
<h3><a href="http://www.webcodez.net/wp-content/plugins/download-monitor/download.php?id=1">Download</a></h3>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/php-smilies-system/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generate Random Passwords</title>
		<link>http://www.webcodez.net/php-mysql/generate-random-passwords/</link>
		<comments>http://www.webcodez.net/php-mysql/generate-random-passwords/#comments</comments>
		<pubDate>Thu, 21 Jan 2010 15:04:23 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[for loop]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[loops]]></category>
		<category><![CDATA[net script]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[variables]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=184</guid>
		<description><![CDATA[For generating passwords multiple methods can be used. In this tutorial we&#8217;ll be discussing 2 ways to generate random passwords. The result of both methods is exactly the same. Although method 1 is based on generating random indexes and picking another (random) index&#8217;s value each time when adding a new random character to the random [...]]]></description>
			<content:encoded><![CDATA[<p>For generating passwords multiple methods can be used. In this tutorial we&#8217;ll be discussing 2 ways to generate random passwords. The result of both methods is exactly the same. Although method 1 is based on generating random indexes and picking another (random) index&#8217;s value each time when adding a new random character to the random password. While method 2 is based on picking the same index but shuffling the values and indexes so that that index contains a different value each time.</p>
<p><strong>Method 1</strong><br />
We&#8217;ll start with the first method which uses these PHP functions:</p>
<p>    * str_split &#8211; converts a string into an array<br />
    * shuffle &#8211; shuffles an array (index and values)</p>
<p>What we need to create first, is a variable $charset which contains all characters and maybe symbols that we want the system to generate a random password out of. So the characters the password generated can/may contain.</p>
<p>Here I take for example all alphabetical characters and all numbers.</p>
<pre name="code" class="php:nogutter">
&lt;?php

$charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678901234567890012345678901234567890";

?>
</pre>
<p>The numbers 0-9 I put in it 4 times because there are about 2 times as much alphabetical characters and they&#8217;re put inside it twice ( non-capital and capital) and I want to have about the same amount (chance) of characters as numbers inside the password.</p>
<p>What we want to do is create a function that generates a random password using random characters or numbers from our charset. We also need to be able to give the amount of chars to pick randomly out of the charset to create a password from ( the length of the random password ). So the argruments for the function should be: charset, length. Where charset is our $charset and length is the length of the password ( amount of random chars picked from the charset and put together ).</p>
<pre name="code" class="php:nogutter">
&lt;?php

function random_passw($charset, $length) {

   ... generate $length random chars out of $charset

}

$charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678901234567890012345678901234567890";

$length = 8; //we set the length for our password to 8 chars for example

?>
</pre>
<p>So now we&#8217;ve come to the part of the function which needs to shuffle all characters of the charset. Therefore we first need to put it into an array as the shuffling is based on shuffling the indexes and values. We use the str_split function to put the charset in an array.</p>
<pre name="code" class="php:nogutter">
function random_passw($charset, $length) {

   $charset_arr = str_split($charset); //charset_array

}
</pre>
<p>So now the charset is put in an array like this:</p>
<blockquote><p>$charset_arr[0] = &#8220;A&#8221;;<br />
$charset_arr[1] = &#8220;B&#8221;;<br />
$charset_arr[2] = &#8220;C&#8221;;<br />
&#8230; etc &#8230;</p></blockquote>
<p>In this case the index 0 has the value &#8216;A&#8217;. We&#8217;ll make a loop which adds that index value to the password ( we&#8217;ll make a variable $passw ) the amount of times set in $length:</p>
<pre name="code" class="php:nogutter">
function random_passw($charset, $length) {

    $charset_arr = str_split($charset); //charset_array

    $passw = ""; //empty password to start with

  for($a=1;$a<=$length;$a++) { //as long as $a is smaller than or equal to $length
  //and increase $a each time the loop is executed

      $passw .= $charset_arr[0]; //add the value of the charset's first character (of index 0, which in this case is equal to the character 'A' )

   }

 }
</pre>
<p>So now it adds '$length' times the character 'A' to the variable $passw. So if we give the value 8 to the variable $length, it adds 'A' to the password 8 times, like:</p>
<blockquote><p>$passw = "AAAAAAAA";</p></blockquote>
<p>But we want it to add a different character to the set (password) each time it adds a character. To do this we use the function shuffle. This function will shuffle all indexes and values randomly - shuffle all chars in the charset in a random order. So say we first got our charset like:</p>
<pre name="code" class="php:nogutter">
$charset_arr = "ABC";
</pre>
<p>Which has the array:</p>
<pre name="code" class="php:nogutter">
$charset_arr[0] = "A";
$charset_arr[1] = "B";
$charset_arr[2] = "C";
</pre>
<p>It will shuffle all values for the indexes, so it could be shuffled like this then (for example, but it's random so it could be shuffled anyhow) :</p>
<pre name="code" class="php:nogutter">
$charset_arr[0] = "C";
$charset_arr[1] = "A";
$charset_arr[2] = "B";
</pre>
<p>So then the index 0 suddenly got the value "C" instead of "A". This way we can make it pick the same index but containing another value for our index '0' each time and this way pick random characters out of the charset.</p>
<pre name="code" class="php:nogutter">
function random_passw($charset, $length) {

     $charset_arr = str_split($charset); //charset_array

    $passw = ""; //empty password to start with

  for($a=1;$a<=$length;$a++) { //as long as $a is smaller than or equal to $length
  //and increase $a each time the loop is executed

      $shuffled = shuffle($charset_arr); //shuffles the indexes and values - in other words: shuffles the chars in the charset in a random order
      $passw .= $shuffled[0]; //take the value of the index '0' of the SHUFFLED charset - the first character of the shuffled charset which is different each time it's shuffled ( which is each time the loop is executed / shuffle function executed )

      }

  }
</pre>
<p>Last thing we need to do is make it return the password generated, which can be done using the function return.</p>
<pre name="code" class="php:nogutter">
function random_passw($charset, $length) {

     $charset_arr = str_split($charset); //charset_array

    $passw = ""; //empty password to start with

  for($a=1;$a<=$length;$a++) { //as long as $a is smaller than or equal to $length
  //and increase $a each time the loop is executed

      $shuffled = shuffle($charset_arr); //shuffles the indexes and values - in other words: shuffles the chars in the charset in a random order
      $passw .= $shuffled[0]; //take the value of the index '0' of the SHUFFLED charset - the first character of the shuffled charset which is different each time it's shuffled ( which is each time the loop is executed / shuffle function executed )

     }

     return($passw);

  }
</pre>
<p>And we're done!</p>
<p>Example of use:</p>
<pre name="code" class="php:nogutter">
function random_passw($charset, $length) {

     $charset_arr = str_split($charset); //charset_array

    $passw = ""; //empty password to start with

  for($a=1;$a<=$length;$a++) { //as long as $a is smaller than or equal to $length
  //and increase $a each time the loop is executed

      $shuffled = shuffle($charset_arr); //shuffles the indexes and values - in other words: shuffles the chars in the charset in a random order
      $passw .= $shuffled[0]; //take the value of the index '0' of the SHUFFLED charset - the first character of the shuffled charset which is different each time it's shuffled ( which is each time the loop is executed / shuffle function executed )
  }

  }

$charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678901234567890012345678901234567890";
$length = 8;

$password = random_passw($charset, $length);

echo "Your password is: ".$password;

?>
</pre>
<p><strong>Method 2</strong></p>
<p>Functions used:</p>
<p>    * mt_rand($first, $last) - generates random number between $first and $last<br />
    * length($str) - calculates the length of the string $str</p>
<p>What we basicly did in the first method was adding the same index's value of the charset. But we made it contain another value each time by suffling the values of the indexes. Now we'll keep our charset in the same 'order' ( so each index keeps the same value ). But this time we'll change the index we request the value of each time we do so. So this way it requests another index's value ( and so another character ) each time we add a new character to the password. In other words: we add random characters to the password. We'll again use our charset and length variables:</p>
<pre name="code" class="php:nogutter">
&lt;?php

$charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678901234567890012345678901234567890";

$length = 8; //we set the length for our password to 8 chars for example

?>
</pre>
<p>And now create a function which generates the random characters. We'll therefore again use a for loop to make it add a new random character to the password string as many times as set in $length. So the password will be the length of $length.</p>
<pre name="code" class="php:nogutter">
function random_passw($charset, $length) {

   $passw = "";

   for($a=1;$a<=$length;$a++) {

       //add a random character to the $passw

   }

}
</pre>
<p>We again use the same loop and set a variable $passw in the beginning to empty. We'll be adding the random characters to it inside the for loop. The charset is now already having indexes and values for each character, like this:</p>
<pre name="code" class="php:nogutter">
$charset[0] = "A";
$charset[1] = "B";
$charset[2] = "C";
... etc ...
</pre>
<p>Just because we got the characters in this order inside the variable:</p>
<blockquote><p>$charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678901234567890012345678901234567890";
</p></blockquote>
<p>You see the first character 'A' has been given the index 0. Now what we basicly need to do for adding a random character, is generating a random index for the array ( and so a random value/character corresponding to that index ). Which is generating a random number from 0 ( the first index ) to the last index. The last index can be generated by counting the amount of characters minus 1. Because the first character hasn't been given the index 1 but 0, and for the second character it's 1, etc.. So for the last character's index it's the amount of characters minus one. The amount of characters can be calculated using the length function:</p>
<pre name="code" class="php:nogutter">
function random_passw($charset, $length) {

   $passw = "";

   for($a=1;$a<=$length;$a++) {

       $first_index = 0;
       $last_index = length($charset)-1;

   }

}
</pre>
<p>Now we need to generate a random number between the first and last index ( 0 - $last_index ). We can use the function mt_rand to do this.</p>
<pre name="code" class="php:nogutter">
function random_passw($charset, $length) {

    $passw = "";

    for($a=1;$a<=$length;$a++) {

        $first_index = 0;
       $last_index = length($charset)-1;

       $index = mt_rand($first_index, $last_index); //generates random index

    }

 }
</pre>
<p>Now we got a random index we generated in the variable $index. And because it's a number between the first and last index of the charset, we are sure it has a value. Which is one of the characters of the charset. Which we can call like $charset[index] ( as it's $array[index], and the charset can be seen a special kind of array where each index has one value ( the next character in the string ) ). And as the random index we generated is in the variable $index, it becomes $charset[$index] for us.So we'll add that value to the password:</p>
<pre name="code" class="php:nogutter">
 function random_passw($charset, $length) {

     $passw = "";

     for($a=1;$a<=$length;$a++) {

         $first_index = 0;
         $last_index = length($charset)-1;

       $index = mt_rand($first_index, $last_index); //generates random index

       $passw .= $charset[$index];

     }

  }
 </pre>
<p>Allright, so now it adds a value of a random index ( and so a random character of the charset ) to the $passw variable. And it does this $length many times. In other words: it creates a random pasword with the length of $length.</p>
<p>Now the last thing to do is actually returning the password:</p>
<pre name="code" class="php:nogutter">
  function random_passw($charset, $length) {

      $passw = "";

      for($a=1;$a<=$length;$a++) {

          $first_index = 0;
         $last_index = length($charset)-1;

        $index = mt_rand($first_index, $last_index); //generates random index

       $passw .= $charset[$index];

      }

   return($passw);

   }
  </pre>
<p>Which is, easy as it gets, the function return. And the random password generator function is done!<br />
It has the same use as the previous one explained in method 1, so enjoy!</p>
<p>Cheers,<br />
Admin.</p>
<p>Btw, realised the first method wasn't that much faster afterall lol </p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/generate-random-passwords/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
