Автор Тема: Php файл да качва видео клип и да пише в xml файл  (Прочетена 5577 пъти)

tommy.bg

  • Напреднали
  • *****
  • Публикации: 63
  • Distribution: Ubuntu
  • Window Manager: Gnome
    • Профил
Здравейте драги съфорумници. Както се подразбира от заглавието ми трябва файл, който да може да качи клип в дадена директория и паралелно с това да записва в xml файла заглавие, описание и каквото и да било и понеже си нямам и понятие от php i xml се обръщам към Вас. Благадоря на всички които биха се отзовали
Активен

VladSun

  • Moderator
  • Напреднали
  • *****
  • Публикации: 2166
    • Профил
Активен

KISS Principle ( Keep-It-Short-and-Simple )
http://openfmi.net/projects/flattc/
Има 10 вида хора на този свят - разбиращи двоичния код и тези, които не го разбират :P

tommy.bg

  • Напреднали
  • *****
  • Публикации: 63
  • Distribution: Ubuntu
  • Window Manager: Gnome
    • Профил
Нямам идея как да ги вържа. Само upload форма имам някаква и се качват обаче не знам как да ги навържа. Т.е. трябва да е един файл който да има полета за заглавие, описание и т.н. после да избера файла който искам да кача и след като натисна upload дадения файл да се качи заедно с описанието. Директорията има права за писане
Активен

VladSun

  • Moderator
  • Напреднали
  • *****
  • Публикации: 2166
    • Профил
Дай да я видим тази "upload" форма.
Активен

KISS Principle ( Keep-It-Short-and-Simple )
http://openfmi.net/projects/flattc/
Има 10 вида хора на този свят - разбиращи двоичния код и тези, които не го разбират :P

b2l

  • Напреднали
  • *****
  • Публикации: 4786
  • Distribution: MCC Interim
  • Window Manager: - // - // -
  • ...sometimes I feel like screaming... || RTFM!
    • Профил
    • WWW
Ето ти един чудесен (поне за мен) пример как се dump-ва xml:
Код
GeSHi (PHP):
  1. <html>
  2. <head>
  3. <title>Create XML</title>
  4. </head>
  5. <body>
  6. <?php
  7.  
  8. // Creates a new document according to 1.0 specs
  9. $document = domxml_new_doc("1.0");
  10.  
  11. // Lets create an element and call it root, we will then append it to the new document.
  12. $rootElement = $document->create_element("root");
  13. $new_node = $document->append_child($rootElement);
  14.  
  15. // Lets create a new node called "Items" and append that to the root node.
  16. $itemsElement = $document->create_element("Items");
  17. $items_node = $new_node->append_child($itemsElement);
  18.  
  19. // Now go into a for loop in which we will create, set, and add five nodes to our Items node.
  20. for($i = 0; $i < 5; $i++) {
  21. $item = $document->create_element("Item");
  22. $item->set_content("This is item $i");
  23. $items_node->append_child($item);
  24. }
  25.  
  26. // Lets dump this structure out to a file called items.xml
  27. $document->dump_file("items.xml");
  28.  
  29. ?>
  30. </body>
  31. </html>

Output:
Код
GeSHi (XML):
  1. <?xml version="1.0" ?>
  2. <root>
  3. <Items>
  4. <Item>This is item 0</Item>
  5. <Item>This is item 1</Item>
  6. <Item>This is item 2</Item>
  7. <Item>This is item 3</Item>
  8. <Item>This is item 4</Item>
  9. </Items>
  10. </root>
Активен

"Човекът е въже, опънато между звяра и свръхчовека, въже над пропаст. Човекът е нещо, което трябва да бъде превъзмогнато." - Фр. Ницше

tommy.bg

  • Напреднали
  • *****
  • Публикации: 63
  • Distribution: Ubuntu
  • Window Manager: Gnome
    • Профил
Това е upload формата

Код
GeSHi (PHP):
  1. <?php
  2. $site_name = $_SERVER['HTTP_HOST'];
  3. $url_dir = " http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF' ]);
  4. $url_this = " http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF' ];
  5.  
  6. // Къде да се записват качените файлове?
  7.  
  8. $upload_dir = "files/";
  9. $upload_url = $url_dir."/files/";
  10. $message ="log.txt";
  11. /************************************************************
  12. Създава директория за качените файлове
  13. ************************************************************/
  14. if (!is_dir("files")) {
  15. if (!mkdir($upload_dir))
  16. die ("няма папка за качените файлове и не можах да създам такава");
  17. if (!chmod($upload_dir,0755))
  18. die ("не можах да сменя правата на 755");
  19. }
  20. /************************************************************
  21. Обслужва заявката на потребителя
  22. ************************************************************/
  23. if ($_REQUEST[del]) {
  24. print "<script>window.location.href='$url_this?message=deleted successfully'</script>";
  25. }
  26. else if ($_FILES['userfile']) {
  27. $message = do_upload($upload_dir, $upload_url);
  28. print "<script>window.location.href='$url_this?message=$message'</script>";
  29. }
  30. else if (!$_FILES['userfile']);
  31. else
  32. $message = "Invalid File Specified.";
  33.  
  34. /************************************************************
  35. Списък с файлове
  36. ************************************************************/
  37. $handle=opendir($upload_dir);
  38. $filelist = "";
  39. while ($file = readdir($handle)) {
  40. if(!is_dir($file) && !is_link($file)) {
  41. $filelist .= "<br><a href='$upload_dir$file'>".$file."</a>";
  42. }
  43. }
  44. function do_upload($upload_dir, $upload_url) {
  45. $temp_name = $_FILES['userfile']['tmp_name'];
  46. $file_name = $_FILES['userfile']['name'];
  47. $file_type = $_FILES['']['exe'];
  48. $file_type = $_FILES['']['mp3'];
  49. $file_type = $_FILES['']['avi'];
  50. $file_type = $_FILES['']['mp3u'];
  51. $file_type = $_FILES['']['php'];
  52. $file_type = $_FILES['']['html'];
  53. $file_type = $_FILES['']['*.*'];
  54. $file_size = $_FILES['userfile']['size'];
  55. $result = $_FILES['userfile']['error'];
  56. $file_url = $upload_url.$file_name;
  57. $file_path = $upload_dir.$file_name;
  58.  
  59. //File Name Check
  60. if ( $file_name =="") {
  61. $message = "Невалиден тип файл";
  62. return $message;
  63. }
  64. //File Size Check
  65. else if ( $file_size > 999999999999999999999) {
  66. print $file_size;
  67. $message = "Размера на файла е много голям.";
  68. return $message;
  69. }
  70. //File Type Check
  71. else if ( $file_type == "text/plain"
  72. || $file_type == "application/force-download"
  73. || $file_type == "application/octet-stream") {
  74. $message = "Не може да качвате скриптови файлове";
  75. return $message;
  76. }
  77. $result = move_uploaded_file($temp_name, $file_path);
  78. if (!chmod($file_path,0755))
  79. $message = "не можах да сменя правата на 755";
  80. else
  81. $message = ($result)?"$file_name($file_type) файла качен успешно." :
  82. "Каченият файл е повреден.";
  83. return $message;
  84. }
  85. ?>
  86. <table style="width: 40%" align="center" valign="top">
  87. <tr>
  88. <td>
  89. <div align="center" style="font-size: 19px; font-weight: bold">
  90. </table>
  91. <body bgcolor="#667987"><center>
  92. <font color=red><?=$_REQUEST[message]?></font>
  93. <form name="upload" id="upload" ENCTYPE="multipart/form-data" method="post">
  94. Качи фаил: <input type="file" id="userfile" name="userfile" size="20">
  95. <input type="submit" name="upload" value="Upload">
  96. </form>
  97. <b>До сега потребителите ни са качили следните файлове:</b>
  98. <hr style="color:yellow; background-color:black; height:1px;
  99. margin-right:0; text-align:right; border:0px">
  100. <?=$filelist?>
  101. </center>
  102. <?
  103. if ($_REQUEST[debug]==1) print "------------------Debugging Info----------------<br>";
  104. if ($_REQUEST[debug]==1) print "site=$site_name<br>dir=$url_dir<br>url=$url_this<br>";
  105. if ($_REQUEST[debug]==1) print "upload dir=$upload_dir<br>upload url=$upload_url<br>";
  106. ?>
  107.  
« Последна редакция: Mar 02, 2011, 04:10 от VladSun »
Активен

VladSun

  • Moderator
  • Напреднали
  • *****
  • Публикации: 2166
    • Профил
Код
GeSHi (PHP):
  1. //File Type Check
  2. else if ( $file_type == "text/plain"
  3. || $file_type == "application/force-download"
  4. || $file_type == "application/octet-stream") {

 ;D ;D ;D

По-добре не го ползвай този скрипт :)
Активен

KISS Principle ( Keep-It-Short-and-Simple )
http://openfmi.net/projects/flattc/
Има 10 вида хора на този свят - разбиращи двоичния код и тези, които не го разбират :P

VladSun

  • Moderator
  • Напреднали
  • *****
  • Публикации: 2166
    • Профил
Код
GeSHi (PHP):
  1. <?php
  2.  
  3. function validateInput($request, &$response, $config)
  4. {
  5. if (!$request['submitted'])
  6. return false;
  7.  
  8. $hasError = false;
  9.  
  10. if (empty($request['desc']))
  11. {
  12. $response['errors'][] = "Полето 'Description' е задължително.";
  13. $hasError = true;
  14. }
  15.  
  16. if (empty($request['file']))
  17. {
  18. $response['errors'][] = "Полето 'File' е задължително.";
  19. $hasError = true;
  20. }
  21.  
  22. if ($request['file']['error'] !== UPLOAD_ERR_OK)
  23. {
  24. $errorMap = array
  25. (
  26. UPLOAD_ERR_INI_SIZE => "The uploaded file exceeds the upload_max_filesize directive in php.ini.",
  27. UPLOAD_ERR_FORM_SIZE => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.",
  28. UPLOAD_ERR_PARTIAL => "The uploaded file was only partially uploaded. ",
  29. UPLOAD_ERR_NO_FILE => "No file was uploaded.",
  30. UPLOAD_ERR_NO_TMP_DIR => "Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3. ",
  31. UPLOAD_ERR_CANT_WRITE => "Failed to write file to disk. Introduced in PHP 5.1.0. ",
  32. UPLOAD_ERR_EXTENSION => "A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.",
  33. );
  34.  
  35. $response['errors'][] = $errorMap[$request['file']['error']];
  36. return false;
  37. }
  38.  
  39. if (file_exists($config['destinationDir'] . '/' . $request['file']['name']))
  40. {
  41. $response['errors'][] = $request['file']['name'] . " вече съществува. ";
  42. $hasError = true;
  43. }
  44.  
  45. if ($request['file']['name'] > $config['maxFileSize'])
  46. {
  47. $response['errors'][] =  "Файлът има размер по-голям от разрешения. (" .
  48. $request['file']['size'] . " > " . $config['maxFileSize']. ")";
  49. $hasError = true;
  50. }
  51.  
  52. if (!in_array(strtolower(pathinfo( $request['file']['name'], PATHINFO_EXTENSION)), $config['allowedExtensions']))
  53. {
  54. $response['errors'][] =  "Файлове с такова разшорение не са разрешени за качване.";
  55. $response['errors'][] =  "Разрешените разширения са " . implode(', ', $config['allowedExtensions']);
  56. $hasError = true;
  57. }
  58.  
  59. return !$hasError;
  60. }
  61.  
  62. function uploadFile($request, &$response, $config)
  63. {
  64. if (false === move_uploaded_file($request['file']['tmp_name'], $config['destinationDir'] . '/' . $request['file']['name']))
  65. {
  66. $response['errors'][] = 'Грека при качването на файла.';
  67. return false;
  68. }
  69. return true;
  70. }
  71.  
  72. function removeFile($request, &$response, $config)
  73. {
  74. if (!unlink($config['destinationDir'] . '/' . $request['file']['name']))
  75. {
  76. $response['errors'][] = 'Грешка при изчистването на файла.';
  77. return false;
  78. }
  79. return true;
  80. }
  81.  
  82. function getList(&$response, $config)
  83. {
  84. $response['files'] = glob($config['destinationDir'].'/*.*');
  85. }
  86.  
  87. function describeFile($request, &$response, $config)
  88. {
  89. libxml_use_internal_errors(true);
  90. $xml = simplexml_load_file($config['destinationFile']);
  91. if (!$xml)
  92. {
  93. $response['errors'][] = "Failed loading XML\n";
  94. foreach(libxml_get_errors() as $error)
  95. {
  96. $response['errors'][] = $error->message;
  97. }
  98. return false;
  99. }
  100.  
  101. $file = $xml->addChild('file');
  102. $file->addChild('name', $request['file']['name']);
  103. $file->addChild('description', $request['desc']);
  104.  
  105. if (false === file_put_contents($config['destinationFile'], $xml->asXML()))
  106. {
  107. $response['errors'][] = 'Грешка при записването в XML файла.';
  108. return false;
  109. }
  110.  
  111. $response['messages'][] = "Качено в " . $config['destinationDir'] . '/' . $request['file']['name'];
  112.  
  113. return true;
  114. }
  115.  
  116. function view($response, $config)
  117. {
  118. $pageTemplate = <<<EOT
  119. <html>
  120. <head>
  121. <style type="text/css">
  122. .error
  123. {
  124. border : 1px solid red;
  125. background-color: #ffa0a0;
  126. color: #220000;
  127. text-align : center;
  128. padding : 20 20;
  129. margin : 10;
  130. }
  131. .message
  132. {
  133. border : 1px solid green;
  134. background-color: #a0ffa0;
  135. color : #220000;
  136. text-align : center;
  137. padding : 20 20;
  138. margin : 10;
  139. }
  140.  
  141. .files
  142. {
  143. border : 1px solid black;
  144. padding : 20;
  145. margin : 10;
  146. }
  147.  
  148. .form
  149. {
  150. border : 1px solid black;
  151. padding : 20;
  152. margin : 10;
  153. }
  154. </style>
  155. </head>
  156. <body>
  157. %s
  158. %s
  159. %s
  160. %s
  161. </body>
  162. </html>
  163. EOT;
  164.  
  165. $listItemTemplate = <<<EOT
  166.    <li>%s</li>
  167. EOT;
  168.  
  169. $listTemplate = <<<EOT
  170. <div class="files">
  171. <ol>
  172. %s
  173. </ol>
  174. </div>
  175. EOT;
  176.  
  177. $errorTemplate = <<<EOT
  178. <div class="error">%s</div>
  179. EOT;
  180.  
  181. $messageTemplate = <<<EOT
  182. <div class="message">%s</div>
  183. EOT;
  184.  
  185. $formTemplate = <<<EOT
  186. <form action="" method="post" enctype="multipart/form-data" class="form">
  187. <input type="hidden" name="submitted" value="1" />
  188. <input type="hidden" name="MAX_FILE_SIZE" value="%d" />
  189. <label for="file">Filename:</label><input type="file" name="file" id="file" />
  190. <br />
  191. <label for="file">Description:</label><textarea cols="20" rows="5"  name="desc" id="desc"></textarea>
  192. <br />
  193. <input type="submit" name="submit" value="Submit" />
  194. </form>
  195. EOT;
  196.  
  197.  
  198.  
  199. $errorView = '';
  200. $messageView = '';
  201. $fileListView = 'No files uploaded.';
  202.  
  203. if (!empty($response['errors']))
  204. {
  205. $errorView = sprintf($errorTemplate, implode('<br />', $response['errors']));
  206. }
  207.  
  208. if (!empty($response['messages']))
  209. {
  210. $messageView = sprintf($messageTemplate, implode('<br />', $response['messages']));
  211. }
  212.  
  213. if (!empty($response['files']))
  214. {
  215. $listItemRenderer = function ($fileName) use ($listItemTemplate)
  216. {
  217. return sprintf($listItemTemplate, htmlentities(pathinfo($fileName, PATHINFO_BASENAME), ENT_QUOTES));
  218. };
  219.  
  220. $fileListView = sprintf($listTemplate, implode("\n", array_map
  221. (
  222. $listItemRenderer,
  223. $response['files']))
  224. );
  225. }
  226.  
  227. $formView = sprintf($formTemplate, $config['maxFileSize']);
  228.  
  229. printf($pageTemplate, $errorView, $messageView, $formView, $fileListView);
  230. }
  231.  
  232. //-----------------------------------------------------------------------------------------//
  233.  
  234.  
  235. $config = array
  236. (
  237. 'maxFileSize' => 900000,
  238. 'allowedExtensions' => array
  239. (
  240. 'jpeg',
  241. 'jpg',
  242. 'gif',
  243. 'bmp',
  244. ),
  245. 'allowOverwrite' => false,
  246.  
  247. 'destinationDir' => 'uploads',
  248. 'destinationFile' => 'db.xml',
  249. );
  250.  
  251. $request = array
  252. (
  253. 'submitted' => isset($_POST['submitted']),
  254. 'file' => isset($_FILES['file']) ? $_FILES['file'] : false,
  255. 'desc' => isset($_POST['desc']) ? $_POST['desc'] : false,
  256. );
  257.  
  258. $response = array
  259. (
  260. 'errors' => array(),
  261. 'messages' => array(),
  262. 'files' => array(),
  263. );
  264.  
  265.  
  266. if (validateInput($request, $response, $config))
  267. {
  268. if (uploadFile($request, $response, $config))
  269. {
  270. if (!describeFile($request, $response, $config))
  271. {
  272. removeFile($request, $response, $config);
  273. }
  274. }
  275. }
  276.  
  277. getList($response, $config);
  278.  
  279. view($response, $config);

PS: PHP 5.3+
« Последна редакция: Mar 03, 2011, 01:46 от VladSun »
Активен

KISS Principle ( Keep-It-Short-and-Simple )
http://openfmi.net/projects/flattc/
Има 10 вида хора на този свят - разбиращи двоичния код и тези, които не го разбират :P

tommy.bg

  • Напреднали
  • *****
  • Публикации: 63
  • Distribution: Ubuntu
  • Window Manager: Gnome
    • Профил
Дава ми тази грешка "Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/evraziab/public_html/upload.php on line 336"


А 336 ред е това "if (!empty($response['errors']))" и колко него редовете изглеждат така


 
Код
GeSHi (PHP):
  1. $errorView = '';
  2.  
  3.      $messageView = '';
  4.  
  5.      $fileListView = 'No files uploaded.';
  6.  
  7.  
  8.  
  9.      if (!empty($response['errors']))
  10.  
  11.      {
  12.  
  13.      $errorView = sprintf($errorTemplate, implode('<br />', $response['errors']));
  14.  
  15.      }
  16.  
  17.  
  18.  
  19.      if (!empty($response['messages']))
  20.  
« Последна редакция: Mar 07, 2011, 11:21 от VladSun »
Активен

b2l

  • Напреднали
  • *****
  • Публикации: 4786
  • Distribution: MCC Interim
  • Window Manager: - // - // -
  • ...sometimes I feel like screaming... || RTFM!
    • Профил
    • WWW
 ???
Код
GeSHi (PHP):
  1. if (!empty($response[errors]))
Активен

"Човекът е въже, опънато между звяра и свръхчовека, въже над пропаст. Човекът е нещо, което трябва да бъде превъзмогнато." - Фр. Ницше

tommy.bg

  • Напреднали
  • *****
  • Публикации: 63
  • Distribution: Ubuntu
  • Window Manager: Gnome
    • Профил
Значи махнах кавичките и на останалите и сега ми дава грешка "Parse error: syntax error, unexpected $end in /home/evraziab/public_html/upload.php on line 456"


Код
GeSHi (PHP):
  1.      <?php
  2.  
  3.         function validateInput($request, &$response, $config)
  4.  
  5.      {
  6.  
  7.      if (!$request['submitted'])
  8.  
  9.      return false;
  10.  
  11.      $hasError = false;
  12.  
  13.  
  14.      if (empty($request['desc']))
  15.  
  16.      {
  17.  
  18.      $response['errors'][] = "Полето 'Description' е задължително.";
  19.  
  20.      $hasError = true;
  21.  
  22.      }
  23.  
  24.  
  25.  
  26.      if ($request['file']['error'] !== UPLOAD_ERR_OK)
  27.  
  28.      {
  29.  
  30.     $errorMap = array
  31.  
  32.      (
  33.  
  34.     UPLOAD_ERR_INI_SIZE => "The uploaded file exceeds the upload_max_filesize directive in php.ini.",
  35.  
  36.      UPLOAD_ERR_FORM_SIZE => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.",
  37.  
  38.      UPLOAD_ERR_PARTIAL => "The uploaded file was only partially uploaded. ",
  39.       UPLOAD_ERR_NO_FILE => "No file was uploaded.",
  40.  
  41.      UPLOAD_ERR_NO_TMP_DIR => "Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3. ",
  42.  
  43.      UPLOAD_ERR_CANT_WRITE => "Failed to write file to disk. Introduced in PHP 5.1.0. ",
  44.  
  45.      UPLOAD_ERR_EXTENSION => "A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.",
  46.  
  47.      );
  48.  
  49.  
  50.  
  51.      $response['errors'][] = $errorMap[$request['file']['error']];
  52.  
  53.      return false;
  54.  
  55.      }
  56.  
  57.  
  58.  
  59.      if (file_exists($config['destinationDir'] . '/' . $request['file']['name']))
  60.  
  61.      {
  62.  
  63.      $response['errors'][] = $request['file']['name'] . " вече съществува. ";
  64.  
  65.      $hasError = true;
  66.  
  67.     }
  68.  
  69.  
  70.  
  71.      if ($request['file']['name'] > $config['maxFileSize'])
  72.  
  73.      {
  74.  
  75.      $response['errors'][] =  "Файлът има размер по-голям от разрешения. (" .
  76.  
  77.      $request['file']['size'] . " > " . $config['maxFileSize']. ")";
  78.  
  79.      $hasError = true;
  80.  
  81.      }
  82.  
  83.  
  84.  
  85.      if (!in_array(strtolower(pathinfo( $request['file']['name'], PATHINFO_EXTENSION)), $config['allowedExtensions']))
  86.  
  87.      {
  88.  
  89.      $response['errors'][] =  "Файлове с такова разшорение не са разрешени за качване.";
  90.  
  91.      $response['errors'][] =  "Разрешените разширения са " . implode(', ', $config['allowedExtensions']);
  92.  
  93.      $hasError = true;
  94.  
  95.      }
  96.  
  97.  
  98.  
  99.      return !$hasError;
  100.  
  101.     }
  102.  
  103.  
  104.  
  105.      function uploadFile($request, &$response, $config)
  106.  
  107.      {
  108.  
  109.      move_uploaded_file($request['file']['tmp_name'], $config['destinationDir'] . '/' . $request['file']['name']);
  110.  
  111.      $response['messages'][] = "Качено в " . $config['destinationDir'] . '/' . $request['file']['name'];
  112.  
  113.      }
  114.  
  115.  
  116.  
  117.      function getList(&$response, $config)
  118.  
  119.      {
  120.  
  121.      $response['files'] = glob($config['destinationDir'].'/*.*');
  122.  
  123.      }
  124.  
  125.  
  126.  
  127.      function describeFile($request, &$response, $config)
  128.  
  129.      {
  130.  
  131.      libxml_use_internal_errors(true);
  132.  
  133.      $xml = simplexml_load_file($config['destinationFile']);
  134.  
  135.      if (!$xml)
  136.  
  137.      {
  138.  
  139.      $response['errors'][] = "Failed loading XML\n";
  140.  
  141.      foreach(libxml_get_errors() as $error)
  142.  
  143.      {
  144.  
  145.             $response['errors'][] = $error->message;
  146.  
  147.         }
  148.  
  149.      return false;
  150.  
  151.      }
  152.  
  153.  
  154.  
  155.      $file = $xml->addChild('file');
  156.  
  157.      $file->addChild('name', $request['file']['name']);
  158.  
  159.      $file->addChild('description', $request['desc']);
  160.  
  161.      file_put_contents($config['destinationFile'], $xml->asXML());
  162.  
  163.      }
  164.  
  165.  
  166.  
  167.      function view($response, $config)
  168.  
  169.      {
  170.  
  171.      $pageTemplate = <<<EOT
  172.  
  173.      <html>
  174.  
  175.      <head>
  176.  
  177.      <style type="text/css">
  178.  
  179.      .error
  180.  
  181.      {
  182.  
  183.      border : 1px solid red;
  184.  
  185.      background-color: #ffa0a0;
  186.  
  187.      color: #220000;
  188.  
  189.      text-align : center;
  190.  
  191.      padding : 20 20;
  192.  
  193.      margin : 10;
  194.  
  195.      }
  196.  
  197.      .message
  198.  
  199.      {
  200.  
  201.      border : 1px solid green;
  202.  
  203.      background-color: #a0ffa0;
  204.  
  205.      color : #220000;
  206.  
  207.      text-align : center;
  208.  
  209.      padding : 20 20;
  210.  
  211.      margin : 10;
  212.  
  213.      }
  214.  
  215.  
  216.  
  217.      .files
  218.  
  219.      {
  220.  
  221.      border : 1px solid black;
  222.  
  223.      padding : 20;
  224.  
  225.      margin : 10;
  226.  
  227.      }
  228.  
  229.  
  230.  
  231.      .form
  232.  
  233.      {
  234.  
  235.      border : 1px solid black;
  236.  
  237.      padding : 20;
  238.  
  239.      margin : 10;
  240.  
  241.      }
  242.  
  243.      </style>
  244.  
  245.      </head>
  246.  
  247.      <body>
  248.  
  249.      %s
  250.  
  251.      %s
  252.  
  253.      %s
  254.  
  255.      %s
  256.  
  257.      </body>
  258.  
  259.      </html>
  260.  
  261.      EOT;
  262.  
  263.  
  264.  
  265.      $listItemTemplate = <<<EOT
  266.  
  267.         <li>%s</li>
  268.  
  269.      EOT;
  270.  
  271.  
  272.  
  273.      $listTemplate = <<<EOT
  274.  
  275.      <div class="files">
  276.  
  277.      <ol>
  278.  
  279.      %s
  280.  
  281.      </ol>
  282.  
  283.      </div>
  284.  
  285.      EOT;
  286.  
  287.  
  288.  
  289.      $errorTemplate = <<<EOT
  290.  
  291.      <div class="error">%s</div>
  292.  
  293.      EOT;
  294.  
  295.  
  296.  
  297.      $messageTemplate = <<<EOT
  298.  
  299.      <div class="message">%s</div>
  300.  
  301.      EOT;
  302.  
  303.  
  304.  
  305.      $formTemplate = <<<EOT
  306.  
  307.      <form action="" method="post" enctype="multipart/form-data" class="form">
  308.  
  309.      <input type="hidden" name="submitted" value="1" />
  310.  
  311.      <input type="hidden" name="MAX_FILE_SIZE" value="%d" />
  312.  
  313.      <label for="file">Filename:</label><input type="file" name="file" id="file" />
  314.  
  315.      <br />
  316.  
  317.      <label for="file">Description:</label><textarea cols="20" rows="5"  name="desc" id="desc"></textarea>
  318.  
  319.      <br />
  320.  
  321.      <input type="submit" name="submit" value="Submit" />
  322.  
  323.      </form>
  324.  
  325.      EOT;
  326.  
  327.  
  328.      $errorView = '';
  329.  
  330.      $messageView = '';
  331.  
  332.      $fileListView = 'No files uploaded.';
  333.  
  334.  
  335.      if (!empty($response[errors]))
  336.  
  337.      {
  338.  
  339.      $errorView = sprintf($errorTemplate, implode('<br />', $response[errors]));
  340.  
  341.      }
  342.  
  343.  
  344.  
  345.      if (!empty($response[messages]))
  346.  
  347.      {
  348.  
  349.      $messageView = sprintf($messageTemplate, implode('<br />', $response[messages]));
  350.  
  351.      }
  352.  
  353.      if (!empty($response[files]))
  354.  
  355.      {
  356.  
  357.      $listItemRenderer = function ($fileName) use ($listItemTemplate)
  358.  
  359.      {
  360.  
  361.      return sprintf($listItemTemplate, htmlentities(pathinfo($fileName, PATHINFO_BASENAME), ENT_QUOTES));
  362.  
  363.      };
  364.  
  365.  
  366.  
  367.      $fileListView = sprintf($listTemplate, implode("\n", array_map)
  368.  
  369.      (
  370.  
  371.      $listItemRenderer,
  372.  
  373.      $response[files]))
  374.  
  375.      );
  376.  
  377.      }
  378.  
  379.      $formView = sprintf($formTemplate, $config[maxFileSize]);
  380.  
  381.      printf($pageTemplate, $errorView, $messageView, $formView, $fileListView);
  382.  
  383.      }
  384.  
  385.  
  386.      //-----------------------------------------------------------------------------------------//
  387.  
  388.      $config = array
  389.  
  390.      (
  391.  
  392.      'maxFileSize' => 900000,
  393.  
  394.      'allowedExtensions' => array
  395.  
  396.      (
  397.  
  398.      'jpeg',
  399.  
  400.      'jpg',
  401.  
  402.      'gif',
  403.  
  404.      'bmp',
  405.  
  406.      ),
  407.  
  408.      'allowOverwrite' => false,
  409.  
  410.  
  411.  
  412.      'destinationDir' => 'uploads',
  413.  
  414.      'destinationFile' => 'db.xml',
  415.  
  416.      );
  417.  
  418.      $request = array
  419.  
  420.      (
  421.  
  422.      'submitted' => isset($_POST[submitted]),
  423.  
  424.      'file' => isset($_FILES[file]) ? $_FILES[file] : false,
  425.  
  426.      'desc' => isset($_POST[desc]) ? $_POST[desc] : false,
  427.  
  428.      );
  429.  
  430.      $response = array
  431.  
  432.      (
  433.  
  434.      'errors' => array(),
  435.  
  436.      'messages' => array(),
  437.  
  438.      'files' => array(),
  439.  
  440.      );
  441.  
  442.      if (validateInput($request, $response, $config))
  443.  
  444.      {
  445.  
  446.      uploadFile($request, $response, $config);
  447.  
  448.      describeFile($request, $response, $config);
  449.  
  450.      }
  451.  
  452.  
  453.      getList($response, $config);
  454.  
  455.      view($response, $config);
  456.  
« Последна редакция: Mar 04, 2011, 01:14 от VladSun »
Активен

VladSun

  • Moderator
  • Напреднали
  • *****
  • Публикации: 2166
    • Профил
Скриптът е реално работещ - дебъгвай :)
Коя версия на PHP ползваш? изиск

PS: Явно променяш сорса - heredoc синтаксът изисква да няма нищо пред затварящия низ. Пробвай скрипта след директен copy-paste ... не променяй нищо освен $config редовете.
« Последна редакция: Mar 04, 2011, 01:31 от VladSun »
Активен

KISS Principle ( Keep-It-Short-and-Simple )
http://openfmi.net/projects/flattc/
Има 10 вида хора на този свят - разбиращи двоичния код и тези, които не го разбират :P

VladSun

  • Moderator
  • Напреднали
  • *****
  • Публикации: 2166
    • Профил
???
Код
GeSHi (PHP):
  1. if (!empty($response[errors]))

Лош съвет :(

http://php.net/manual/en/language.types.array.php
Цитат
Why is $foo[bar] wrong?

Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not. But why? It is common to encounter this kind of syntax in old scripts:
<?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?>

This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in future define constants which, unfortunately for such code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.
Активен

KISS Principle ( Keep-It-Short-and-Simple )
http://openfmi.net/projects/flattc/
Има 10 вида хора на този свят - разбиращи двоичния код и тези, които не го разбират :P

tommy.bg

  • Напреднали
  • *****
  • Публикации: 63
  • Distribution: Ubuntu
  • Window Manager: Gnome
    • Профил
Версията на php e 5.2.12. Хоства се в superhosting.bg
Активен

neter

  • Global Moderator
  • Напреднали
  • *****
  • Публикации: 3408
  • Distribution: Debian, SailfishOS, CentOS
  • Window Manager: LXDE, Lipstick
    • Профил
    • WWW
сега ми дава грешка "Parse error: syntax error, unexpected $end in /home/evraziab/public_html/upload.php on line 456"
Не си затворил кода с ?> накрая ;)
Активен

"Да си добре приспособен към болно общество не е признак за добро здраве" - Джиду Кришнамурти