perl кодеры помощь нужна.

Discussion in 'PHP' started by guest3297, 26 Feb 2007.

  1. guest3297

    guest3297 Banned

    Joined:
    27 Jun 2006
    Messages:
    1,246
    Likes Received:
    639
    Reputations:
    817
    Code:
    #!/usr/bin/perl
    
    ### Virtual Webwerx Form-Based Upload CGI
    ### v1.0 (17 Feb 96) by James K. Boutcher (geewhiz@novia.net)
    ### Feel free to use, modify, distribute.. But remember to give some credit
    ### where credit is due.
    ###
    ### If you are having problems with this, or have a bug to report, just send
    ### me some mail
    
    
    # Let's define our variables first off.. 
    $| = 1;  
    $upath = "/stor/mp3/webuploads/";
    $uindex = "/stor/mp3/webuploads/upload.index";
    $tempfile = $upath . $ENV{'REMOTE_ADDR'};
    $nofileerror = "/upload.html";
    
    # The following reads in the CGI buffer, and writes it to a temporary file
    # which will used later.
    read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
    open (x,">$tempfile");
    print x $buffer;
    close (x);
    
    
    # Now, time to open the temporary file and process it!
    open (temp,$tempfile);
    
    
    # Gotta pull the MIME/multipart separator line out.. We'll keep the 15 
    # digit number for later...
    $_ = <temp>;
    ($vernum) = /(\d+)/;
    
    
    # Next line of the file contains the filename in the format: 
    #     filename="C:\windows\win.ini"
    # We'll just keep the part inside the quotes...
    $_ = <temp>;
    $filetemp = $1 if (/filename=\"(.*)\"/); 
    
    
    # The filename currently has the full pathname to the file in it.. We
    # don't want that! .. First we grab the last word after the backslash (for
    # PC systems), then we're gunna grab the last word after the forward slash
    # (unix systems).. Don't worry, it works.
    @pathz = (split(/\\/,$filetemp));
    $filetempb = $pathz[$#pathz];
    @pathza = (split('/',$filetempb));
    $filename = $pathza[$#pathza];
    
    
    # And, if the filename is nothing, we'll clean everything up and give them
    # a pretty error message
    if ($filename eq "") {
    	print "Location: $nofileerror\n\n";
    	close(temp);
    	`rm $tempfile`;
    	}
    
    
    # Now that we know the name of the file, let's create it in our upload
    # directory..
    open (outfile, ">$upath$filename");
    
    
    # Now we don't care about the Content-type of this, so we'll pass that up
    $junk = <temp>; 
    $junk = <temp>;
    
    
    # And we're gunna read/write all the lines of our file until we come to the
    # MIME-multipart separator, which we'll ignore.
    while (<temp>) {
       if (!(/-{28,29}$vernum/)) {
    		print outfile $_;
    		}
       }
    
    # We're done with that.. Let's close things up and remove that temp file.
    close (temp);
    close (outfile);
    `rm $tempfile`;
    
    
    # And bust da HTML
    print "Content-type: text/html\n\n";
    print "<html><title>Form Upload</title><body>\n";
    print "You may now go to the <A HREF=\"http://206.54.177.102:84\">WebAmp</A> page and search for your file in the webuploads directory.<br><br>\n";
    print "</body></html>";
    Просьюба корректно обьяснить куда загружаеться файл, если скрипт лежит в /cgi-bin/ ?
    Какое имя назначаеться и так далее.
    Учитывай то что пути прописанные в файле истины.
     
  2. k1b0rg

    k1b0rg Тут может быть ваша реклама.

    Joined:
    30 Jul 2005
    Messages:
    1,182
    Likes Received:
    399
    Reputations:
    479
    сначала создается в папке /stor/mp3/webuploads/"твой ип", временный файл с длиной запроса.
    Потом этот файл читается, и это число присваивается переменной $vernum.

    Затем стоит проверка, если filename определен, и лежит в ковычках то присваивается переменой filetemp (в этом скрипте filname закомментирован)

    @pathz присваиваем файл filetemp. деленный по \
    $filetempb присваиваем последний эл. массива
    @pathza делим $filetempb по /
    $filename последний эл. @pathza


    если filname пустой, посылаем накуй редиректом, удаляем тем файл.

    открывается файл /stor/mp3/webuploads/$filname, производится проверка содержания у tempfile и записывается в $filename.

    удаляем темпфайл.

    вроде всё
     
    2 people like this.
  3. darky

    darky ♠ ♦ ♣ ♥

    Joined:
    18 May 2006
    Messages:
    1,773
    Likes Received:
    825
    Reputations:
    1,418
    как то по наркомански скрипт написан )) не проще -

    Code:
    #!/usr/bin/perl -w 
    
     use CGI; 
    
     $upload_dir = "/home/mywebsite/htdocs/upload"; 
    
     $query = new CGI; 
    
     $filename = $query->param("file"); 
     $filename =~ s/.*[\/\\](.*)/$1/; 
     $upload_filehandle = $query->upload("file"); 
    
     open UPLOADFILE, ">$upload_dir/$filename"; 
    
     binmode UPLOADFILE; 
    
     while ( <$upload_filehandle> ) 
     { 
       print UPLOADFILE; 
     } 
    
     close UPLOADFILE; 
    
     print $query->header ( ); 
     print <<END_HTML; 
    
     <HTML> 
     <HEAD> 
     <TITLE>Thanks!</TITLE> 
     </HEAD> 
    
     <BODY> 
    
     <P>Uploaded нах=)</P> 
    
     </BODY> 
     </HTML> 
    
     END_HTML
    
     
    #3 darky, 27 Feb 2007
    Last edited: 27 Feb 2007
    2 people like this.
  4. guest3297

    guest3297 Banned

    Joined:
    27 Jun 2006
    Messages:
    1,246
    Likes Received:
    639
    Reputations:
    817
    ты это админам скажи ))) был бы рад если он такой был )))
     
  5. temp_late

    temp_late Banned

    Joined:
    22 Aug 2006
    Messages:
    47
    Likes Received:
    7
    Reputations:
    2
    Нужна помощь


    Есть форма[для примера]:
    PHP:
    <html><body>
    <
    form action='txt.php' name='message' method="post">
    <
    textarea name="str" cols="105" rows="11">
    Какойто
    текст
    содержащие
    переходы
    на
    другие строки
    </textarea><input type="submit" value='go'></form></body></html>

    Скрипт обработчик[txt.php]:
    PHP:
    <?php
    $a
    =eregi_replace("\\n","",$_POST["str"]); //По идее здесь удаляем все переходы на новые строки
    echo "<pre>$a</pre>";
    ?> 
    Столкнулся с проблемой, по задумки мне нужно из формы textarea взять текст и вырезать из него все переходы на новые строки, короче забить весь текст в одну строковую переменную не в массиве, только у меня ничего не получается.

    В дальнейшем я это хотел использовать этот вид для хранение в файле, - 1 строчка - 1 сообщение, а пока получаеться не то, что нужно, сообщение одно, а в файл записываеться с этими переходами и получаеться что у меня там больше, при считывание из него по строчкам суть сообщения теряеться.

    ps: Извеняюсь что в тему о помощи с Perl ответил, просто решил не засерать форум увидел что в этой теме разбирают проблеммы, обрадовался что не придеться создавать еще одну. Глаза уже слепаються третей день сижу над этой проблеммы перечитал кучу страниц а ответов так и не нашол...
     
    #5 temp_late, 28 Feb 2007
    Last edited: 28 Feb 2007
  6. darky

    darky ♠ ♦ ♣ ♥

    Joined:
    18 May 2006
    Messages:
    1,773
    Likes Received:
    825
    Reputations:
    1,418
    А зачем тогда брать textarea.. ведь он спец под многострочные данные..
     
  7. Talisman

    Talisman Elder - Старейшина

    Joined:
    22 Apr 2006
    Messages:
    400
    Likes Received:
    151
    Reputations:
    80
    имхо перед записью в файл кодирую данные например base64_(en|de)code :) и если в файле есть еще бред, типа логина и имени, то обезопасишь себя от части атак.
     
  8. DRON-ANARCHY

    DRON-ANARCHY Отец порядка

    Joined:
    4 Mar 2005
    Messages:
    716
    Likes Received:
    142
    Reputations:
    50
    Ну короче я понял, что тебе нужна всего одна функция - str_replace()
    попробуй такой вариант решения:
    PHP:
    <?
    $a=str_replace("\n","",$_POST["str"]); //вот тут удаляем переходы
    echo "<pre>$a</pre>"

    ?>
     
  9. NaX[no]rT

    NaX[no]rT Members of Antichat

    Joined:
    3 Sep 2005
    Messages:
    489
    Likes Received:
    201
    Reputations:
    202
    Code:
    $str = implode(explode("\n",$_POST['str']));
     
    _________________________
  10. DRON-ANARCHY

    DRON-ANARCHY Отец порядка

    Joined:
    4 Mar 2005
    Messages:
    716
    Likes Received:
    142
    Reputations:
    50
    так вот кто придумал Windows Vista !!!))))