Script Tips


NetBizCity - Script Tips
Sunday, 14 February 2010 19:08

Uploading Files

Written by

Uploading files with PHP
 

To upload files with php is pretty simple.
We first start with a basic form and add enctype plus method = post.

<form action="index.php" enctype="multipart/form-data" method="post">
<input type="file" name="upload" size="40">

<input type="submit" name="start_upload" value="Start Load">
</form>

You can place this form on any page but will need to change the action= to match the name of the php script you create. In our example we named it index.php but it can be any name as long as the extension is .php.

We now add the PHP code which is as follows:

<?php
$tst = isset($_POST['start_upload']) ? $_POST['start_upload'] : '';


if (!empty($tst)){

// Where the file is going to be placed
$target_path = "/home/yoursite/public_html/uploads/";

/* Add the original filename to our target path. */
$target_path = $target_path . basename( $_FILES['upload']['name']);

if(move_uploaded_file($_FILES['upload']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['upload']['name']).
    " has been uploaded<br>";
}else{
    echo "The uplaod failed!";
}
?>

It's that easy and the only other thing you can do is add a filter to only allow certian file types.
To do this we can add these lines:

$filetype = $_FILES['upload']['type'];
   if($filetype=="application/pdf" or $filetype=="application/zip" or $filetype=="application/x-zip"){

   Put your code here to upload file!!

  }

You can add or remove file types to the above sample.


 

 

 

Script Tips Search

Registered User