Web-development course

Day 9

Welcome to day9 of PHP in 15 days – Guaranteed Training Course. I am very much excited to talk about some really new and exciting things. Also, I am very happy and satisfied with your progress as you have covered 8 days training sessions successfully of this course and I am sure you have learnt a lot. There are only 5 more days remaining including today of this course. As on day14 and 15 we are going to develop our final project. So, I must say keep it up and try to devote yourself as much as you can as you know “All is well if end is well”.So, today we are going to learn about:

·         File Uploading

·         Introduction To Database (MySQL)





File Uploading:

There are moments when you want your users to upload a file along with other form data. So, in this case you need to create little more functionality in your HTML form as well as in your PHP Code. So, let’s see, how to handle files. So, here this is our previous form we created on day7 in form submission tutorial. I am using this to save our time. Now here we need to add one more thing and that is file uploading button. Let’s create it now. This is also the input field of type file and just give it name ‘img’. Also, let’s put the label to tell the user what it is and that is ‘Attach your snap file: ’. And here we go, we get a button here to browse the system from where we can upload an image file. Let’s try to upload an image file here. Browser your computer and attach one and here you can see the name is displaying here. It means image is now attached with our form. Hit register and oh, its submitting the form data to an unknown file, let’s correct it and submit form data on this same file. Now, to grab this file data we have another super-global and that is $_FILES.



$_Files:

This is another super-global array which stores the data of the file submitted through a form and is available only when the form is submitted containing a file. $_FILES array is a multidimensional array. Main level arraycontains the names of the files you uploadthrough the form and deep level array stores the data for one particular uploaded file. What does it means? It means we can provide our users the option to upload more than one files within one single form. When user uploads two or more than two files through the same form, $_FILES is capable to store the information of all those files. So, what does it do, it stores the names of files in an array as keys and within each value of this first array there starts another array and that stores the data of that particular file.

Here is an example that how this multidimensional array stores the data for multiple files uploaded at the same time through a single form. Just assume that within the form we created two inputs for type i.e. file and the value of first name attribute is ‘img’ and the second one is img2. When the user will submit the form the $_FILES super-global array will be available in this form.

 
 
 
 
$_FILES= array(
'img'=>array(
'name' =>'name of file',
'tmp_name' =>'Temporary Name of File',
'error' =>boolean,
'size' =>100
),
'img2'=>array(
'name' =>'name of file',
'tmp_name' =>'Temporary Name of File',
'error' =>boolean,
'size' =>100
)
);

 

Now, let’s grab the data of our uploaded image file and this will make it clearer to us.

Now here in square brackets like other super-global arrays, let’s just put the name we defined down here in our form and that is ‘img’, just put this in here, which is also an array, let’s ask for the keys in it and the first one is going to be the name which is the original name of the uploaded file. After the file has been uploaded to the server this file is stored on the server temporarily and is given a temporary name. So, we can ask for that name too by using ‘tmp_name’. Next is size of this file and lastly we can check whether any error occurred or not, so it will give us Boolean.

Let’s just echo all of these and put br tags between them and let’s see what output we get.

echo $_FILES['img']['name'];
echo '<br>';
echo $_FILES['img']['tmp_name'];
echo '<br>';
echo $_FILES['img']['size'];
echo '<br>';
echo $_FILES['img']['error'];

 

Let’s get back to the browser, refresh and select a file and here we have selected an image file and hit Register.You can see a lot of errors of undefined index. It means the array data we asked for is undefined or not created yet. So, what might be the problem? Actually everything is OK but we need to define the encryption type of this form. Encryption type attribute defines the response behavior when form is submitted. If we don’t define this attribute, it stays at default encryption type and that is application/x-www-form-urlencoded which is not capable to transfer the files uploaded through the form.So we need to change default encryption type to multipart/form-data and this will easily upload our files to the server. So, let’s define it now.

       enctype="multipart/form-data"

 

So, now we are ready to upload our file. Try it one more time. Refresh the browser, select an image file and there you can see the file has been uploaded successfully.You can see all the information of the uploaded filewe wanted to echo. Let’s put br tags between the information for presenting them line by line. You can see all the information about our uploaded file. This integer value is the size of our file and denoting number of bytes. So, here we have successfully uploaded our file to the server. But it’s on the server and is saved temporarily. Still we need to grab this file and move and save it into some specific directory where we want to store our image files. Like may be images directory. So, we will grab this temporary file and move it to the destination folder on the server.

For this purpose PHP provides a very handy internal function move_uploaded_file(). This function takes two arguments, first is the temporary name with whichfile wassaved on the server temporarily and second argument is the directory name (Directory in which we want to store this file) along with actual file name. So, we just put the variable tmp_name and so called directory ‘dir’ and a variable for the name of the file we want to save this file with.

      move_uploaded_file($tmp_name, ‘dir/’.$name);

 

Now we must create the variables we used in this internal function before making a call to this function. So, here, instead of creating all of these variables one by one, what we can do here is, we can use another internal function ‘EXTACT’. What this function does is, it grabs all the keys of an array and makes them available as variables and assign them their own relevant values from the supplied associative array. So, let’s just use this function and supply the ‘img’ array from $_FILES multidimensional array.

       EXTRACT($_FILES['img']);

 

Now we have everything set up.Just one thing left and that is we need to create the directory. Let’s create an images directory in our day9 directory.

images/

Now just write this directory name here in thisinternal function and concatenate it with name of image. Let’s resend the same information by pressing F5 and our previous uploaded file will be uploaded one more time.

      move_uploaded_file($tmp_name, ‘images/’.$name);

 

Here you can see we get no errors. It means the file has been uploaded tothe server and has moved to the images folder successfully. So, let’s go to the images directory and you can see the file has been stored in this folder successfully. Let’s delete this file and try it one more time. Directory is empty now.Let’s go back to the browser and upload another file. Let’s upload penguins file. Go back to imagesdirectory and here we go, our file has been successfully uploaded.Also you can see it’s stored with the name we used in second argument. One more thing we can do in this code is that we can store the name ofthis destination folder in a variable. Let’s do this. Make a variable‘dir’ and store the destination folder namealong with its path in the variable. Now we can replace it from here and put the variable instead and this gives us a little nicer look.

$dir = ‘images/’;
move_uploaded_file($tmp_name, $dir.$name);

 

Now let’s try one more time to upload another file.Select a file and upload it and here you can see it’s been uploaded successfully.

We can also add some restrictions on the file uploading.We can set the size limit of the file. For this we need to create a conditional statement. If the file size is greater than 100bytes than display error message ‘You can not upload image greater than 100bytes’ and if this happens just die right there.

if($_FILES['img']['size'] >100){
echo 'You cannot upload image greater than 100Bytes.';
die();
}

 

Simple is that. Let’s go back and try this in the browser. And here we go upload a file hit ‘Register’ and you can see the error message ‘You cannot upload image file greater than 100bytes’. You can limit the size according to your requirements.

Now, another thing is error. If any error occurs while uploading file we will echo the message and die the script again. So, same conditional statement again and here we put the error equals to 1, means if some error occurs then echo ‘error while uploading file’ and die.

if($_FILES['img']['error'] == 1){
echo 'Error while uploading file.';
die();
}

 

So, in this way you can direct your users to upload some specific size, type and containing clean content in their files. We have completed one portion of the file uploading and storing it’s details in DB will be covered in our training session where we will work with databases.

Email:

We can send emails directly through PHP. PHP provides a very handy internal function mail() to generate and send emails through our php script. Let’s try to understand how we can use this internal function.

Just write ‘mail’ reserved word to call this internal function. This function takes at least three arguments. Although you can provide 4th argument as well but without providing at least first three arguments this mail function will not work. So, first argument is the email address to whom you want to send email, let’s just put a variable $to here for instance. We’ll just create this variable and assign this an email value to whom we want to send an email. Second argument is the subject of the email. Just put a variable here to $subject. This subject will appear in the email subject line. Third argument is the message and just put $message here too. This is going to hold the content of the email you send. You can provide another argument and that is headers. Let’s just put $headers here. We’ll talk about this in a moment.

Now let’s create these variables and assign values to these. First one is $to. We need to supply the string value and that must be an email address, so, let’s just put here a dummy email address ‘mick@abcdefg.com’. $message is also going to be a string let’s put singles quotes around and between these let’s just put a message and put a semicolon at the end of the line. Now, $subject variable we missed that, let’s create one here and this is going to be a string as well and just write a dummy subject here.

You can use br for line brakes but this mostly don’t work. So, you need to use “\n” instead and this will put a line break within the message text. If you are writing the message within single quotes then you must concatenate this with your message and place this new line within double quotes, so that PHP might parse it correctly.

Now few things about headers. Headers are actually information carriers about language used for the email, encoding which is useful for SMTPs and rendering of the email. This is an optional argument.

You need and should use this argument when you plan to send lots of emails through php script containing formatted messages. Email containing html characters will not be rendered unless you define correct header. Like if you have created your email like a webpage and have used HTML within your email message, so you need to define the content-type and version etc. Also, you declare addresses like From, CC and BCC with their concerned names as well.

Also, when you configure mail server with your script you are in need to set these headers.

For now just keep in mind this internal function i.e. ‘mail’ and supply only first three compulsory arguments. And that’s it, this is all for mail internal function, this script is now ready to send the email to the address we specified here.

For more details on mail() function I recommend you to visit php.net.

 




Introduction to Database:

Databases are actually the information storage houses. We store all the information about our site’s pages, categories, tags, tables’ data, time, duration, links, paths, files and lotsof other stuff. But keep in mind that database is just like a text file which keeps on writing within itself and in its own way. We can explore this information anytime, retrieve any information, edit, delete and update any particular information we want. For this purpose, every database has its own query base with the help of which database administrators can Create, Read, Update and Delete data from its storage (Memory). This manipulation of data is called the CRUD.

Databases are structured. One database can have many tables and every table can have many columns and rows. We create tables and columns on our own and name them as we want. So, how you use your database, it’s all up to you and your requirements. Now let’s take a tour ofMySQLdatabase.We are going to work withthis database, so, let’s just try to explore how it works.

MySQL:

MySQL is a database. We can create databases, tables and fields in MySQL using PHPMyAdmin. PHPMyAdmin is an open source tool developed using PHP and is used to handle MySQL database system through user interface. This tool has made creating databases, tables and manipulation of data whole lot easier than ever before. Through PHPMyAdmin we can run SQL queries to search, add, update and delete data from our database. So, let’s have a look at and try to understand how we can use it.

PHPMyAdmin:

To access PHPMyAdmin make sure that your server that is Apache and MySQLare running. Now, type in address bar localhost/PHPMyAdmin and hit enter. And now you are in PHPMyAdmin interface. Sometimes you might be asked to enter the password. For local host when you set up, WAMP or XAMPP these don’t require you provide one because bydefault you can enter without password and giving the user name ‘root’ only. So, if it happens type in the user name root and let password field empty and click enter or login. Now you are in PHPMyAdmincontrol panel. From here youcan manipulate data, add databases, create tables, columns etc.

You can see this is your local server and address is 127.0.0.1.so keep this address in mind. We will use this or localhost within PHP. Now first thing you might need is to create your first database. For this you can simply click this New button or you can go to databases from here and here you can see the list of all databases you already have created and here is ‘create new database’. Let’s create a database and name it as phpin15days and click this create button. Here we go, our database has been created. You can see it here in the side bar and also in the list of database here. Now we need to enter in this database to do further activities, so, just click on the name of this database and now we are inside our phpin15days database. Don’t let yourself confuse with database word. We use database for the whole program like MySQL, MS SQL, SQL etc. and also we call database where we create tables for storing the information etc.So, now we are in database that is ‘phpin15days’. As this is absolutely new database we just created so, there is nothing inside it. So, it’s prompting us to create a table first. Everything will be stored within tables of the database. Now let’s create our first table and give it a name users. Always name tables relevant to the data you want to store in it. Like if you want a table that will store the information of users, name the table ‘users’ or something that can easily hint you what kind of data is there in this table. So, it’s just the common sense you need to use. Next thing is to decide how many columns you want in this table. You can create more columns for sure but number mentioned here is just an ease of access to create the columns of a table. For now let’s keep it to 6 and click GO button below here or just press enter from your keyboard.

Now on this screen you can see we have 6 fields to fill and these are going to be the columns of our users table. Everything is defined and mentioned with headings and labels here.We just need to fill out some of the fields and change some options. Let’s do it now. Name is the name or label of a column and this should be unique in the whole table. I am going to name this first column ‘userID’, as this column would hold all the users IDs and as we know ids should be integers so, we need to set data-type here and just keep it to its default as INT. This INT means integer.Also, let’s make it Primary and auto-increment. One table can have only one column as primary and primary column is the main identification of any table, just to elaborate. Also, we makethis column auto-increment because we want a unique ‘userID’ for every user registered and table will automatically allot new id to every new user registered. We could’ve defined it unique to make this column unique but auto-increment serves us better than unique and will keep on adding ids on its own. Next column will store the name of users, so, just name it name. You know that name would be a string consisting characters and not integers, so, let’s change INT to VARCHAR.The type VARCHAR means variable characters.You need to select this type according to the data type of the datathat you will store in the column. There are four main types which are used most often and are defined at the top INT, VARCHAR, TEXT and DATE. Below you can find the sub-categories of these types and some others too. So, you can easily select one that suits best to your storing data. Let’s select VARCHAR for now. When you select VARCHAR you need to specify how many characters are going to store in this column.This number will strictly define that you will not be able to store data beyond this character limit. If you try to store data containing characters exceeding this limit will not be stored.Also, when you select VARCHAR the without specifying number of characters your table will not be created. So, again use common sense and guess how many characters a name can have. Let’s keep it to 40 characters for now. Next we need to store the usernames and this column type should set to VARCHAR too and let’s keep it to 20 characters. Next we need to store the password as well, users will set a password and that password will be stored. This can be strange that I will keep this VARCHARof length 64 characters. So, why is this so. We need to hash all the passwords. We will encrypt them and hash them and this way we can hide these from hackers. If something horrible happens and a hacker cracks into our database, still he wouldn’t be unable to guess what the passwords are as because of encryption applied. Another thing we might use to make passwords more secure is using the salt. This is an ad-on, we can put in the passwords to make these more complex to guess. For now, don’t bother what it is. Just assume this as another column going to store a stringof variable characters. Next is joined and this is going to store the date, when the user joined. So, make type of salt VARCHAR and joined as Date. Here if you want to add one more column to this table you can do it from here. Just type in this field how many columns you want to add and click Go button and you get the new row to fill and your previous setting and input data will not lost as well. Finally when you are ready to create this table, just click this SAVE button below here and there you go. Now, it’s showingus an error ‘Please enter a valid length’, it means we missed defining the length of some column of type VARCHAR. Click OK and here you can see we did not supply the length for the column Salt. Let’s just define it to 64. Let’s try to save it one more time. And this time it’s saved. So, we have created our first table successfully using PHPMyAdmin.

Now, here, you can see the table name users. Let’s click on it. And now we are inside our table. Here we get a message, ‘MySQL returned and empty string’. This means there is no data in this table yet and off-course we did not submit or stored any data in this table yet. From these tabs here, we can check the structure by clicking this structure tab. And here you can see all the column names with their structure like, type, primary key, auto increment etc.From here, you can also change setting of any column if you want. Another tab SQL click on it. You can perform any kind of query here.  You can write your own query to do anything with your table and fields. Or you can choose any readymade query by clicking onone of these buttons. Just click one of these and you will get the basic query with accurate syntax. You can also, modify this basic query to suit your own need. Insert, select, update, select all etc. Next thing you can do from here is this search tab options. In this search form you can see all the fields listed with their type. So, you just need to fill any field against its name and it will give the results if found some. Next is insert button. Click it.  Now you can see few forms with the name of columns of users table. From here you can insert data directly to users table. This PHPMyAdmin makes the data insertion whole lot easy.

Next tab is ‘Export’.  This is the thing you will use to take backup of your database or when you want this database somewhere else. This export function will prepare an SQL file and will download it for you. Just keep in mind that when you are within a table and clicks this button, your table will be exported and if you are at database level and not in a table, export button will export the whole database. You just need to click this Go button here and it will be exported. Similarly, Import tab works and imports database or table.If you are in a table you can import only database file for this table only. If you are at database level it will import table or tables, even you can import all the tables for a database. You just need to browse and click the .sql file and then Go.

Now let’s go back to database level and go to the Operations menu from this main menu here. Here you can see different areas with different headings.So, each section has its own unique functionality. Database Comments you can add some comments for this database which help you remember some important things about this database. Next one is create table section and this is the same two columns to create new column as we found in the start of this introduction session today. Next you can rename this database. The database name will be changed to the name you will define here. Sometimes this is very useful when you need to import or export whole database as whenever you import the database within a database, the names of both databases should exactly match. Below this section is a verydangeroussection. Clicking on this button or link will remove or delete your whole database. So, be careful. In next portion, here, you can copy this database. This will create a duplicate copy of this database in which you are right now. You can see there are options right below this so, using this you can define what do you want to copy, whether structure only, structure and data both, data only etc. So, it’s very useful. So, this is the operations menu of PHPMyAdmin which allows you to perform different kind of tasks for your databases.

Let’s go back into our users table. Still you can see operations tab, let’s check it out. Now from here, you can perform different operations on your table also. Here you can see you can move table to another database.  In table options you can rename it, provide comments, change storage engine, which is a different story and other options. Next, you can copy this whole table to another database, so this table will keep intact and another table will be generated in another database you specify and from the options below, you can set according to the needsand copy this table. Below here there is another section and you can see different links here. These are all mainly used to erase the empty rows, optimize table and speed up table. You can click on the question mark besides each link to get more details about what these do and finally these two options in this section. Truncate command will delete all the data from the table and Drop link will simply delete the whole table. So, be careful while using these commands. These are frequently used menu items and options. There is also too much functionality which PHPMyAdmin provides us, but, for now it’s more than enough. Login toPHPMyAdmin and try to understand various options we just discussed, create databases, create tables and try to get familiar with its usage.


Practice files Day #9

         Download 



Related Posts:

Leave a reply

Required fields are marked *

Login to Post Comment