<?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; admin</title>
	<atom:link href="http://www.webcodez.net/author/admin/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>Retrieving User Input Data</title>
		<link>http://www.webcodez.net/php-mysql/retrieving-user-input-data/</link>
		<comments>http://www.webcodez.net/php-mysql/retrieving-user-input-data/#comments</comments>
		<pubDate>Sat, 27 Feb 2010 14:19:50 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[Forms]]></category>
		<category><![CDATA[if loop]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[user input]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=460</guid>
		<description><![CDATA[In this tutorial we&#8217;ll be retrieving data from form fields. To do this we&#8217;ll first create an example form. We&#8217;re using the POST method to send the form data in the first example. Will later explain what this means, and how we can then retrieve the data from the form fields. Also the GET method [...]]]></description>
			<content:encoded><![CDATA[<p>In this tutorial we&#8217;ll be retrieving data from form fields. To do this we&#8217;ll first create an example form. We&#8217;re using the POST method to send the form data in the first example. Will later explain what this means, and how we can then retrieve the data from the form fields. Also the GET method will be explained in this tutorial later on. For the form we set the action to the file itself ( we call it &#8216;form_handle.php&#8217;, call it anything you like ). </p>
<h3>The Form</h3>
<p><strong>File: form_handle.php</strong></p>
<pre name="code" class="php:nogutter">
&lt;form method="POST" action="fom_handle.php">
 &lt;input type="text" name="test_field">
 &lt;input type="submit" name="submit" value="Send!">
&lt;/form>
</pre>
<p><h3>Handling the form data</h3>
<p>Ok in this form we made 2 fields. One text input field, we named &#8216;test_field&#8217; and one submit button we called &#8217;submit&#8217; and already gave the value &#8216;Send!&#8217; to it. Now once the submit button gets pressed, the data of the input fields will be send using the method POST to the file form_handle.php ( as set in the form tag ). This means all values of the input fields will be stored into $_POST['input_field_name'] variables. So in our case we got 2 input fields, and so 2 $_POST variables will be created. One for the field &#8216;test_field&#8217;, which will be stored in $_POST['test_field'], and one for the submit button field we called &#8217;submit&#8217;, which will bestored in $_POST['submit']. So in this way the data will be send to the page once the form gets submitted using the form. The submit button we gave a default value already &#8216;Send!&#8217; so for this input field always this variable will be created:</p>
<p><pre name="code" class="php:nogutter">
$_POST['submit'] = "Send!";
</pre>
</p>
<p>Once the form has been submitted. So we can actually CHECK if the form was submitted, by validating this:</p>
<p><pre name="code" class="php:nogutter">
&lt;?php
if($_POST['submit'] == "Send!") { //form has been submitted correctly?

   //handle form data

}

  //show form

}
?>
</pre>
<p>Because when the form gets submitted, as mentioned above, for each field will be created a variable $_POST['field_name'] and given a value ( either filled in by user or the default value ) which is default set to &#8216;Send!&#8217; for the submit button. So the variable $_POST['submit'] must have been created if the form was submitted and must be given the value &#8216;Send!&#8217; to as we gave it that value inside the form submit button input field. But we also made another input field we called &#8216;test&#8217;. This field we didn&#8217;t gave a value and can be filled in by the user as it&#8217;s a &#8220;text&#8221; input field. Which looks like this:</p>
<p></p>
<input type="text" name="test">
<p></p>
<p>And we want to show what the user filled in there. And as we know the data of the input fields are stored in $_POST['input_field_name'], we can get the data filled in for the field named &#8216;test&#8217; from the variable $_POST['test']. So let&#8217;s do this. But of course only when the form was submitted this is possible, so we use the loop we created to check whether the form was submitted or not:</p>
<p><strong>File: form_handle.php</strong></p>
<pre name="code" class="php:nogutter">
&lt;?php

if($_POST['submit'] == "Send!") { //form has been submitted correctly?

   //handle form data
   echo "<b>Input field: 'test'</b> - You filled in: ".$_POST['test'];

}else{ //not submitted? show form

?>

&lt;form method="POST" action="fom_handle.php">
 &lt;input type="text" name="test_field">
 &lt;input type="submit" name="submit" value="Send!">
&lt;/form>

&lt;?php

}

?>
</pre>
<p>When the form has not been submitted yet, this will output:</p>
<p></p>
<form method="POST" action="fom_handle.php">
<input type="text" name="test_field">
<input type="submit" name="submit" value="Send!">
</form>
<p></p>
<p>Once the form has been submitted this will output:</p>
<p> </p>
<p><b>Input field: &#8216;test&#8217;</b> &#8211; You filled in: [here what the user filled in for this field]</p>
<p>Allright, so those are the basics of retrieving user input data. The same principe works for all other input fields such as checkboxes ( which get their value when they&#8217;re checked ), radio boxes, etc..</p>
<p>However there&#8217;s also a second method: the GET method. It works the same for retrieving the data, they&#8217;re put inside $_GET['input_field_name'] when submitting the form. However, they can be changed inside the url. As they&#8217;re now submited through url. Like:</p>
<blockquote><p>
form_handle.php?submit=Send!&#038;test=what_the_user_filled_in_for_this_field</p></blockquote>
<p>So it could be manipulated very easily by changing that inside the url, and beside that, the user can see all values of as well hidden input fields ( which are given a default value for example ) through url. For example you&#8217;d have an input field:</p>
<pre name="code" class="php:nogutter">
&lt;input type='hidden' name='key' value='myverylongsecretkey2985230'>
</pre>
<p></p>
<p>Then once the form gets submitted using GET method you&#8217;ll see this key just in the url!</p>
<blockquote><p>form_handle.php?key=myverylongsecretkey2985230</p></blockquote>
<p>So you don&#8217;t want that. So usually POST methods are used for securely submitting form, user input data.</p>
<p><h3>End of tutorial</h3>
</p>
<p>We&#8217;ve come to the end of this small tutorial. Hope you learnt something in this tutorial and also have a look at the tutorial about <a href="http://www.webcodez.net/php-mysql/user-input-validation/">User Input Validation</a>. Which can nicely be combined with this tutorial on how to actually first RETRIEVE the user input data before validating it or anything. Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/retrieving-user-input-data/feed/</wfw:commentRss>
		<slash:comments>0</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>Securing data in PHP</title>
		<link>http://www.webcodez.net/php-mysql/securing-data-in-php/</link>
		<comments>http://www.webcodez.net/php-mysql/securing-data-in-php/#comments</comments>
		<pubDate>Wed, 17 Feb 2010 12:10:12 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[php database interactions]]></category>
		<category><![CDATA[PHP securing data]]></category>
		<category><![CDATA[php user input]]></category>
		<category><![CDATA[secure]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=417</guid>
		<description><![CDATA[It&#8217;s very important to secure your data in PHP correctly. Because if you don&#8217;t, your website is in risk of being harmed by SQL injections and other dangerous code injections, which you obviously don&#8217;t want. So to protect your website against these code attacks, this tutorial was written  
This tutorial will explain the reasons [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s very important to secure your data in PHP correctly. Because if you don&#8217;t, your website is in risk of being harmed by SQL injections and other dangerous code injections, which you obviously don&#8217;t want. So to protect your website against these code attacks, this tutorial was written <img src='http://www.webcodez.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>This tutorial will explain the reasons to secure data in PHP and the best ways to easily accomplish this.</p>
<h3>Securing data before database interaction</h3>
<p>The first &#8216;type&#8217; of data you should secure is the data which you will interact to the database with. Of course you could as well just use the user inputten data to interact with your database table right away, but let&#8217;s have a look at what could happen if you do so:</p>
<p><strong>Unsecure mysql select query(BAD):</strong></p>
<pre name="code" class="php:nogutter">
$user_input1 = "username_example"; //example of valid user input
$user_input2 = " ' OR username = 'username_example"; //BAD user input
$sql = "SELECT id FROM accounts WHERE username = '$user_input1' AND password = '$user_input2' ";
</pre>
<p>This is an example of an unsecure sql query which could for example be used with a login system to check whether the user inputten username &#038; password are valid. However because of it&#8217;s unsecurity users could just fill in some password like &#8216;OR username = &#8216;username_example  . What will happen then, you can see from the following:</p>
<pre name="code" class="php:nogutter">
$sql = "SELECT id FROM accounts WHERE username = '$user_input1' AND password = '$user_input2' ";
</pre>
<p>becomes =></p>
<pre name="code" class="php:nogutter">
$sql = "SELECT id FROM accounts WHERE username = 'username_example' AND password = '' OR username = 'username_example' ";
</pre>
<p>Now, say, &#8216;username_example&#8217; is a valid username of an account the user knows and want to login to without having to supply the password ( hack it ), he just filled in his bad code to make the query still return true because it now checks whether the username &#038; password are correct OR the username is only correct. Which obviously is the case. So the user has now successfully logged in to the victims account. Of course you don&#8217;t want this to happen to your website&#8217;s members! So be smart, and secure your data in PHP.</p>
<p>However this was just an example for an unsecure login system, sql query. The same thing can happen to any other sql queries which are set up unsecured, which use user inputten data straight away without securing it first. </p>
<p>In the above example the coder made atleast 2 major security faulths:</p>
<ul>
<li>
Coder used the user inputten data straight away into a sql query</li>
<li>Coder put the user inputten data in the query between single quotes</li>
</ul>
<p>The first faulth was explained above. But beside that it was also very wrong to put the user input data between single quotes which, as you could see in the above example of a bad user input, made the user able to easily bypass/get round these quotes and add another part to the query themselves. So the first thing we should do to make this query to secure is put it between &#8216;&#8221;. and .&#8221;&#8216;:</p>
<p>So in general example:</p>
<pre name="code" class="php:nogutter">
$better_query = "SELECT field FROM table WHERE field = '".$_POST['userinput_fieldname']."' ";
</pre>
<p>But still this isn&#8217;t enough. However it&#8217;s already a lot harder now for the user to inject codes inside the query, it still can be done. To prevent this totally, we can use the security function made by PHP: mysql_real_escape_string. This function will escape all dangerous contents out of the user inputten data. So it can&#8217;t do any harm to your sql query and database and/or website anymore.<br />
<strong><br />
Secure and proper select query example (GOOD):</strong></p>
<pre name="code" class="php:nogutter">
$better_query = "SELECT field FROM table WHERE field = '".mysql_real_escape_string($_POST['userinput_fieldname'])."' ";
</pre>
<p>Allright, so now atleast our query is secured and safe. The same can be done by <strong>INSERTING </strong>data into the database however there&#8217;s still one thing that could possibly happen: an error can occur when users use symbols such as &#8216; and &#8221; (quotes) in an inapropperiate way. </p>
<p>To fix this, we can make PHP add slasshes before these symbols to escape them. This will make these quotes for example, to be threatend as plain text. A function that does this for us is: <strong>addslashes</strong>.</p>
<p><strong>Secure and proper insert query example (GOOD):</strong></p>
<pre name="code" class="php:nogutter">
$secure_and_proper_query = "INSERT INTO table(field)VALUES('".addslashes(mysql_real_escape_string($_POST['userinput_fieldname']))."' ";
</pre>
<p>When doing this you might want to use stripslashes again when rertrieving the data, if it happens to show the slashes in the output.</p>
<h3>Securing data before database output</h3>
<p>It&#8217;s also not always safe to output user input data from database straight away, especially when you haven&#8217;t secured the user input data. If you DO secure the user input data to the database as done above, you should be safe, but to be 100% sure the database fields don&#8217;t contain any codes that will be executed: a function such as htmlspecialchars could be used. This function escapes all possibly harming tags/symbols out of the data. For example < will become &lt;. Which will only be converted once by the browser into the text symbol < and which won't be executed as a code ( such as < b > normally would make text bold ).<br />
<strong><br />
Secure Output Example:</strong></p>
<pre name="code" class="php:nogutter">
//example of bad user input from database or input field
$bad_userinput = "make whole page from here bold! &lt;b> and mess up layout &lt;/table> or &lt;table>";

echo htmlspecialchars($bad_userinput); //hah I won't!
</pre>
<p>And <strong>Fixed </strong>- your webpage has been prevented of being totally messed up by the user input.</p>
<p><strong>Hope you learnt something and don&#8217;t forget: always secure user inputten data in PHP before using <img src='http://www.webcodez.net/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> !</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/securing-data-in-php/feed/</wfw:commentRss>
		<slash:comments>3</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>Object Oriented Programming Basics</title>
		<link>http://www.webcodez.net/php-mysql/object-oriented-programming-basics/</link>
		<comments>http://www.webcodez.net/php-mysql/object-oriented-programming-basics/#comments</comments>
		<pubDate>Fri, 12 Feb 2010 18:49:03 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[basics]]></category>
		<category><![CDATA[classes]]></category>
		<category><![CDATA[instances]]></category>
		<category><![CDATA[methods]]></category>
		<category><![CDATA[Object Oriented Programming]]></category>
		<category><![CDATA[objects]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[properties]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=348</guid>
		<description><![CDATA[This tutorial will be explaining the basics of Object Oriented Programming (OOP) classes. Let&#8217;s start with getting straight the following question:
What will be explained in this tutorial?
This tutorial will only explain the basics of OOP programming in PHP which consist of:


 creating classes
creating public, protected and private functions &#038; variables
creating objects (instances of classes)
using/calling other [...]]]></description>
			<content:encoded><![CDATA[<p>This tutorial will be explaining the basics of Object Oriented Programming (OOP) classes. Let&#8217;s start with getting straight the following question:</p>
<h3>What will be explained in this tutorial?</h3>
<p>This tutorial will only explain the basics of OOP programming in PHP which consist of:</p>
<p><strong>
<ul>
<li> creating classes</li>
<li>creating public, protected and private functions &#038; variables</li>
<li>creating objects (instances of classes)</li>
<li>using/calling other variables or functions inside the class</li>
<li>using objects to call to functions or variables of the class</li>
</ul>
<p></strong></p>
<h3>Why OOP?</h3>
<p>First of all OOP can be, especially when creating huge scripts/projects, much easier to work with ( edit, modify, etc. ), it&#8217;s much more organized. Beside that it also makes use of classes, objects and functions which can make the programming a lot more efficient and fast. Also it offers a lot of (extra) features.</p>
<h3>OOP &#8211; what&#8217;s it?</h3>
<p>OOP is based on using objects created by classes. These classes can contain properties ( constants, variables ) and methods ( functions ). Let&#8217;s start with the classes of OOP and how to create them.</p>
<h3>Classes &#038; Objects</h3>
<p>As mentioned above OOP uses classes which create the final &#8216;object&#8217;. To create a class we use the keywords <strong>class</strong>. This is how we create a basic class:</p>
<pre name="code" class="php:nogutter">
class MyBasicClass {

  //... what should this class be cappable of - do?

}
</pre>
<p>You see the class we create starts with the keyword <strong>class </strong>followed by the name of the class we create. Then we put everything of the class between { and }. What we&#8217;re going to put here is what this class should be cappable of &#8211; what should it be able to do? We could for example make it show a welcome message which however is rather useless but just to give an idea of how it works. To do so, we need to create a function inside the class. Let&#8217;s call the function &#8217;sayHello&#8217;.</p>
<pre name="code" class="php:nogutter">
class MyBasicClass {

  //... what should this class be cappable of - do?
  // say hello!

  public function sayHello() {
       echo "Hello! Welcome to my website!";
  }

}
</pre>
<p>When it comes to creating functions or properties for a class, you have the choice of making it either a <strong>public </strong>, <strong>protected </strong>or <strong>private </strong>function or property. We made this function a public function so we can access  it outside the class ( call it from an object ).</p>
<p><strong>Public</strong><br />
Public functions or properties are accessable inside the class and parent classes but also outside the class (via/by object).</p>
<p><strong>Protected</strong><br />
Protected functions or properties are only accessable inside the class and parent classes and not outside the class itself.</p>
<p><strong>Private</strong><br />
Private functions or properties are only accessable inside the class itself and not by parent classes or objects.</p>
<p>Now we have created the class, but haven&#8217;t created the object, an instance of the class, yet. To do this we create a variable object and use the new keyword to create an instance of the class, the object.</p>
<pre name="code" class="php:nogutter">
$myObject = new MyBasicClass();
</pre>
<p>Now we created an instance of the class &#8216;MyBasicClass&#8217; as an object &#8216;$myObject&#8217;. Do remember to put the creation of the class above this so an instance can be created of it. Otherwise it won&#8217;t find the class initialized and return an error.</p>
<p>Remember we made the function &#8217;sayHello&#8217; as a public function. So we should be able to access it outside the class using the object (instance of the class) we just created in $myObject. To do this we use the symbol ->.</p>
<pre name="code" class="php:nogutter">
$myObject = new MyBasicClass();

$myObject->sayHello(); //say hello to the world!
</pre>
<p>This makes it call the public function &#8217;sayHello&#8217;. Let&#8217;s put it together so you can see how the real script looks like:</p>
<pre name="code" class="php:nogutter">
&lt;php

class MyBasicClass {

  //... what should this class be cappable of - do?
  // say hello!

  public function sayHello() {
       echo "Hello! Welcome to my website!";
  }

}

$myObject = new MyBasicClass();

$myObject->sayHello(); //say hello to the world!

?>
</pre>
<p>This will output:</p>
<blockquote><p>
Hello! Welcome to my website!</p></blockquote>
<p><strong>Note:</strong> However in most cases classes are created within a seperated file ( usually called something like: classname.class.php ) and included anywhere above the part where it creates the object. Usually just in the top/header.</p>
<p>Creating a variable inside the class can be done in exactly the same way as creating a function. We can again make it either public, protected or private.</p>
<p><strong>Example:</strong></p>
<pre name="code" class="php:nogutter">
class MyBasicClass {

  //... what should this class be cappable of - do?
  // say hello!

  private $message = "Hello! Welcome to my website!";

  public function sayHello() {
       //show the message set in $message
  }

}
</pre>
<p>We here created a private variable &#8216;$message&#8217; which so will only be accessable inside the class, which is the only way we&#8217;ll need to use it. Now we want the function sayHello to show the message we just set. Therefore we&#8217;ll need to use the variables of the function, to be specific: the variable called &#8216;message&#8217; ( which we just created ). Accessing variables of the same class inside the class can be done like this:</p>
<pre name="code" class="php:nogutter">
$this->variable_name
</pre>
<p>So in our case:</p>
<pre name="code" class="php:nogutter">
$this->message
</pre>
<p>It&#8217;s just the way to access variables of its own class. So let&#8217;s use this to show the welcome message inside the function &#8217;sayHello&#8217;:</p>
<pre name="code" class="php:nogutter">
class MyBasicClass {

  //... what should this class be cappable of - do?
  // say hello!

  private $message = "Hello! Welcome to my website!";

  public function sayHello() {
       echo $this->message;
  }

}
</pre>
<p>This will output exactly the same as the previous class function if we create an instance object of it again and call for (execute) the function again. But we won&#8217;t do this again, it&#8217;s just the same way as done above ( creating an instance object of the class, then calling the function sayHello ).</p>
<p>We might want to be able to set the value of the welcome message (variable &#8216;message&#8217;) outside of the class, when creating an instance object of the class. So we could have multiple instances with each showing different welcome messages for example. We&#8217;ll use the default __construct function to do this, which will require the user to set variables for the class when creating the object (instance).</p>
<pre name="code" class="php:nogutter">
  public function __construct($variable1, $variable2, $optionalVariable3 = NULL) {

  }
</pre>
<p>It obviously needs to be a public function as it needs to be accessed automaticly when creating a new instance of the class. The variables that need to be given a value to is put between the brackets. In this example there&#8217;s one optional variable ( $optionalVariable3 ) which has been given a default value ( NULL ). So for that variable no other value is REQUIRED to be given, but optional. However in our case we only need to construct ONE variable, the variable containing the welcome message: $message. </p>
<pre name="code" class="php:nogutter">
  public function __construct($message) {

  }
</pre>
<p>However the value of $message ( set by the user when creating an instance object of the class ) is now only accessable inside this __construct function. To make it a public variable which is accessable all over the class, we will again use $this->variable_name to create the variable for the whole class:</p>
<pre name="code" class="php:nogutter">
  public function __construct($message) {

      $this->message = $message; //set the public variable 'message' equal to the value of $message
      //as public variables can be accessed inside the whole class atleast

  }
</pre>
<p>Let&#8217;s put it inside our previous class. So replace the $this->message variable with this construct function which sets it equal to the value given by the user when creating an object instance of the class.</p>
<pre name="code" class="php:nogutter">
class MyBasicClass {

  //... what should this class be cappable of - do?
  // say hello!

  public function __construct($message) {

      $this->message = $message; //set the public variable 'message' equal to the value of $message
      //as public variables can be accessed inside the whole class atleast

  }

  public function sayHello() {
       echo $this->message;
  }

}
</pre>
<p>Now we could create an object, instance of the class and set the welcome message to show:</p>
<pre name="code" class="php:nogutter">
$myObject = new MyBasicClass("Example welcome message!");
</pre>
<p>And again use the -> symbol to call the function that shows the welcome message ( function &#8217;sayHello&#8217; ):</p>
<pre name="code" class="php:nogutter">
$myObject = new MyBasicClass("Example welcome message!");
$myObject->sayHello();
</pre>
<p>Let&#8217;s put it all together:</p>
<pre name="code" class="php:nogutter">
&lt;?php

class MyBasicClass {

  //... what should this class be cappable of - do?
  // say hello!

  public function __construct($message) {

      $this->message = $message; //set the public variable 'message' equal to the value of $message
      //as public variables can be accessed inside the whole class atleast

  }

  public function sayHello() {
       echo $this->message;
  }

}

$myObject = new MyBasicClass("Example welcome message!");
$myObject->sayHello();

?>
</pre>
<p>Instead of using the __construct function, the variable could as well be set as an argrument of the &#8217;sayHello&#8217; function itself. In that case you would need to set the welcome message when calling the function ( $myObject->sayHello(&#8220;welcome message&#8221;) ) instead of when creating the object.</p>
<h3>Conclusion</h3>
<p>So now we&#8217;re able to create a class, create (public, protected and private) functions and properties, construct a class so it&#8217;s constructable/modifieable/configurable outside the class (when creating the object), create an instance of the class and call functions and properties of the class using the object (instance of the class).</p>
<h3>What&#8217;s next?</h3>
<p>Play arround with creating objects, classes, methods and properties and try to think of useful and efficient ways to use them. If you don&#8217;t really have a clue yet on the use of them ( examples ), no worries: more tutorials will follow with <strong>useful examples</strong> of the use of classes and a tutorial further continueing on extending classes and creating more advanced classes as well, soon. An example of a very good use of classes would be to create a template system like Smorty e.g. which requires functions to set template to load, module to load, macros, etc., so classes would come very handy here. A tutorial on creating a basic template system will be written and posted as well for who&#8217;s interested.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/object-oriented-programming-basics/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>File Upload</title>
		<link>http://www.webcodez.net/php-mysql/file-upload/</link>
		<comments>http://www.webcodez.net/php-mysql/file-upload/#comments</comments>
		<pubDate>Sat, 06 Feb 2010 11:17:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[Encrypted]]></category>
		<category><![CDATA[File Handling]]></category>
		<category><![CDATA[Files]]></category>
		<category><![CDATA[Forms]]></category>
		<category><![CDATA[net script]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Upload]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=285</guid>
		<description><![CDATA[In this tutorial we&#8217;ll be creating a basic File Upload System. This tutorial only requires you (preferably) to have a basic understanding about PHP variables and loops. Although, some pre-knowledge about PHP arrays wouldn&#8217;t hurt either!
Overview
Let&#8217;s start with having a look at the functions that will be explained in this tutorial and so our file [...]]]></description>
			<content:encoded><![CDATA[<p>In this tutorial we&#8217;ll be creating a basic File Upload System. This tutorial only requires you (preferably) to have a basic understanding about PHP variables and loops. Although, some pre-knowledge about PHP arrays wouldn&#8217;t hurt either!</p>
<h3>Overview</h3>
<p>Let&#8217;s start with having a look at the functions that will be explained in this tutorial and so our file upload system will be cappable of:</p>
<p>- Upload form<br />
- Uploading files to a specific directory<br />
- Set max file size for upload files<br />
- Limit uploadable files by specific file extension<br />
- Retrieve error message &#038; handling<br />
- Check whether file doesn&#8217;t already exists</p>
<h3> Upload Form </h3>
<p>We&#8217;ll start off with creating a upload form for our file upload system. File upload systems often use the <strong>POST </strong>method for this form which is a common way of submitting data using forms. The action of the form is set to the file that will handle the uploading, which will be done in the same file: &#8220;upload.php&#8221;. One last thing that we&#8217;ll need to set for our form is the enctype attribute which we set to &#8220;multipart/form-data&#8221;. This will basicly enable us to upload files and handle them.</p>
<pre name="code" class="php:nogutter">
<form method="POST" action="upload.php" enctype="multipart/form-data">
... upload form fields ...
</form>
</pre>
<p>Allright, now we ll be adding the fields to the form. Which are the &#8217;select upload file&#8217; input field and the &#8217;submit&#8217; button. Let&#8217;s start with the &#8217;select upload file&#8217; input field. This input field allows the user to pick a file to upload. It can be created by creating a normal input field in which you set the type equal to &#8216;file&#8217;. This will make it a common file select input field in which the user can select a file from his computer to upload. Give it any name you like but remember we&#8217;ll need the name of the input field later to retrieve the file selected by the user ( and all data related to it ). Here I gave it the name &#8216;uploadfile&#8217;.</p>
<pre name="code" class="php:nogutter">
<form method="POST" action="upload.php" enctype="multipart/form-data">
<input type="file" name="uploadfile">
</form>
</pre>
<p>The second input field we&#8217;ll be adding is the submit button. Which we can create by adding a normal input field with as type set to &#8217;submit&#8217;. The value of this input field will be shown as text on the button. Also don&#8217;t forget to set a name for this input field ( submit button ) as otherwise no POST data will be send which <em>is</em> required to check if the form was submitted.</p>
<p><strong>File: upload.php</strong></p>
<pre name="code" class="php:nogutter">
<form method="POST" action="upload.php" enctype="multipart/form-data">
<input type="file" name="uploadfile">
<input type="submit" name="submit" value="Upload File">
</form>
</pre>
<p>That&#8217;s it, our basic file upload form. However notice that we&#8217;ll be editing it later by adding more input fields to it which allow us to set more limitations or use more features of file handling system.</p>
<h3>File Upload Handling</h3>
<p>Okay, so we&#8217;ve now got our basic file uploading form in which the user can select a file to upload and submit it. But obviously this doesn&#8217;t do the job of actually uploading the file selected by the user. Therefore we&#8217;ll need to use some PHP functions, handle the uploading process. All info we need about the user selected upload file and the process of submiting it can be found inside the array variable <strong>$_FILES['file_inputfield_name']</strong>. And as in the example we gave the &#8216;file&#8217; input field the name &#8216;uploadfile&#8217;, we can find all file data in <strong>$_FILES['uploadfile']</strong>. So what data can be found inside? Here&#8217;s a basic list of the sub-variables we&#8217;ll be using:</p>
<p>[TABLE=3]</p>
<p>The first thing we want to do is check whether any error occured already while &#8217;submitting&#8217; the file (through form). To do this we&#8217;ll check the &#8216;error&#8217; subvariable which is stored in $_FILES['uploadfile']['error'] assuming the upload file input field is given the name &#8216;uploadfile . You can as well see this in the table above. When no errors have occured, this variable should contain the numeric value &#8216;0&#8242;. So to check if any errors occured we simply check it with an if loop:</p>
<pre name="code" class="php:nogutter">
&lt;?php
if($_FILES['uploadfile']['error'] > 0) {

    echo "Error occured!";

}else{

    //... no error occured - upload the file! ...

}
?>
</pre>
<p>This needs to be checked once the file has been ( attempted to be ) submitted. This can be checked by checking the array variable $_POST. As we used the method &#8216;POST&#8217; for submitting the form data. Which means that, once the form has been submitted, all data will go inside the $_POST array variable. So we simply check if this is the case by using the empty function to check whether it&#8217;s empty. We put a ! before it to check if it is NOT empty ( so if the form has been submitted ).</p>
<pre name="code" class="php:nogutter">
&lt;?php
if(!empty($_POST)) {

    if($_FILES['uploadfile']['error'] > 0) {

          echo "Error occured!";

    }else{

          //... no error occured - upload the file! ...

    }

}
?>
</pre>
<p>Let&#8217;s put it together with the form:</p>
<p><strong>File: upload.php</strong></p>
<pre name="code" class="php:nogutter">
<form method="POST" action="upload.php" enctype="multipart/form-data">
<input type="file" name="uploadfile">
<input type="submit" name="submit" value="Upload File">
</form>

&lt;?php
if(!empty($_POST)) {

    if($_FILES['uploadfile']['error'] > 0) {

          echo "Error occured!";

    }else{

          //... no error occured - upload the file! ...

    }

}
?>
</pre>
<p>Now we&#8217;re heading to the part of processing the uploading of the file. Therefore we can use a simple function <strong>move_uploaded_file</strong>. Which, when we put it in a loop, does 2 things for us: checking whether the file could be uploaded to a temporary directory AND ( if so ) move the uploaded file to our set directory. So it will require us to set 2 argruments for it, the <strong>upload file</strong> and the <strong>path </strong>to move the uploaded file to. The path will need to include the name of the file too ($_FILES['uploadfile']['name'])!</p>
<pre name="code" class="php:nogutter">
$path = "uploads/".$_FILES['uploadfile']['name'];
</pre>
<p>We create a variable $path which we put the path for the upload file to be moved to, into. We set it to &#8216;uploads/uploadfile_name&#8217; but you can set it to any directory you like the upload file to be placed into.</p>
<p>Now, the function to actually move the uploaded file to this path looks like this:</p>
<pre name="code" class="php:nogutter">
move_uploaded_file($_FILES['uploadfile']['tmp_name'], $path);
</pre>
<p>As the $_FILES['uploadfile']['tmp_name'] is the path of the temporary location in which the upload file was automaticly uploaded into and the $path variable contains the path that it needs to be moved to.</p>
<p>And inside a loop:</p>
<pre name="code" class="php:nogutter">
if(move_uploaded_file($_FILES['uploadfile']['tmp_name'], $path)) {

    //... file successfully uploaded and moved to the path set in $path

}else{

   //... could not move uploaded file to path set in $path

}
</pre>
<p>Let&#8217;s put it inside our script:</p>
<p><strong>File: upload.php</strong></p>
<pre name="code" class="php:nogutter">
<form method="POST" action="upload.php" enctype="multipart/form-data">
<input type="file" name="uploadfile">
<input type="submit" name="submit" value="Upload File">
</form>

&lt;?php
if(!empty($_POST)) {

    if($_FILES['uploadfile']['error'] > 0) {

          echo "Error occured!";

    }else{

          //... no error occured - upload the file! ...

          //>>>>HERE<<<<<

          $path = "uploads/".$_FILES['uploadfile']['name'];

          if(move_uploaded_file($_FILES['uploadfile']['tmp_name'], $path)) {

               //... file successfully uploaded and moved to the path set in $path
               echo "File &lt;b>
                   ".$_FILES['uploadfile']['name']."&lt;/b>
                    successfully uploaded to ".$path;

          }else{

              //... could not move uploaded file to path set in $path
              echo "Error - could not move uploaded file to {$path}!";

          }

    }

}
?>
</pre>
<p>We put it in the second loop which checks if there were any errors ( remember? ) and we put it in the else part which is executed when no errors were found. As in that case the file was successfully submitted and uploaded to temporary path, and needs to be uploaded/moved to the definitive path.</p>
<h3>Max File Size</h3>
<p>For adding a max file size we could either do this inside the<strong> php.ini</strong> file (find MAX_FILE_SIZE) or by adding another input field to the form. You could even make another loop to check if the max file size was not exceeded (check $_FILES['uploadfile']['size'] to check ). However we&#8217;ll be using the second method: we&#8217;ll add another input field to the file upload form. This input field needs to be hidden as it just sets a value, and is not litterally an <strong>input </strong>field. We need to set the name of the input field equal to &#8216;MAX_FILE_SIZE&#8217; so the system will recognize it as the input field containing the max file size for the upload file.</p>
<pre name="code" class="php:nogutter">
<input type="hidden" name="MAX_FILE_SIZE" value="1048576">
</pre>
<p>The type of the field is set to &#8216;hidden&#8217; as mentioned above already. The name to &#8216;MAX_FILE_SIZE&#8217;, also as mentioned above and the value to &#8216;1048576&#8242; BYTES, which is equal to 1 MB (1024 bytes = 1 KB, 1024 KB = 1 MB => 1 MB = 1024 BYTES * 1024 = 1048576 BYTES  (1 MB) ).</p>
<p>Add it to the form with the other input fields and &#8230;             &lt;b>DONE!&lt;/b></p>
<p><strong>File: upload.php</strong></p>
<pre name="code" class="php:nogutter">
<form method="POST" action="upload.php" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="1048576">
<input type="file" name="uploadfile">
<input type="submit" name="submit" value="Upload File">
</form>

&lt;?php
if(!empty($_POST)) {

    if($_FILES['uploadfile']['error'] > 0) {

          echo "Error occured!";

    }else{

          //... no error occured - upload the file! ...

          //>>>>HERE<<<<<

          $path = "uploads/".$_FILES['uploadfile']['name'];

          if(move_uploaded_file($_FILES['uploadfile']['tmp_name'], $path)) {

               //... file successfully uploaded and moved to the path set in $path
               echo "File &lt;b>
                   ".$_FILES['uploadfile']['name']."&lt;/b>
                    successfully uploaded to ".$path;

          }else{

              //... could not move uploaded file to path set in $path
              echo "Error - could not move uploaded file to {$path}!";

          }

    }

}
?>
</pre>
<h3> Upload File Extensions </h3>
<p>Now we&#8217;ll be creating another loop to check whether the extension of the uploaded file is allowed by us. In this example we&#8217;ll allow a couple of image types (jpg, jpeg, gif, png and bmp) but make it anything you want to allow upload files of. The extension of the upload file is set in $_FILES['uploadfile']['type'] as explained in the beginning of this tutorial inside the table, list. We&#8217;ll use a simple pattern to check if the file type, extension, is any of these images. If you aren&#8217;t familiar with php patterns either skip this part, use a regular if loop or have a look at the tutorial about <a href="http://www.webcodez.net/php-mysql/user-input-validation/">user input validation</a>.</p>
<pre name="code" class="php:nogutter">
/^image\/(jpg|jpeg|gif|png|bmp)$/
</pre>
<p>The file type should start with &#8216;image/&#8217; all image files are given the file type value &#8216;image/extension&#8217; (where extension is any of jpg, jpeg, gif, etc. ). We allow a collection of file types: jpg or jpeg or gif or png or bmp &#8211; the file may contain any of these. They&#8217;re seperated by a | to indicate the file type may be ANY of these ( one ). You could as well just allow ALL image extensions. The pattern would then look like this:</p>
<pre name="code" class="php:nogutter">
/^image\/(.*)$/
</pre>
<p>As all images get the file extension starting with &#8216;image/&#8217;<any image extension>.</p>
<p>We put it inside a regular if loop and use the preg_match function to check whether the pattern matched with the upload file extension.<br />
Notice the file extension is set in $_FILES['uploadfile']['type'] and that we use the function <strong>strtolower</strong> so that for example<br />
JPEG would become jpeg. So it won&#8217;t make any difference for capital letters &#8211; match the pattern as well as they&#8217;re converted to non-capital (lower) letters ).</p>
<pre name="code" class="php:nogutter">
$pattern_filetypes = "/^image\/(jpg|jpeg|gif|png|bmp)$/";
if(preg_match($pattern_filetypes, strtolower($_FILES['uploadfile']['type']))) {

     //matched the pattern -> file type is allowed

}else{

   //didn't match the pattern -> file type is not allowed

}
</pre>
<p>Put the pattern for the filetypes that are allowed inside a variable to make it easier readable and editable.</p>
<p>So, where do we put this inside our total script? It should be in the first loop atleast, as that&#8217;s where all the file handling takes place ( when the form was submitted ). The second loop inside that one, of our whole script checks, checks if there are any errors. It should be in the else part of that loop as that else part is executed when no errors were found. And then it will need to check the file type, and if that&#8217;s correct as well, it will execute the file uploading stuff:</p>
<p><strong>File: upload.php</strong></p>
<pre name="code" class="php:nogutter">
<form method="POST" action="upload.php" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="1048576">
<input type="file" name="uploadfile">
<input type="submit" name="submit" value="Upload File">
</form>

&lt;?php
if(!empty($_POST)) {

    if($_FILES['uploadfile']['error'] > 0) {

          echo "Error occured!";

    }else{

          //... no error occured - upload the file! ...

          //>>>>HERE<<<<<

          $pattern_filetypes = "/^image\/(jpg|jpeg|gif|png|bmp)$/";
          if(preg_match($pattern_filetypes, strtolower($_FILES['uploadfile']['type']))) {

               //matched the pattern -> file type is allowed

               //Put the file handling script here (moved from below)

         $path = "uploads/".$_FILES['uploadfile']['name'];

          if(move_uploaded_file($_FILES['uploadfile']['tmp_name'], $path)) {

               //... file successfully uploaded and moved to the path set in $path
               echo "File &lt;b>
                   ".$_FILES['uploadfile']['name']."&lt;/b>
                    successfully uploaded to ".$path;

          }else{

              //... could not move uploaded file to path set in $path
              echo "Error - could not move uploaded file to {$path}!";

          }

          }else{

              //didn't match the pattern -> file type is not allowed

             echo "Error - file type not allowed!";
         }

    }

}
?>
</pre>
<h3> Retrieve errors &#038; Handling </h3>
<p>Now that we&#8217;ve got our file upload system work, we do want to be able to tell the user WHAT error occured if any. As now it just showed an error message if any error occured. Let&#8217;s have a closer look on that part again, pick it out of our script for a sec:</p>
<pre name="code" class="php:nogutter">

    if($_FILES['uploadfile']['error'] > 0) {

          echo "Error occured!";
</pre>
<p>When $_FILES['uploadfile']['error'] contains a value greater than 0, an error has occured. But what error occured can be told by checking the value ( number ) of $_FILES['uploadfile']['error'] which contains the number of the error occured. Here&#8217;s a list of what error each number represents:</p>
<p>[TABLE=5]</p>
<p>As you can see all numbers greater than 0 indicate an error ( we checked it correctly in the if loop: $_FILES['uploadfile']['error'] > 0 ). Now we&#8217;re going to create a switch loop which checks WHICH of the errors occured. We&#8217;ll be using the data from the table above:</p>
<pre name="code" class="php:nogutter">
switch($_FILES['uploadfile']['error']) {

         case 1:
         echo "Max file size exceeded";
         break;

         case 2:
         echo "Max file size exceeded";
         break;

         case 3:
         echo "File was only partially uploaded";
         break;

         case 4:
         echo "File was not uploaded";
         break;

         case 5:
         echo "Missing temp directory";
         break;

         case 6:
         echo "Could not write file to disk";
         break;

         case 7:
         echo "Upload stopped by file extension";
         break;

}
</pre>
<p>Think that&#8217;s quite straight forward. It checks which error number occured ( value of $_FILES['uploadfile']['error']) and for each number it shows the corresponding error message. Let&#8217;s put it all together!</p>
<p><strong>File: upload.php</strong></p>
<pre name="code" class="php:nogutter">
<form method="POST" action="upload.php" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="1048576">
<input type="file" name="uploadfile">
<input type="submit" name="submit" value="Upload File">
</form>

&lt;?php
if(!empty($_POST)) {

    if($_FILES['uploadfile']['error'] > 0) {

          echo "Error occured - ";

         //>>>HERE<<<
         //which error occured?

         switch($_FILES['uploadfile']['error']) {

               case 1:
               echo "Max file size exceeded";
               break;

               case 2:
               echo "Max file size exceeded";
               break;

               case 3:
               echo "File was only partially uploaded";
               break;

               case 4:
               echo "File was not uploaded";
               break;

               case 5:
               echo "Missing temp directory";
               break;

               case 6:
               echo "Could not write file to disk";
               break;

              case 7:
              echo "Upload stopped by file extension";
              break;

        }

    }else{

          //... no error occured - upload the file! ...

          $pattern_filetypes = "/^image\/(jpg|jpeg|gif|png|bmp)$/";
          if(preg_match($pattern_filetypes, strtolower($_FILES['uploadfile']['type']))) {

               //matched the pattern -> file type is allowed

               //Put the file handling script here (moved from below)

         $path = "uploads/".$_FILES['uploadfile']['name'];

          if(move_uploaded_file($_FILES['uploadfile']['tmp_name'], $path)) {

               //... file successfully uploaded and moved to the path set in $path
               echo "File &lt;b>
                   ".$_FILES['uploadfile']['name']."&lt;/b>
                    successfully uploaded to ".$path;

          }else{

              //... could not move uploaded file to path set in $path
              echo "Error - could not move uploaded file to {$path}!";

          }

          }else{

              //didn't match the pattern -> file type is not allowed

             echo "Error - file type not allowed!";
         }

    }

}
?>
</pre>
<h3> File Exists Check </h3>
<p>Now one last thing we might want to do is check whether the uploaded file doesn&#8217;t already exist. We can simply use the function<strong> file_exists</strong> to do this.</p>
<pre name="code" class="php:nogutter">
if(file_exists('file/path/')) {

    // file exists

}else{

   // file doesn't exist

}
</pre>
<p>So in our case the path would be $path ( remember?). As we earlier set $path equal to:</p>
<pre name="code" class="php:nogutter">

         $path = "uploads/".$_FILES['uploadfile']['name'];
</pre>
<p>Which is the path for the file to be uploaded to. But we first want to check if the file already exists in there, so we use the file_exists function.</p>
<pre name="code" class="php:nogutter">
if(file_exists($path)) {

    // file exists
    echo "File already exists!";

}else{

   // file doesn't exist - continue uploading

}
</pre>
<p>We put it in the script right after the part where the $path is set ( which is in the loop where it starts uploading the file ):</p>
<p><strong>File: upload.php</strong></p>
<pre name="code" class="php:nogutter">
<form method="POST" action="upload.php" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="1048576">
<input type="file" name="uploadfile">
<input type="submit" name="submit" value="Upload File">
</form>

&lt;?php
if(!empty($_POST)) {

    if($_FILES['uploadfile']['error'] > 0) {

          echo "Error occured - ";

         switch($_FILES['uploadfile']['error']) {

               case 1:
               echo "Max file size exceeded";
               break;

               case 2:
               echo "Max file size exceeded";
               break;

               case 3:
               echo "File was only partially uploaded";
               break;

               case 4:
               echo "File was not uploaded";
               break;

               case 5:
               echo "Missing temp directory";
               break;

               case 6:
               echo "Could not write file to disk";
               break;

              case 7:
              echo "Upload stopped by file extension";
              break;

        }

    }else{

          //... no error occured - upload the file! ...

          $pattern_filetypes = "/^image\/(jpg|jpeg|gif|png|bmp)$/";
          if(preg_match($pattern_filetypes, strtolower($_FILES['uploadfile']['type']))) {

               //matched the pattern -> file type is allowed

               //Put the file handling script here (moved from below)

         $path = "uploads/".$_FILES['uploadfile']['name'];

//>>>HERE<<<

if(file_exists($path)) {

    //file exists

    echo "File already exists!";

}else{

   //file doesn't exist - continue uploading

          if(move_uploaded_file($_FILES['uploadfile']['tmp_name'], $path)) {

               //... file successfully uploaded and moved to the path set in $path
               echo "File &lt;b>
                   ".$_FILES['uploadfile']['name']."&lt;/b>
                    successfully uploaded to ".$path;

          }else{

              //... could not move uploaded file to path set in $path
              echo "Error - could not move uploaded file to {$path}!";

          }

}

          }else{

              //didn't match the pattern -> file type is not allowed

             echo "Error - file type not allowed!";
         }

    }

}
?>
</pre>
<h3>Done!</h3>
<p>And that&#8217;s our final script! Hope you learnt something and have fun uploading <img src='http://www.webcodez.net/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> .</p>
<h3>Modification Suggestions</h3>
<p>&lt;b>Change the path to url&lt;/b><br />
As with this file uploading system we let it show the relative PATH to the file, we could also make it show the url to the file uploaded. To do this you need to change this part of the script:</p>
<pre name="code" class="php:nogutter">
               //... file successfully uploaded and moved to the path set in $path
               echo "File &lt;b>".$_FILES['uploadfile']['name']."&lt;/b> successfully uploaded to ".$path;
</pre>
<p>That&#8217;s where it shows the file being successfully uploaded -message. You see it shows the path which is set in $path. To make it show the URL, just create another variable for example like this:</p>
<pre name="code" class="php:nogutter">
      $website_url = "http://mywebsite.com/directory_of_this_file"; /* url to the directory of this file (not the file itself) - for example: http://mywebsite.com/ or http://www.mywebsite.com/upload/ ) */
      $file_url = $website_url."/".$path;
</pre>
<p>We created the variable $file_url which holds the url to your site / the path to the upload file which is the total url to the uploaded file.</p>
<pre name="code" class="php:nogutter">
               //... file successfully uploaded and moved to the path set in $path

               $website_url = "http://mywebsite.com/directory_of_this_file";
               $file_url = $website_url."/".$path;

               echo "File &lt;b>".$_FILES['uploadfile']['name']."&lt;/b> successfully uploaded to <a href='".$file_url."'>".$file_url."</a>";
</pre>
<p>Cheers,<br />
Admin.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/file-upload/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Backlinks Checker Script</title>
		<link>http://www.webcodez.net/scripts-snippets/backlinks-checker-script/</link>
		<comments>http://www.webcodez.net/scripts-snippets/backlinks-checker-script/#comments</comments>
		<pubDate>Thu, 04 Feb 2010 15:34:44 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Scripts & Snippets]]></category>
		<category><![CDATA[backlinks]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[net script]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[snippet]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=280</guid>
		<description><![CDATA[This small php code snippet I wrote can be used in several ways. For example to get all backlinks to a certain website from a list of websites. This list of websites should be put in websites.txt file with one website per line. It could as well be used to check whether, a link to [...]]]></description>
			<content:encoded><![CDATA[<p>This small php code snippet I wrote can be used in several ways. For example to get all backlinks to a certain website from a list of websites. This list of websites should be put in websites.txt file with one website per line. It could as well be used to check whether, a link to your website was found/put on a specific website which can be used for reciprocal link requirements e.g.. This is just a small snippet code and can still be optimized. However there are many uses of this script, hope you&#8217;ll enjoy it anyway!</p>
<h3>Script: backlinks_checker.php</h3>
<pre name="code" class="php:nogutter">
&lt;?php

####################################################################
/* backlinks_checker.php                                                               */
/* Author: webcodez.net 							                */
/* Creation Date: 2 February 2010 - 3 February 2010		       */
/* Description: Checks whether a link is on a specific website.    */
/* *Update: Gets all backlinks to a specific website from urls.     */
####################################################################

###################### CONFIG #######################################
$domainsite = "webcodez.net"; //domainname of the website to search backlinks for - example: domainname.com
$urls_file = "urls.txt"; //file containing all urls to check for backlinks on
####################################################################

$domainsite = str_replace(".", "\.", $domainsite);

$urls = array("http://www.webcodez.net/"); //website pages to check backlinks on

//Get urls to check backlinks on
$handle = @fopen($urls_file, "r");
if ($handle) {
    $curr_arr = count($urls);
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);
        //if(file_exists($buffer))
		$urls[$curr_arr] = $buffer;
	  $curr_arr++;
    }
    fclose($handle);
}

$total_urls = 0;

foreach($urls as $key => $addr) {

$urls_cont = file_get_contents($addr);
$pattern = "/(http)(s)?(:\/\/)(www\.|[A-Za-z0-9_-]*\.)?".$domainsite."(\/[A-Za-z0-9-_ .]*)*/ ";
$get = preg_match_all($pattern, $urls_cont, $backlinks);

$catch_backlinks[$key] = $backlinks[0];
$amount_backlinks[$key] = count($catch_backlinks[$key]);

$total_backlinks += $amount_backlinks[$key];

}

echo "&lt;h3> Total Backlinks Found: ".$total_backlinks." &lt;/h3>";

foreach($urls as $key => $addr) {

echo "&lt;p>&lt;b>{$amount_backlinks[$key]} Links to ".stripslashes($domainsite)." found on \"".$addr."\"&lt;/b>&lt;/p>";

foreach($catch_backlinks[$key] as $url) {

	echo "&lt;p>{$url}&lt;/p>";

}

}

?>
</pre>
<h3>How to use?</h3>
<p>Just create a &#8216;urls.txt&#8217; in which you put all websites on which you want to check backlinks to your/any website on. Take one line per url. Then inside the script replace &#8216;webcodez.net&#8217; with your own website or the domain of the website you want to check backlinks of.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/scripts-snippets/backlinks-checker-script/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>User Input Validation (Part 2) Examples</title>
		<link>http://www.webcodez.net/php-mysql/user-input-validation-examples-1/</link>
		<comments>http://www.webcodez.net/php-mysql/user-input-validation-examples-1/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 10:26:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[net script]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[preg_match]]></category>
		<category><![CDATA[regular expressions]]></category>
		<category><![CDATA[user input validation]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=248</guid>
		<description><![CDATA[In the previous tutorial on user input validation the basics about user input validation were explained. This tutorial will require you to have a basic knowledge about user input validations (php patterns), if you don&#8217;t know about php patterns yet I&#8217;d advice you to first have a look at the previous tutorial about user input [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://www.webcodez.net/php-mysql/user-input-validation/">previous tutorial on user input validation</a> the basics about user input validation were explained. This tutorial will require you to have a basic knowledge about user input validations (php patterns), if you don&#8217;t know about php patterns yet I&#8217;d advice you to first have a look at the previous tutorial about <a href="http://www.webcodez.net/php-mysql/user-input-validation/">user input validation</a>. In this tutorial a couple of examples of user input validation patterns will be given and explained. The patterns explained in this tutorial are for: <strong>email </strong>and <strong>website address (url)</strong> user input validations.</p>
<h2>Use of all patterns</h2>
<p>All patterns explained in this tutorial can be used by using the <strong>preg_match </strong>function, for example using an if loop:</p>
<pre name="code" class="php:nogutter">
//$value = $_POST['input_field_name']; for example
if(preg_match("/pattern/", $value))
   //matched
else
  //did not match
</pre>
<h3>Email Validation</h3>
<p>To validate a user input for an email, to check whether it&#8217;s a valid email, can be done in several ways. Here I&#8217;ll be showing 2 ways to validate an email. To create a pattern for validating an email you&#8217;ll first need to think of how an email can look like ( structure ). Which is:</p>
<blockquote><p>email_name@email_provider.lang</p></blockquote>
<p>Where &#8216;lang&#8217; can be anything like: com or net or nl ( dutch ), etc.. The &#8216;email_name&#8217; can be anything of any length containing alphabetical characters, numbers or the &#8211; _ symbols. Same goes for the &#8216;email_provider&#8217;. So for validating USA email addresses (.com) for example, we could have a pattern like this:</p>
<p><strong>Pattern:</strong></p>
<pre name="code" class="php:nogutter">
/^[A-Za-z0-9-_.]*@[A-Za-z0-9-_.]*(\.com)$/
</pre>
<p>However this pattern will only allow/match email addresses that end with .com. We could use the | seperator to allow several &#8216;extensions&#8217; for the email ( .com OR .net OR .nl, etc..). That would look like this:</p>
<p><strong>Pattern:</strong></p>
<pre name="code" class="php:nogutter">
/^[A-Za-z0-9-_.]*@[A-Za-z0-9-_.]*(\.com|\.net|\.nl|\.de|\.be|\.co\.uk)$/
</pre>
<p>And you could add all extensions you want to allow for the email address there, seperated by | and don&#8217;t forget to escape the dots (.) with a backslash (\) so it will be treated as a normal character.</p>
<p><strong>Note:</strong> a second way to do this could be to allow all extensions (.com, .net or .anythinghere). To do this just replace the \.com|\.net|etc&#8230; by <em>\.[A-Za-z0-9]*</em> which basicly means: all alphabetical characters and numbers.</p>
<p><strong>Example of use:</strong></p>
<pre name="code" class="php:nogutter">
&lt;?php

$email = "validemail123@validprovider_09.net";

if(preg_match("/^[A-Za-z0-9-_.]*@[A-Za-z0-9-_.]*(\.com|\.net|\.nl|\.de|\.be|\.co\.uk)$/", $email)) {

    echo "&lt;p> Valid email: {$email} &lt;/p>";

}else{

    echo "&lt;p> Invalid email: {$email} &lt;/p>";

}

$email = "invalid' email@invalid,provider}.fpweo";

if(preg_match("/^[A-Za-z0-9-_.]*@[A-Za-z0-9-_.]*(\.com|\.net|\.nl|\.de|\.be|\.co\.uk)$/", $email)) {

    echo "&lt;p> Valid email: {$email} &lt;/p>";

}else{

    echo "&lt;p> Invalid email: {$email} &lt;/p>";

}

?>
</pre>
<p><strong>Output:</strong></p>
<blockquote><p>Valid Email: validemail123@validprovider_09.net</p>
<p>Invalid Email: invalid&#8217; email@invalid,provider}.fpweo</p></blockquote>
<h3>Website Address Validation</h3>
<p>For creating a pattern to validate website adresses (urls) we&#8217;ll have a look at a valid structure of a website address first, which is similar to:</p>
<blockquote><p>http(s)://(www. or subdomain.)websitename.com(/directories)(/page.ext)(?getvar&#038;getvars)</p></blockquote>
<p>Where what&#8217;s between brackets is optionally. The .com can be any other &#8216;extension&#8217; of course (.net or .co.uk, etc.).</p>
<p><strong>Pattern:</strong></p>
<pre name="code" class="php:nogutter">
/^(http)(s)?(:\/\/)(www\.|[A-Za-z0-9_-]*\.)?[A-Za-z0-9_-]*(\.com|\.net|\.co\.uk|\.net)(\/|\/[A-Za-z0-9-_ .]*)*$/
</pre>
<p>This is just an example of a pattern I created that could be used. It may at first look complex but it isn&#8217;t that complex at all if you have a further look into it. Let&#8217;s go through it briefly. Each valid website address starts with &#8216;http&#8217; (^(http)) followed by an optional &#8217;s&#8217; ( (s)? ). After that there&#8217;s a &#8216;://&#8217; which is put inside the pattern as (:\/\/) as all /s need to be escaped by a \. So // becomes \/\/. Then there&#8217;s an optional ( so a ? behind the collection  ) &#8216;www.&#8217; or &#8217;subdomain_name.&#8217; where the subdomain_name can be any alphabetical character or number or _ or &#8211; ([A-Za-z0-9_-]) and any size (* = any amount of characters). The question mark behind this collection ( www. | subdomain. ) defines it may occur one or zero times (that it&#8217;s optional). Then there&#8217;s again the [A-za-z0-9_-] which again means any alphabetical characters or numbers or the _ or &#8211; symbol, which is for the domainname of the website which may contain any of these characters in any length (*). Then it should be followed by any of these &#8216;extensions&#8217; ( \.com|\.net|\.co\.uk|\.net ). Now the rest of the pattern is optional &#8211; there can be anything after the url (after a backslash / ).</p>
<p><strong>Example of use:</strong></p>
<pre name="code" class="php:nogutter">
&lt;?php

$url = "http://www.validurl.net/anypath/anyfile.php?anything";

if(preg_match("/^(http)(s)?(:\/\/)(www\.|[A-Za-z0-9_-]*\.)?[A-Za-z0-9_-]*(\.com|\.net|\.co\.uk|\.net)(\/|\/[A-Za-z0-9-_ .]*)*$/", $url)) {

    echo "&lt;p> Valid url: {$url} &lt;/p>";

}else{

    echo "&lt;p> Invalid url: {$url} &lt;/p>";

}

$url = "http://invalidurl-^.";

if(preg_match("/^(http)(s)?(:\/\/)(www\.|[A-Za-z0-9_-]*\.)?[A-Za-z0-9_-]*(\.com|\.net|\.co\.uk|\.net)(\/|\/[A-Za-z0-9-_ .]*)*$/", $url)) {

    echo "&lt;p> Valid Url: {$url} &lt;/p>";

}else{

    echo "&lt;p> Invalid Url: {$url} &lt;/p>";

}

?>
</pre>
<p><strong>Output:</strong></p>
<blockquote><p>Valid Url: http://www.validurl.net/anypath/anyfile.php?anything</p>
<p>Invalid Url: http://invalidurl-^.</p></blockquote>
<p><strong>Note</strong>: To only allow domain names website addresses without any paths behind it ( like: http://www.google.com ) remove the last part of the pattern between brackets followed by a * ( which is: (\/|\/[A-Za-z0-9-_ .]*)* ) or replace it by (\/)? if you do want to allow a possible ending backslash ( http://www.google.com/ ).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/user-input-validation-examples-1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>HTML paragraph name &#8216;trick&#8217;</title>
		<link>http://www.webcodez.net/html-css/html-paragraph-name-trick/</link>
		<comments>http://www.webcodez.net/html-css/html-paragraph-name-trick/#comments</comments>
		<pubDate>Sat, 30 Jan 2010 12:12:46 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[HTML & CSS]]></category>
		<category><![CDATA[a tag]]></category>
		<category><![CDATA[paragraph]]></category>
		<category><![CDATA[trick]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=228</guid>
		<description><![CDATA[A common use of the a (&#60;a&#62;) tag in HTML would be to make a link ( &#60;a href = &#8220;link&#8221;&#62;link text&#60;/a&#62; ).  However it can as well be used to give a specifc paragraph its own name or ID. If you do this, the paragraph will be automaticly scrolled to when you open your [...]]]></description>
			<content:encoded><![CDATA[<p>A common use of the <strong>a</strong> (&lt;a&gt;) tag in HTML would be to make a link ( &lt;a href = &#8220;link&#8221;&gt;link text&lt;/a&gt; ).  However it can as well be used to give a specifc paragraph its own name or ID. If you do this, the paragraph will be automaticly scrolled to when you open your page url like this: page.html#paragraph_name. Where the &#8216;paragraph_name&#8217; is the name of the paragraph that needs to be scrolled to. This can be very usefully when you&#8217;ve got a very long text and got several paragraphs which you want to be easy accessable through links.</p>
<p><strong>Example:</strong></p>
<pre name="code" class="html:nogutter">&lt;p&gt;&lt;a name="paragraph1"&gt;Paragraph 1&lt;/a&gt;&lt;/p&gt;</a>

some very long text here

&lt;p&gt;&lt;a name="paragraph2"&gt;Paragraph 2&lt;/a&gt;&lt;/p&gt;</a>

another very long text</pre>
<p>In this example we set 2 paragraphs names: paragraph1 and paragraph2. Both are now automaticly scrolled to by adding #paragraph1 or #paragraph2 to the url. However this is of course only usefully when you&#8217;ve got a very long text as mentioned before, where you&#8217;ve got a long scroll bar wherefore it would be easy to have an index page for the article including links to all paragraphs.</p>
<p><strong>Example2:</strong></p>
<pre name="code" class="html:nogutter">&lt;h2&gt;Paragraphs&lt;/h2&gt;
1. &lt;a href='#paragraph1'&gt;Paragraph1&lt;/a&gt; &lt;br /&gt;
2. &lt;a href='#paragraph2'&gt;Paragraph2&lt;/a&gt; &lt;br /&gt;

&lt;p&gt;&lt;a name="paragraph1"&gt;Paragraph 1&lt;/a&gt;&lt;/p&gt;

some very long text here

&lt;p&gt;&lt;a name="paragraph2"&gt;Paragraph 2&lt;/a&gt;&lt;/p&gt;

another very long text</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/html-css/html-paragraph-name-trick/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
