Sunday, May 15, 2016

PHP Tutorial 8

File Handling: Listing files
<?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>';
            }
}

?>

File Handling: Checking if a file exists
<?php
$filename = 'file.txt';
if(file_exists($filename)){
            echo 'File already exists.';
} else {
            $handle = fopen($filename, 'w');
            fwrite($handle, 'Nothing');
            fclose($handle);
}

?>

File Handling: Deleting and Renaming files
<?php
$filename = 'filetodelete.txt';
if(unlink($filename)){
            echo 'File <strong>'.$filename.'</strong> has been deleted.';
} else {
            echo 'File cannot be deleted.';
}
?>

<?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';
}
?>
Uploading Files:
<?php
if(isset($_POST['submit'])){
$name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$location = 'uploads/';   
   
if(isset($name)&&!empty($name)){
    if(move_uploaded_file($tmp_name, $location.$name)){
        echo 'Successfully the (<strong>'.$name.'</strong>) file uploaded!';
    }else{
        echo 'There was an error uploading the file.';
       
    }
        
  }else{
      echo 'Please choose a file';
  }

}
?>

<form action="newboston.php" method="POST" enctype="multipart/form-data">
   
    <input type="file" name="file" /><br/><br/>
    <input type="submit" name="submit" value="Upload"/>
</form>



No comments:

Post a Comment