Изучение возможностей языка серверных сценариев - PHP

Автор работы: Пользователь скрыл имя, 16 Мая 2013 в 23:30, лабораторная работа

Описание работы

Цель: Изучение возможностей языка серверных сценариев - PHP. Ознакомление с функциями навигации по файловой системе. Постановка задачи: Необходимо в сайт, созданный в лабораторной работе №4 добавить страницу Файловый навигатор. Данная страница должна представлять собой окно, позволяющее выполнять навигацию по файловой системе сервера в рамках каталога, где размещается сайт.

Файлы: 1 файл

Report.docx

— 39.40 Кб (Скачать файл)

Министерство  образования и науки Украины

Национальный  аэрокосмический университет

им. Н.Е. Жуковского

 

Кафедра компьютерных систем и сетей

 

Лабораторная  работа № 5

«Изучение возможностей языка серверных сценариев - PHP»

по курсу  «Web-программирование»

 

 

 

 

 

Выполнил:

студент гр.

 
   

подпись

дата

 

Проверил:

   
   

подпись

Дата


 

 

 

Харьков 2013

 

Цель: Изучение возможностей языка серверных сценариев - PHP. Ознакомление с функциями навигации по файловой системе.

 

 

 

Постановка задачи: Необходимо в сайт, созданный в лабораторной работе №4 добавить страницу Файловый навигатор. Данная страница должна представлять собой окно, позволяющее выполнять навигацию по файловой системе сервера в рамках каталога, где размещается сайт. Файловый менеджер должен выводить следующую информацию о файле на сервере:

  1. Имя файла
  2. Тип (файл или каталог)
  3. Размер файла (в единицах KB, MB, GB в зависимости от размера файла)
  4. Дата создания файла
  5. Функция согласно варианту задания

 

 

fm.php

<?php

 

$_CONFIG = array();

$_ERROR = "";

$_START_TIME = microtime(TRUE);

 

$_CONFIG['lang'] = "en";

$_CONFIG['show_top'] = true;

$_CONFIG['main_title'] = "File Manager";

$_CONFIG['time_format'] = "d.m.y H:i:s";

$_CONFIG['charset'] = "UTF-8";

$_CONFIG['starting_dir'] = ".";

 

$_TRANSLATIONS = array();

 

// English

$_TRANSLATIONS["en"] = array(

"file_name" => "File name",

"size" => "Size",

"last_changed" => "Last changed",

"total_used_space" => "Total used space",

"free_space" => "Free space",

"unable_to_read_dir" => "Unable to read directory",

"location" => "Location",

"root" => "Root",

"page_load_time" => "Page loaded in %.2f ms",

"del" => "Del",

);

 

// Russian

$_TRANSLATIONS["ru"] = array(

    "file_name" => "Имя файла",

    "size" => "Размер",

    "last_changed" => "Последнее изменение",

    "total_used_space" => "Всего использовано",

    "free_space" => "Свободно",

    "unable_to_read_dir" => "Не возможно прочитать папку",

    "location" => "Расположение",

    "root" => "Корневая папка",

    "page_load_time" => "Страница загружена за %.2f мс.",

    "del" => "Удалить",

);

 

/***************************************************************************/

/*   IMAGE CODES IN BASE64                                                 */

/*   You can generate your own with a converter                            */

/*   Like here: http://www.motobit.com/util/base64-decoder-encoder.asp     */

/*   Or here: http://www.greywyvern.com/code/php/binary2base64             */

/*   Or just use PHP base64_encode() function                              */

/***************************************************************************/

 

 

$_IMAGES = array();

 

$_IMAGES["arrow_down"] = "arrow_down";

$_IMAGES["arrow_up"] = "arrow_up";

$_IMAGES["del"] = "del";

$_IMAGES["archive"] = "archive";

$_IMAGES["audio"] = "audio";

$_IMAGES["code"] = "code";

$_IMAGES["database"] = "database";

$_IMAGES["directory"] = "directory";

$_IMAGES["graphics"] = "graphics";

$_IMAGES["image"] = "image";

$_IMAGES["presentation"] = "presentation";

$_IMAGES["spreadsheet"] = "spreadsheet";

$_IMAGES["textdocument"] = "textdocument";

$_IMAGES["vectorgraphics"] = "vectorgraphics";

$_IMAGES["video"] = "video";

$_IMAGES["webpage"] = "webpage";

$_IMAGES["7z"] = $_IMAGES["archive"];

$_IMAGES["as"] = "as";

$_IMAGES["avi"] = $_IMAGES["video"];

$_IMAGES["bz2"] = $_IMAGES["archive"];

$_IMAGES["c"] = "c";

$_IMAGES["cab"] = $_IMAGES["archive"];

$_IMAGES["cpp"] = "cpp";

$_IMAGES["cs"] = "cs";

$_IMAGES["css"] = $_IMAGES["code"];

$_IMAGES["doc"] = $_IMAGES["textdocument"];

$_IMAGES["docx"] = $_IMAGES["textdocument"];

$_IMAGES["exe"] = "exe";

$_IMAGES["gz"] = $_IMAGES["archive"];

$_IMAGES["gif"] = $_IMAGES["image"];

$_IMAGES["h"] = "h";

$_IMAGES["htm"] = $_IMAGES["webpage"];

$_IMAGES["html"] = $_IMAGES["webpage"];

$_IMAGES["iso"] = "iso";

$_IMAGES["java"] = "java";

$_IMAGES["jpg"] = $_IMAGES["image"];

$_IMAGES["jpeg"] = $_IMAGES["image"];

$_IMAGES["js"] = "js";

$_IMAGES["mov"] = $_IMAGES["video"];

$_IMAGES["mp3"] = $_IMAGES["audio"];

$_IMAGES["mp4"] = $_IMAGES["audio"];

$_IMAGES["mpeg"] = $_IMAGES["video"];

$_IMAGES["mpg"] = $_IMAGES["video"];

$_IMAGES["odg"] = $_IMAGES["vectorgraphics"];

$_IMAGES["odp"] = $_IMAGES["presentation"];

$_IMAGES["ods"] = $_IMAGES["spreadsheet"];

$_IMAGES["odt"] = $_IMAGES["textdocument"];

$_IMAGES["pdf"] = "pdf";

$_IMAGES["php"] = "php";

$_IMAGES["png"] = $_IMAGES["image"];

$_IMAGES["pps"] = $_IMAGES["presentation"];

$_IMAGES["ppsx"] = $_IMAGES["presentation"];

$_IMAGES["ppt"] = $_IMAGES["presentation"];

$_IMAGES["pptx"] = $_IMAGES["presentation"];

$_IMAGES["psd"] = $_IMAGES["graphics"];

$_IMAGES["rar"] = $_IMAGES["archive"];

$_IMAGES["rb"] = "rb";

$_IMAGES["sln"] = "sln";

$_IMAGES["sql"] = $_IMAGES["database"];

$_IMAGES["tar"] = $_IMAGES["archive"];

$_IMAGES["tgz"] = $_IMAGES["archive"];

$_IMAGES["txt"] = "txt";

$_IMAGES["wav"] = $_IMAGES["audio"];

$_IMAGES["wma"] = $_IMAGES["audio"];

$_IMAGES["wmv"] = $_IMAGES["video"];

$_IMAGES["xcf"] = $_IMAGES["graphics"];

$_IMAGES["xls"] = $_IMAGES["spreadsheet"];

$_IMAGES["xlsx"] = $_IMAGES["spreadsheet"];

$_IMAGES["xml"] = $_IMAGES["code"];

$_IMAGES["zip"] = $_IMAGES["archive"];

 

 

/***************************************************************************/

/*   HERE COMES THE CODE.                                                  */

/*   DON'T CHANGE UNLESS YOU KNOW WHAT YOU ARE DOING ;)                    */

/***************************************************************************/

 

//

// The class for any kind of file managing, for now - only deleting

//

class FileManager

public static function delete_dir($dir) {

if (is_dir($dir)) {

$objects = scandir($dir);

foreach ($objects as $object) {

if ($object != "." && $object != "..") {

if (filetype($dir."/".$object) == "dir")

FileManager::delete_dir($dir."/".$object);

else

unlink($dir."/".$object);

}

}

rmdir($dir);

}

}

 

public static function delete_file($file){

if(is_file($file)){

unlink($file);

}

}

 

//

// The main function, checks if the user wants to perform del operation

//

function run($location)

{

if(isset($_GET['del'])){

$split_path = Location::splitPath($_GET['del']);

$path = "";

for($i = 0; $i < count($split_path); $i++){

$path .= $split_path[$i];

if($i + 1 < count($split_path))

$path .= "/";

}

if($path == "" || $path == "/" || $path == "\\" || $path == ".")

return;

 

if(is_dir($path))

FileManager::delete_dir($path);

else if(is_file($path))

FileManager::delete_file($path);

}

}

}

 

//

// Dir class holds the information about one directory in the list

//

class Dir

{

var $name;

var $location;

 

//

// Constructor

//

function Dir($name, $location)

{

$this->name = $name;

$this->location = $location;

}

 

function getName()

{

return $this->name;

}

 

function getNameHtml()

{

return htmlspecialchars($this->name);

}

 

function getNameEncoded()

{

return rawurlencode($this->name);

}

 

//

// Debugging output

//

function debug()

{

print("Dir name (htmlspecialchars): ".$this->getName()."\n");

print("Dir location: ".$this->location->getDir(true, false, false, 0)."\n");

}

}

 

//

// File class holds the information about one file in the list

//

class File

{

var $name;

var $location;

var $size;

var $type;

var $modTime;

 

//

// Constructor

//

function File($name, $location)

{

$this->name = $name;

$this->location = $location;

 

$this->type = File::getFileType($this->location->getDir(true, false, false, 0).$this->getName());

$this->size = File::getFileSize($this->location->getDir(true, false, false, 0).$this->getName());

$this->modTime = filectime($this->location->getDir(true, false, false, 0).$this->getName());

}

 

function getName()

{

return $this->name;

}

 

function getNameEncoded()

{

return rawurlencode($this->name);

}

 

function getNameHtml()

{

return htmlspecialchars($this->name);

}

 

function getSize()

{

return $this->size;

}

 

function getType()

{

return $this->type;

}

 

function getModTime()

{

return $this->modTime;

}

 

//

// Determine the size of a file

//

public static function getFileSize($file)

{

return filesize($file);

}

 

public static function getFileType($filepath)

{

return File::getFileExtension($filepath);

}

 

public static function getFileMime($filepath)

{

$fhandle = finfo_open(FILEINFO_MIME);

$mime_type = finfo_file($fhandle, $filepath);

$mime_type_chunks = preg_split('/\s+/', $mime_type);

$mime_type = $mime_type_chunks[0];

$mime_type_chunks = explode(";", $mime_type);

$mime_type = $mime_type_chunks[0];

return $mime_type;

}

 

public static function getFileExtension($filepath)

{

return strtolower(pathinfo($filepath, PATHINFO_EXTENSION));

}

 

//

// Debugging output

//

function debug()

{

print("File name: ".$this->getName()."\n");

print("File location: ".$this->location->getDir(true, false, false, 0)."\n");

print("File size: ".$this->size."\n");

print("File modTime: ".$this->modTime."\n");

}

}

 

class Location

{

var $path;

 

//

// Split a file path into array elements

//

public static function splitPath($dir)

{

$dir = stripslashes($dir);

$path1 = preg_split("/[\\\\\/]+/", $dir);

$path2 = array();

for($i = 0; $i < count($path1); $i++)

{

if($path1[$i] == ".." || $path1[$i] == "." || $path1[$i] == "")

continue;

$path2[] = $path1[$i];

}

return $path2;

}

 

//

// Get the current directory.

// Options: Include the prefix ("./"); URL-encode the string; HTML-encode the string; return directory n-levels up

//

function getDir($prefix, $encoded, $html, $up)

{

$dir = "";

if($prefix == true)

$dir .= "./";

for($i = 0; $i < ((count($this->path) >= $up && $up > 0)?count($this->path)-$up:count($this->path)); $i++)

{

$temp = $this->path[$i];

if($encoded)

$temp = rawurlencode($temp);

if($html)

$temp = htmlspecialchars($temp);

$dir .= $temp."/";

}

return $dir;

}

 

function getPathLink($i, $html)

{

if($html)

return htmlspecialchars($this->path[$i]);

else

return $this->path[$i];

}

 

function getFullPath()

{

return dirname($_SERVER['SCRIPT_FILENAME'])."/".$this->getDir(true, false, false, 0);

}

 

//

// Debugging output

//

function debug()

{

print_r($this->path);

print("Dir with prefix: ".$this->getDir(true, false, false, 0)."\n");

print("Dir without prefix: ".$this->getDir(false, false, false, 0)."\n");

print("Upper dir with prefix: ".$this->getDir(true, false, false, 1)."\n");

print("Upper dir without prefix: ".$this->getDir(false, false, false, 1)."\n");

}

 

 

//

// Set the current directory

//

function init()

{

if(!isset($_GET['dir']) || strlen($_GET['dir']) == 0)

{

$this->path = $this->splitPath(EncodeExplorer::getConfig('starting_dir'));

}

else

{

$this->path = $this->splitPath($_GET['dir']);

}

}

 

//

// Checks if the current directory is below the input path

//

function isSubDir($checkPath)

{

for($i = 0; $i < count($this->path); $i++)

{

if(strcmp($this->getDir(true, false, false, $i), $checkPath) == 0)

return true;

}

return false;

}

}

 

class EncodeExplorer

{

var $location;

var $dirs;

var $files;

var $sort_by;

var $sort_as;

var $spaceUsed;

var $lang;

 

//

// Determine sorting, calculate space.

//

function init()

{

$this->sort_by = "";

$this->sort_as = "";

if(isset($_GET["sort_by"]) && isset($_GET["sort_as"]))

{

if($_GET["sort_by"] == "name" || $_GET["sort_by"] == "size" || $_GET["sort_by"] == "mod")

if($_GET["sort_as"] == "asc" || $_GET["sort_as"] == "desc")

{

$this->sort_by = $_GET["sort_by"];

$this->sort_as = $_GET["sort_as"];

}

}

if(strlen($this->sort_by) <= 0 || strlen($this->sort_as) <= 0)

{

$this->sort_by = "name";

$this->sort_as = "desc";

}

 

 

global $_TRANSLATIONS;

if(isset($_GET['lang']) && isset($_TRANSLATIONS[$_GET['lang']]))

$this->lang = $_GET['lang'];

else

$this->lang = EncodeExplorer::getConfig("lang");

}

 

//

// Read the file list from the directory

//

function readDir()

{

global $encodeExplorer;

//

// Reading the data of files and directories

//

if($open_dir = @opendir($this->location->getFullPath()))

{

$this->dirs = array();

$this->files = array();

while ($object = readdir($open_dir))

{

if($object != "." && $object != "..")

{

if(is_dir($this->location->getDir(true, false, false, 0)."/".$object))

{

$this->dirs[] = new Dir($object, $this->location);

}

else

$this->files[] = new File($object, $this->location);

}

}

closedir($open_dir);

}

else

{

$encodeExplorer->setErrorString("unable_to_read_dir");;

}

}

 

function sort()

{

if(is_array($this->files)){

usort($this->files, "EncodeExplorer::cmp_".$this->sort_by);

if($this->sort_as == "desc")

$this->files = array_reverse($this->files);

}

 

if(is_array($this->dirs)){

usort($this->dirs, "EncodeExplorer::cmp_name");

if($this->sort_by == "name" && $this->sort_as == "desc")

$this->dirs = array_reverse($this->dirs);

}

}

 

function makeArrow($sort_by)

if($this->sort_by == $sort_by && $this->sort_as == "asc")

{

$sort_as = "desc";

$img = "arrow_up";

}

else

{

$sort_as = "asc";

$img = "arrow_down";

}

 

if($sort_by == "name")

$text = $this->getString("file_name");

else if($sort_by == "size")

$text = $this->getString("size");

else if($sort_by == "mod")

$text = $this->getString("last_changed");

 

return "<a href=\"".$this->makeLink($sort_by, $sort_as, null, $this->location->getDir(false, true, false, 0))."\">

$text <img style=\"border:0;\" alt=\"".$sort_as."\" src=\"".$this->makeIcon($img)."\" /></a>";

}

 

function makeLink($sort_by, $sort_as, $delete, $dir)

{

$link = "?s&amp;";

 

if(isset($this->lang) && $this->lang != EncodeExplorer::getConfig("lang"))

$link .= "lang=".$this->lang."&amp;";

 

if($sort_by != null && strlen($sort_by) > 0)

$link .= "sort_by=".$sort_by."&amp;";

 

if($sort_as != null && strlen($sort_as) > 0)

$link .= "sort_as=".$sort_as."&amp;";

 

$link .= "dir=".$dir;

if($delete != null)

$link .= "&amp;del=".$delete;

return $link;

}

 

function makeIcon($l)

{

global $_IMAGES;

 

$l = strtolower($l);

if (isset($_IMAGES[$l]))

{

 

return "mimes/".$_IMAGES[$l].".gif";

}

return "mimes/unknown.gif";

}

 

function formatModTime($time)

{

$timeformat = "d.m.y H:i:s";

if(EncodeExplorer::getConfig("time_format") != null && strlen(EncodeExplorer::getConfig("time_format")) > 0)

$timeformat = EncodeExplorer::getConfig("time_format");

return date($timeformat, $time);

}

 

function formatSize($size)

{

$sizes = Array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB');

Информация о работе Изучение возможностей языка серверных сценариев - PHP