Skip to content

HTML, Script file

Yòmá edited this page Dec 29, 2022 · 10 revisions

Directory List Example

  • Directory Listing.html
<html>
  <head>
    <title>Directory Listing</title>
  </head>
  <body>
    <h1>Directory Listing</h1>
    <ul>
      <li><a href="file1.html">file1.html</a></li>
      <li><a href="file2.html">file2.html</a></li>
      <li><a href="file3.html">file3.html</a></li>
    </ul>
  </body>
</html>
  • Directory Listing.php
<html>
  <body>
    <h1>Current Directory List</h1>
    <ul>
      <?php
      // Open the current directory
      $dir = opendir('.');
      // Loop through the files in the directory
      while (($file = readdir($dir)) !== false) {
        if ($file != "." && $file != "..") {
          // Print the file name as a list item
          echo "<li>$file</li>";
        }
      }
      // Close the directory
      closedir($dir);
      ?>
    </ul>
  </body>
</html>


File Upload Example

<html>
  <body>
    <form action="/upload" method="post" enctype="multipart/form-data">
      <label for="file">Select a file:</label>
      <input type="file" id="file" name="file">
      <br>
      <input type="submit" value="Upload">
    </form>
  </body>
</html>
<html>
  <body>
    <form enctype = "multipart/form-data" action = "python_script.py" method = "post">
      <p>Upload File: <input type = "file" name = "filename" /></p>
      <p><input type = "submit" value = "Upload" /></p>
    </form>
  </body>
</html>

python upload cgi

#!/usr/bin/python
import cgi, os
import cgitb; cgitb.enable()
# import cgitb; cgitb.enable(display=0, logdir="./log")

save_path = os.getenv("SAVED_PATH")

if save_path is None:
	save_path = "./tmp/"
else:
	save_path += "/"

if not os.path.exists(save_path):
	os.mkdir(save_path)

print("Content-Type: text/html")
# Parse the form data
form = cgi.FieldStorage()
# Extract the uploaded files
files = {}
for field in form.keys():
	# Check if the field is a file field
	if isinstance(form[field], cgi.FieldStorage) and form[field].filename:
		# Save the file to the specified location
		with open(save_path + form[field].filename, 'wb') as f:
			f.write(form[field].file.read())
		files[field] = form[field].filename

if len(files) > 0:
	message = "file uploaded success"
else:
	message = "file uploaded failed"

# Print the uploaded files
response = "<html><body><center>"
response += "<h1>{}<h1>".format(message)
for field, filename in files.items():
    response += "<p>{}: {}</p>\n".format(field, filename)
response += "</center></body></html>"

print("Content-Length: {}".format(len(response)))
print()
print(response)




Add CGI

  • Here is a simple CGI program written in Python 3 along with the HTML that handles a simple addition problem.

add.html:

<!DOCTYPE html>
<html>
 <body>
  <form action="add.cgi" method="POST">
   <fieldset>
     <legend>Enter two numbers to add</legend>
     <label>First Number: <input type="number" name="num1"></label><br/>
     <label>Second Number: <input type="number" name="num2"></label><br/>
   </fieldset>
   <button>Add</button>
  </form>
 </body>
</html>

add.cgi:

#!/usr/bin/env python3

import cgi, cgitb
cgitb.enable()

input_data = cgi.FieldStorage()

print('Content-Type: text/html') # HTML is following
print('')                         # Leave a blank line
print('<h1>Addition Results</h1>')
try:
    num1 = int(input_data["num1"].value)
    num2 = int(input_data["num2"].value)
except:
    print('<output>Sorry, the script cannot turn your inputs into numbers (integers).</output>')
    raise SystemExit(1)
print('<output>{0} + {1} = {2}</output>'.format(num1, num2, num1 + num2))

This Python 3 CGI program gets the inputs from the HTML and adds the two numbers together.

#!/usr/bin/perl

use CGI;

# Create a new CGI object
my $cgi = CGI->new;

# Get the values of the two numbers to add from the query string
my $num1 = $cgi->param('num1');
my $num2 = $cgi->param('num2');

# Convert the numbers to integers
$num1 = int($num1);
$num2 = int($num2);

# Add the numbers
my $sum = $num1 + $num2;

# Print the HTML response
print $cgi->header,
      $cgi->start_html("Addition Result"),
      $cgi->h1("Addition Result"),
      $cgi->p("The sum of $num1 and $num2 is $sum."),
      $cgi->end_html;
  • path/?num1=5&num2=7

The following Perl program shows all the environment variables passed by the Web server:

#!/usr/bin/env perl

=head1 DESCRIPTION

printenv — a CGI program that just prints its environment

=cut
print "Content-Type: text/plain\n\n";

foreach ( sort keys %ENV ) {
    print "$_=\"$ENV{$_}\"\n";
}

Clone this wiki locally