Sunday 30 March 2014

Uploading Files Restricting in php

Uploading Files the Basic we had Seen how to Upload Files Different Types or any file Which is insecure. Now let say you had a website that allow user's to upload images you may want to specify selected amount of file types that you can accept file extension that you want to allow to the user's to upload to your website You need to perform checks. For example i had uploaded .jpg files but i don't wanna allow php file or doc or any other type of file extension.

Code For uploading Files Restricting File In Php

<?php

$name = $_FILES['file']['name'];

$extension = strtolower(substr($name, strpos($name, '.') +1 ));

$size = $_FILES['file']['size'];

$type = $_FILES['file']['type'];



$tmp_name = $_FILES['file']['tmp_name'];



if (isset($name)) {

    if(!empty($name)) {

                   if(($extension=='jpg'||$extension=='jpeg')&&$type='image/jpeg') {

       

                        $location = 'uploads/';

       

                            if(move_uploaded_file($tmp_name, $location.$name)) {

                            echo 'Uploaded!';

                  }else {

                   echo 'There was an error.';

                   }

        

                   }else {

         echo 'File Must Be Jpeg/jpg.';

          }

    }else {

    

     echo 'Please Choose a file.';

    }

}



?>



<form action = "upload.php" method="POST" enctype="multipart/form-data">

<input type="file" name="file"><br><br>

<input type="submit" value="Submit">

</form>

Uploading Files Restricting in Php Output


File Extension in Php
Screenshot1
Uploading Files Restriction In Php
Screenshot2
As Its Uploading Files the basic we had seen uploading files Now Above Code is restricting File Extensions For Restricting File we can Restrict the file type which is uploaded.

So, Here we will check the file type for uploading system in php programming. We can do that will file type property in php programming. 

$type = $_FILES['file']['type'];

If I will Upload image file its type will be image/jpe also in Script we had check whether the file extension with substr function. 

$extension = strtolower(substr($name, strpos($name, '.') +1 ));

We had Two arguments such as $name and the . where we want to take the option and strtolower function will also identify the lower case and if it been in uppercase it will make it to lower case. Here we are using substr and strpos function to find out the extension of the file from the name of the file with extension. We getting out the extension to check whether the extension is in image format. After that we had checks with if else conditions. 

Code for uploading Restricting File Size

<?php

$name = $_FILES['file']['name'];

$extension = strtolower(substr($name, strpos($name, '.') +1 ));

$type = $_FILES['file']['type'];

$size = $_FILES['file']['size'];



$max_size = 2097152;







$tmp_name = $_FILES['file']['tmp_name'];



if (isset($name)) {

   if(!empty($name)) {

                   if(($extension=='jpg'||$extension=='jpeg')&&$type='image/jpeg' && $size<=$max_size)  {

       

                        $location = 'uploads/';

       

                            if(move_uploaded_file($tmp_name, $location.$name)) {

                            echo 'Uploaded!';

                  }else {

                    echo 'There was an error.';

                    }

        

                   }else {

         echo 'File Must Be Jpeg/jpg and must be 2mb or less.';

           }

    }else {

    

     echo 'Please Choose a file.';

    }

}



?>



<form action = "upload.php" method="POST" enctype="multipart/form-data">

<input type="file" name="file"><br><br>

<input type="submit" value="Submit">

</form>

Output

File Size Conversion
Screenshot3
uploading file size restriction in php
Screenshot4
In this example we are checking file size. So, we make sure that we had maximum security possible. What happen if we want to check file size now file size is actually process through in bytes. If we don't want image more then 2 megabytes. As you can see in screenshot3 google calculates 2 megabytes = 2097152 bytes. So we Just copy and paste bytes into the variables.

if(($extension=='jpg'||$extension=='jpeg')&&$type='image/jpeg' && $size<=$max_size)  {


This line of code i had perform simple check to whether the maximum size of the file is less then or equal to this size. with && another logical operators $size <= $max_size. also modify or error message file must be jpeg/jpg and must be 2 mb or less. So, now we are checking file must be an image file and also less then 2 megabytes. So, this is we are providing security to the server for uploading file as much as possible to allow image file extension upload and size restricting in php.
Read More

Saturday 29 March 2014

Uploading Files in Php


uploading files in php
Uploading Files In Php Programming Language. Uploading Files The Basics In Php Programming Language. Uploading Files Is very very Popular Topic because lots of websites now deals with files uploads it may be example uploading an images, Uploading documents, Even Uploading something needs to be proceeded at some point. So, how we do we handle file upload in php. Now its relatively easy handle file uploads in php. For the purpose of this tutorials You can see screenshot 1 script file name upload.php and directory name uploads/ folder. We will work with upload.php. Now the purpose of this videos its just simply how we take a file allow the user to select file from the computer and then send it to specific directory. Here we are not not looking to the security for uploading of the files. So, This codes are not safe to use at web-server because in actual facts the user will be upload any file. For example user can upload .php file extension file an they could miss-around with your server. So, In this tutorials we just learning how to uploads files but not its security.

Code For Uploading Files The Basic In Php


<?php

$name = $_FILES['file']['name'];

$size = $_FILES['file']['size'];

$type = $_FILES['file']['type'];



$tmp_name = $_FILES['file']['tmp_name'];



if (isset($name)) {

if(!empty($name)) {

echo 'OK.';

}else {

echo 'Please Choose a file.';

}

}



?>



<form action = "upload.php" method="POST" enctype="multipart/form-data">

<input type="file" name="file"><br><br>

<input type="submit" value="Submit">

</form>

Output (Screenshot2)

uploading files in php
Screenshot1
upload files in php
Screenshot2
Upload Files in php
Screenshot3
uploading files in php
Screenshot4
uploading files in php
Screenshot5
uploading files in php
Screenshot6
uploading files in php
Screenshot7

We will start with create form with form action upload.php because out php script is in same file. method is going to be POST remember we are sending large amount of data so method be Post. There is one addition attribute you need to apply in this form tag encrypt this is a way the data in form encoded when its send we need to supply this multipart/form-data So this is basically allow us to process the form and enable file upload we are sending alot much amount data and this is  encrypt this just tell us when we process on it it tells how we gonna encoded the data. So, Now we allow the user to upload the file we use input type tag file which will create browse button with name called file Then we create Submit Button to it.

In this article we are not including form security in another article we will only allow .jpg file to be uploaded. When the file is upload with php script we will grape file name, size of file, temporary location of the file. 



<?php

$name = $_FILES['file']['name'];

$size = $_FILES['file']['size'];

$type = $_FILES['file']['type'];



$tmp_name = $_FILES['file']['tmp_name'];



if (isset($name)) {

if(!empty($name)) {

echo 'OK.';

}else {

echo 'Please Choose a file.';

}
}



?>

In piece of php code we will grape the file name $name = $_FILES['file']['name']; This will show us the file name, $size = $_FILES['file']['size']; This will show us the file size, Then $type = $_FILES['file']['type']; This will show us the file type, $tmp_name = $_FILES['file']['tmp_name']; This will show the temporize location the file had been uploaded to the server. $error = $_FILES['file']['error']; This will show any error in uploading the files to the server.

Then i will check whether the file is uploaded we can access all information of file which is uploaded to the server but in this example i will only just check whether file is uploaded or not so will check with isset function. You can see output screenshot if file is not choose it shows message to the user please choose a file and if file is uploaded to the server you can see the message ok.


Code for Uploading File to the Directory 



<?php

$name = $_FILES['file']['name'];

$size = $_FILES['file']['size'];

$type = $_FILES['file']['type'];



$tmp_name = $_FILES['file']['tmp_name'];



if (isset($name)) {

if(!empty($name)) {





$location = 'uploads/';



if(move_uploaded_file($tmp_name, $location.$name)) {

echo 'Uploaded!';

}else {

echo 'Please Choose a file.';

}

}



?>



<form action = "upload.php" method="POST" enctype="multipart/form-data">

<input type="file" name="file"><br><br>

<input type="submit" value="Submit">

</form>

Output

uploading php file
Screenshot6
uploading files in php
Screenshot7


In this example we are uploading file to temporarily location to particular directory which we had uploads folder as you can see screenshots6 File is saved in uploads folder. In screenshot7 you can see the file url it is saved in uploads folder. In this way we can successfully uploaded a file. We used move_uploaded_file function with passing two parameters $tmp_name is variable in which temporarily file location and the $location where we want to move the file with $name variable which contain the name of the file with extension of the file.
Read More

Friday 28 March 2014

File Handling Deleting and renaming files in php

File Handling in php
File Handling Deleting and renaming Files in php. Before going to start read File handling writing to the file. In this tutorials we will see deleting and renaming the file which we had uploaded to the server by php functions or by php scripts. We will go through couple of functions deleting files and rename files. we had a specific function to delete file and  had function that rename the file to a file name of our choice. Why may you need to delete or renaming the files. For example you may want your user to delete file which had been upload by providing link to it and php function you can delete particular file. Same way you want user to rename the file by there choice you provide such task by php functions.

As you can see in screenshot1 we had 2 files filetodelete.txt is the file which we will delete in examples and filetorename so keep eye on it. File.php is file we performing task or writing php scripts for file handling deleting files and renaming files.

Code For File Handling deleting files (Screenshot2)

php File Deleting
Screenshot1

Deleting File in php
Screenshot2





<?php

$filename = 'filetodelete.txt';

if (unlink($filename)) {

echo ' File <strong>'.$filename.'</strong> had been  deleted.';

}else {

echo 'File cannot be deleted.';

}

?>

File Handling deleting files
Screenshot1
?>

Output (Screenshot 3)

File Handling Deleting and renaming files in php
Screenshot3
For File handling deleting files we had php function called unlink functions which will delete the file by php scripts. In unlink function we have to provide argument the name of the file which we want to delete. In this example we had if condition in php which we file provide value of true and false. If file is on the server it will be deleted by unlink function of php otherwise if the value is false it will show the error message file cannot be deleted or file cannot find as you wish. We are saving name of the file in variables in php such as $filename = 'filetodelete.txt'; .

Screenshot4
File Handling Deleting and Renaming files in php
Screenshot5


You can see output screenshot3 File had been deleted from the directory You can see in Screenshot4. If We run the code again you can see in screenshot5 we will have warning message unlink(filetodelete.txt) [function.unlink]: No such file or directory in C:\xampp\htdocs\series\filehandling\file.php on line 5. Also it echo out else part File cannot be deleted.


Renaming Files In Php

If we want to rename File By php Script. If we want to generate random number for file name we can use rand function. Here we will rename filetorename.txt to any random generated number in Php Programming Language. 

Code for Renaming File In Php Programming Language.

Screenshot6



<?php



$filename = 'filetorename.txt';

$rand = rand(10000,99999);



if (rename($filename, $rand.'.txt')) {

echo 'File <strong>'.$filename.'</strong> has been renamed to <strong>'.$rand.'txt </strong>';



} else {

echo 'Error Renaming.';

}

?>

Output 

Renaming files in php
Screenshot7

renaming file handling files in php
Screenshot8
We are generating random number to file by renaming file name by php script. Firstly we declaring filetorename.txt to $filename. Also making rand function we make function with rand () It takes lower and upper limit Here our lower limit is 10000, and our upper limit is 99999. It will generate five numbers. To rename the file we had function rename() function it will take two parameters File which we want to rename and the name we want to be to file by renaming, So, Here example piece of code is 

rename($filename, $rand'.txt');

Here we are appending file extension to .txt If we will not define type it will be an unknown file type. We will use if else statement to check whether file had been renamed or not.
As you can see output screenshot 7 and Screenshot 8.

In This tutorials we had seen Unlink function and rename function. Unlink function in php is used to delete the file from the particular directory. Rename function is used to rename the particular file from directory.
Read More

File Handling Checking If a File Exists into php

File handling checking file exists into php
File Handling in php checking if a file exits. In handling files we will check whether file exists into the server. Before we make file to the server it will check whether that file already there at server or not. Now Why we have to do this at real life application Let say You have file upload form and you allowing users to upload specific files and may be storing them in the area that they can be viewed or public or your personal. You may be asking users to uploading for example CV or you may be asking them to uploading images that is contribute a part of website. So, you gonna have specific location or locations where you gonna save images or files. However if you are generating random for images or files names. They could still match however if you create random number its always possibilities they can match. Now we will create a example in which it will check whether the file exists if it already exists it will show message File already exists. Otherwise it will File Handing Writing File in php.


Code for File Handling Checking If a File Exists

checking if a file already exists in php
Screenshot1

<?php



$filename = 'file.txt';



if (file_exists($filename)) {

echo 'File Already Exists.';



} else {

$handle = fopen($filename, 'w' );

fwrite($handle,'Nothing');

fclose($handle);

}

?> 

Output (Screenshots)

file in php
Screenshot2
Handling in file php
Screenshot3
File In php
Screenshot4
Files in php
Screenshot5
File Handling checking if a file exists into php
Screenshot6
Files In php
Screenshot7
For Checking File already exists into the server we use file_exists function and into we provide parameter name of the file which we had stored inside variable $filename. In this application we had created File Handling writing to the file in php before that we had if condition in php which checks whether name of the file is already created into the server or not. We can also check to the particular directory searching file by name of file by file_exists functions. Now here file_exists function will return true value if file already exists and if file does not exists it will give false value. If file_exists functions returns true that means file is already presents in our directory or into server where were you want. In parameters of name of file we can also provide directory examples dir/file.txt etc. Folder may be dir so you may also read directory search to the directory if file already exists.

As you can see screenshot2 and screenshot3 we had run php script by opening file file.php and again you can see in screenshot4. It had created file.txt with nothing return in it. As our php scripts runs well. Now you can see again by calling file.php you can see screenshot6 and screenshot7. You can see the error message that file already exists because we had run php scripts first then we had run it again it shows file that had been created once.
Read More

File Handling Listing files in php

File Handling Files in Php programming Language. In File handling we learn open a file write to the file, read to the file and appending to the file. In this we will learn how to look up to the specific directory and list all files. With the help of loop in php the content of the directory display foreach file. We are going to display a list then we create hyperlink foreach file, So we can click on it and go through it. Firstly Why it may Useful. Let Say You were creating some kind of file based Photo gallery and you want to have several folder for example. For example we had Files directory in which we have firstfile.txt, secondfile.txt and thirdfile.txt. Now what we are going to do is we are going to be looking inside files directory listing all files. You may want to create php script search an particular directory list of images display on a page. So, you can adopt this example i am going to use really really easily into your website and for your own purposes.

We are going to be using two different functions open directory and then reading directory You properly guest difference between this two open directory function will actually open the directory load into handle which we had done in file handling in php. With read directory we can put this into loop and create read directory as an another variable. So, the read directory gone be read handle which evaluate with another variable called files. So, You gone understand properly by example.


Code for File Handling Listing Files

File Handling Listing files in php
Screenshot1


<?Php



$directory = 'files';



if ($handle = opendir($directory.'/')) {

	echo 'Looking inside\''.$directory.'\':<br>';



while ($file = readdir($handle)) {

if ($file!='.'&&$file!='..') {

echo '<a href="'.$directory.'/'.$file.'">'.$file.'</a><br>';

}

}

}

?>

Output 

File Operation in php
Screenshot2
File Handling Listing Files in php
Screenshot3
Example for file handling listing files in php. In this example firstly we will create variable called directory. This variable will address to the particular file in which we are looking for the files. 

$directory = 'files';

files is the folder name in which we have files to look inside the directory.

Now we had to create handle to handle function opendir function 

if ($handle = opendir($directory.'/')){

In this we had created function opendir which open the directory and its appended with forward slash. If its find and open the directory which we assign in $directory variable such as files it will echo out

echo 'looking inside\''.$directory.'<br>';

As you can see output in screenshot2 Its open the directory and echo out the text we had looking inside files.

While ($file = readdir($handle)

Now in this code above we had while loop it will read directory and we applying handle into that So, We reading in the $handle that we already open with opendir function. Every Time we go around this loop Variable $file going to equal to next file along. Now here files are in text format for going to the file from browser we have to link to it for that we will use simple html hyperlink.

if ($file!='.'&&$file!='..') Its if condition to remove dots from which assigns to go forward and backward which we now removing from if conditions.

echo '<a href="'.$directory.'/'.$file.'">'.$file.'</a></br>';

This will link to the files to the particular directory called files. 

As you can see screenshot3 the link to the files and directory is opened. By clicking on the file name it will go to the content of the file in this way we can create particular directory to the browser by php script.

Read More

Explode function with file handling example

php explode implode function
The explode function with file handling example in php programming language. Will read the file. echo out to the user for reading the data of the file by file handling in php programming language.

Code for explode function with file handling example(Screenshot1)

explode function file handling php
Screenshot1

<?php



$filename = 'names.txt';

$handle = fopen($filename,'r');



$datain = fread($handle, filesize($filename));



$names_array = explode(',', $datain);



foreach($names_array as $name) {

echo $name. '<br>';

}



?>

Output (Screenshot2,)

php explode function
Screenshot2
In this example we are going to learn to read data from a file but obviously when u are reading data from the file. Its not always line by line basis. You may find commas separating your values and in this case we got few names here commas separated each value. Now how we deal with reading this in. Php file handling reading into the file. 

$handle fopen($filename, 'r');

Above code will create a handle to open and reading the file r stands for reading the file. We can also use file function which i had shown in example of file handling reading to the file. or we can also write  $handle fopen('names.txt','r');. I have taken names.txt in variale $filename for futhur use.

$datain = fread($handle, filesize($filename));

Above code will inilize the filesize will tell php file contain that much data instead of writing filesize we can also write the character we want from the file. like fread($handle,100); that's means it will contain 100 characters from the file.


$names_array = explode(',', $datain);

It will explode all commas from the file. Will remove commas from the file array of the name.

foreach($names_array as $name) {
echo $name. '<br>';
}

It will get array will write names one by one.
Read More

Wednesday 26 March 2014

File handling appending a file in php

file operation in php
Php File Handling appending a file in php programming Language. File Handling Writing File we had seen to write into the file by php Scripts. Appending to the file is where we can add more to the existence file. Let see same example of File handling Writing file.

Code for File Handling Writing file in php(Screenshot1)

writing to file in php
Screenshot1


<?php

$handle = fopen('names.txt','w');



fwrite($handle,'Alex'."\n");

fwrite($handle, 'Billy');



fclose($handle);
?>

Output (Screenshot2)

file handling in php
Screenshot2
This script of php will create or open name names.txt write to names in it and close the file. Now if we again write another name it will erase or delete the existence names. So, If you want to the file as it is and want to add another name to it you can use appending to the file let see example.

Code for File Handling Appending a file (Screenshot3)

appending file in php
Screenshot3


<?php

$handle = fopen('names.txt','a');



fwrite($handle,"\n".'Steven'."\n");



fclose($handle);

?>

Output (Screenshot4)

appending file in php
Screenshot4
Now i had change w to a for appending to the file in php programming Languages. It will Now add the name steven to our already created file names.txt with two another names alex, billy. If we use w it will overwrite over the file. 

Code for File Handling Appending a file (Screenshot5)

file handling appending a file in php
Screenshot5


<?php

$handle = fopen('names.txt','w');



fwrite($handle,"\n".'Steven'."\n");



fclose($handle);

?>

Output (Screenshot4)

appending file in php
Screenshot4
As you can see the output its override to the existence names. Now you can see the importance of the appending a file In php programming Language. 

Now why do have writing to the file and Appending to the file features. We can use this for opening th file and writing once in it. then by appending feature we can reuse that file to. 

Code for file Handling Appending a file 



<?php



if(isset($_POST['name'])) {

$name = $_POST['name'];

if(!empty($name)) {



$handle = fopen('names.txt','a');

fwrite($handle, $name."\n");

fclose($handle);

}else{

echo 'Please type a name.';

}

}



?>



<form action="file.php" method="POST">

Name:<br>

<input type="text" name="name"><br><br>

<input type="Submit" value="Submit">

</form>


Output (Screenshot)

appending file on php
Screenshot7

appending file on php
Screenshot8

In this example you had got idea how we can use this file handling by taking user data and save to the file. For Example here we had the names from the user and we are saving to the file names.txt. As you can see the output Screenshots.

Php File Handling Reading file


Php file handling reading file in php programming language. If we want to read a file want to read data from the file. If we want to read each name and display them to the user. 


Code for Php File Handling Writing File



<?php



if(isset($_POST['name'])) {

$name = $_POST['name'];

if(!empty($name)) {



$handle = fopen('names.txt','a');

fwrite($handle, $name."\n");

fclose($handle);



echo 'Current names in file:';



$readin = file('names.txt');

foreach($readin as $fname) {

echo trim($fname). ',';

}else{

echo 'Please type a name.';

}

}



?>



<form action="file.php" method="POST">

Name:<br>

<input type="text" name="name"><br><br>

<input type="Submit" value="Submit">

</form>

Output (Screenshot9)

file handling in php
Screenshot9
php file handling appending reading file in php
Screenshot10
In this example we are created a application for appending a file and display the file to the user. It will show the names. appended to the file. When the user will submit new name in the form as we seen in example of appending a file It will reproduce is the list of the current names. I will create list separated by commas not line by line so will use foreach loop. 

$readin = file('names.txt');

Code will read the file and it will contains only file which we want to read file function stands for reading file in php programming language. When we use file function it will open and will read the file. Here we does not need to fopen function because file function will open and read file for us.

foreach($readin as $fname) 

Code $readin is the array of names which are in file names.txt. Then we fetch all the names to fname. 

echo fname.',';

Code will put commas after each names.

Now you can see current names in file. We also used trim function which will remove white space or any other special characters from our names. 
Read More

About Me

Welcome to Extra Tutorials! My name is Mohammed and I am the 22 year writer, website developer, and photographer behind the blog. Thanks for visiting! Tutorials Jackpot… In addition to Developer, I love to develop websites and I love to write. Starting a php Blog was inevitable for me. What began as a simple way to share all of my Tutorials with friends and family has developed into my Part time job.

Mohammed Padela

WHAT IS PHP PROGRAMMING

WHAT IS PHP PROGRAMMING
WHAT IS PHP PROGRAMMING

Follow Us

Popular Posts

Designed ByBlogger Templates