Script

Filter
2004-10-02

Referenser i variabler eller funktioner

Php
By reference är samma sak som att använda globala variabler
<?php 
$name = 'Rolf'; 
$namn = &$name; // $namn är nu en reference till $name 
$namn .= ' Fredriksson'; 
print("Jag heter $name.<br><br>\n"); 

function half(&$num) { // by reference (&)
    $num /= 2; 
    // return $num; behövs inte
}

$myNum = 30; 
print("Hälften av $myNum är: ");
half($myNum); 
print($myNum);
?> 
2004-10-02

Variabla variabler

Php
Ett sätt att namnge en variabel med ett variabelt namn
<?php 
$myStr = "I"; 
$$myStr = "am"; 
$$$myStr = "great."; 

// Hmm... where did these variables come from? 
echo "$myStr "; 
echo "$I "; 
echo "$am\n"; 

// Now for the moment of truth ..."; 
$am = "exaggerating."; 

// It works the other way too! 
echo "$myStr "; 
echo "${$myStr} "; 
echo "${${$myStr}}\n "; 


// Ett praktiskt exempel: Parsa en configfil, typ:
// # This is sample a configuration file. 
// admin_fname = Amol 
// admin_lname = Hatwar 
// admin_email = amolhatwar@consultant.com 
// admin_login = admin 
// admin_pass = secretstring 
// # File Ends 
 
/* conf_parser.php
** Parses a config file and sets global vars. 
** Give the filename with path info whenever possible. 
*/ 

function conf_parse($file_name) { 
    // @ in front makes the function quiet.
    // Error messages are not printed. 
    $fp = @($file_name, "r") or die("Cannot open $file_name"); 
    while ($conf_line = @fgets($fp, 1024)) {
        // Do stripping after hashes
        $line = ereg_replace("#.*$", "", $line); 
        if ($line == "") { 
            // Drop blank lines
            continue; 
        } 
        // Drop '=' and split
        list($name, $value) = explode ('=', $line);
        $name = trim($name); // Strip spaces. 
        $$name= trim($value); // Define the said variable. 
    }
    fclose($fp) or die("Can't close file $file_name"); 
} 
?> 
2004-10-02

For each

Php
Iteration av alla element
// Lista från formulär (multiple)...
foreach ($_POST['lista'] as $listvarde) { 
    echo "$listvarde<br />"; 
} 

// assoc. array...
foreach ($arr as $nyckel => $varde) { 
    echo '<li>' . $nyckel . ' = ' . $varde; 
} 
2004-09-02

En egen perl-modul

Perl
Skriv din egen felhanterarmodul för CGI-script
#!/usr/bin/perl -wT

# Copy this file to one of the perl-libraries,
# eg: /usr/lib/perl5/site_perl/Rosiro/Error.pm ...
#
# Use the module as follows:
#
# #!/usr/bin/perl -wT
#
# use strict;
# use CGI;
# use Rosiro::Error;
#
# my $q = new CGI;
#
# unless ( check_something_important() ) {
#     error( $q, "Something bad happened." );
# }

package Rosiro::Error;

# Export the error subroutine
use Exporter;
@ISA = "Exporter";
@EXPORT = qw( error );

$VERSION = "0.01";

use strict;
use CGI;
use CGI::Carp qw( fatalsToBrowser );

BEGIN {
    sub carp_error {
        my $error_message = shift;
        my $q = new CGI;
        my $discard_this = $q->header( "text/html" );
        error( $q, $error_message );
    }
    CGI::Carp::set_message( \&carp_error );
}

sub error {
    my( $q, $error_message ) = @_;
    print $q->header( "text/html" ),
        $q->start_html( "Error" ),
        $q->h2( "Error" ),
        $q->p( "Sorry, the following error has occurred: " ),
        $q->p( $q->i( $error_message ) ),
        $q->end_html;
    exit;
}

1; 
2004-09-02

Upload file via CGI

Perl
Ladda upp filer med CGI.pm
#!/usr/bin/perl -wT

use strict;
use CGI;
use Fcntl qw(:DEFAULT :flock);

use constant UPLOAD_DIR     => "/var/www/cgi-bin/upload/";
use constant BUFFER_SIZE    => 16_384;
use constant MAX_FILE_SIZE  => 1_048_576;
use constant MAX_DIR_SIZE   => 100 * 1_048_576;
use constant MAX_OPEN_TRIES => 100;

$CGI::DISABLE_UPLOADS = 0;
$CGI::POST_MAX        = MAX_FILE_SIZE;

my $q = new CGI;
$q->cgi_error and error($q, "Error transferring file: " . $q->cgi_error);

# lodstrecken i "or" tyvärr borta här...
my $file      = $q->param("file")        error($q, "No file recieved.");
my $filename  = $q->param("filename")    error($q, "No filename entered.");
my $fh        = $q->upload("file")        error($q, "Error uploading file...");
my $buffer    = "";

if (dir_size(UPLOAD_DIR) + $ENV{CONTENT_LENGTH} > MAX_DIR_SIZE) {
    error($q, "Upload directory is full.");
}

# Allow letters, digits, underscores,
# convert anything else to underscore...
$filename =~ s/[^\w.-]/_/g;
if ($filename =~ /^(\w[\w-]*)(.[\w.-]+)?/) {
    $filename = $1 . ($2    '.err');
} else {
    error($q, "Invalid file name; files must start with a letter or number.");
}

# Open output file, making sure the name is unique
until (sysopen OUTPUT, UPLOAD_DIR . $filename, O_CREAT   O_RDWR   O_EXCL) {
    $filename =~ s/(\d*)(\.\w+)$/($1  0) + 1 . $2/e;
    $1 >= MAX_OPEN_TRIES and error($q, "Unable to save your file.");
}

# This is necessary for non-Unix systems - harmless on Unix
# convert newlines on non-unix-systems...
binmode $fh;
binmode OUTPUT;

# Write contents to output file...
while (read($fh, $buffer, BUFFER_SIZE)) {
    print OUTPUT $buffer;
}

close OUTPUT;

print $q->header("text/plain"), "File recieved.";

sub dir_size {
    my $dir = shift;
    my $dir_size = 0;
    
    # Loop through files and sum the sizes (no subdirs)
    opendir DIR, $dir or die "Unable to open $dir: $!";
    foreach(readdir DIR) {
        $dir_size += -s "$dir/$_";
    }
    return $dir_size;
}

sub error {
    my($q, $reason) = @_;
    
    print $q->header("text/html"),
        $q->start_html("Error"),
        $q->h2("Error"),
        $q->p("Your upload was not processed because the following error occurred:"),
        $q->p( $q->i($reason) ),
        $q->end_html;
    exit;
}

# lodstrecken tyvärr borta i koden... 
🙂