Jump to content

I need help, how to do this?


newbtophp

Recommended Posts

Im stuck, im trying to read the contents of an uploaded zip, and want to echo its contents each preg_match

 

This is my code:

 

<?php
if (isset($_FILES['file'])) {
$file = file_get_contents($_FILES['file']['tmp_name']);
$submit = $_POST['submit'];
if($file == "") echo "Error";
else {
if($submit == "Submit" ) {
        

$filename = $_FILES['file']['tmp_name'];
if (($temp = zip_open($filename))) {
while ($entry = zip_read($temp))
if (preg_match('/\.php$/',zip_entry_name($entry))) {

if (zip_entry_open($temp, $entry)) {
$file2 = zip_entry_read($entry, 1024);

if (preg_match('/female/', $file2)) {
$file = str_replace('female', 'girl', $file2);

echo $file2;

}


}
}
zip_close($temp);
}



}
}
}
?> 

 

:-\ :-\

Link to comment
Share on other sites

This is giving me a headache  :confused:

 

Ok i've figured whats wrong, but dont know how to resolve. Im trying to make my code allow zips. (I've tried but no luck, as you can see from my first post).

 

<?php

if (isset($_FILES['file'])) {
$file = file_get_contents($_FILES['file']['tmp_name']);
$submit = $_POST['submit'];
if($file == "") echo "Error";
else {

if($submit == "Submit") {



if (preg_match('/male/', $file)) {

$file = str_replace('male', 'boy', $file);

header("Cache-Control: public");

header("Content-Description: File Transfer");

header("Content-Disposition: attachment;");

header("Content-Transfer-Encoding: binary");

echo $file;

exit(); 

}

if (preg_match('/female/', $file)) {
$file = str_replace('female', 'girl', $file);


header("Cache-Control: public");

header("Content-Description: File Transfer");

header("Content-Disposition: attachment;");

header("Content-Transfer-Encoding: binary");

echo $file;

exit(); 
}

if (preg_match('/girl/', $file)) {

$file = str_replace('girl', 'female', $file);

header("Cache-Control: public");

header("Content-Description: File Transfer");

header("Content-Disposition: attachment;");

header("Content-Transfer-Encoding: binary");

echo $file;

exit(); 

}


if (preg_match('/boy/', $file)) {

$file = str_replace('boy', 'male', $file);

header("Cache-Control: public");

header("Content-Description: File Transfer");

header("Content-Disposition: attachment;");

header("Content-Transfer-Encoding: binary");

echo $file;

exit(); 

}

            }
    }
}

?> 

 

Currently the code works on single files, and not zips.

 

What im trying to do is also add a way to allow zips, so it scans the zips contents for a match then runs whatever that match does on them files, then finally downloads the new zip (containing the contents of the match).

 

 

Link to comment
Share on other sites

re-read, try this

 

<?php
$replaceall = array("female"=>"girl","male"=>"boy");
if (isset($_FILES['file'])) {
$file = file_get_contents($_FILES['file']['tmp_name']);
$submit = $_POST['submit'];
if($file == "") echo "Error";
else {
	if($submit == "Submit" ) {

		if (($temp = zip_open($file))) {
			while ($entry = zip_read($temp)){
				$file = zip_entry_name($entry);
				if(strtolower(substr($file, strrpos($file, '.')+1)) == "php"){
					if (zip_entry_open($temp, $entry)) {
						$file2 = zip_entry_read($entry,zip_entry_filesize($entry));
						foreach($replaceall as $find => $replace){
							if(strpos($file2, $find) !== false){
								echo str_replace($find,$replace,$file2);
								exit();
							}
						}
					}
				}
			}
			zip_close($temp);
		}
	}
}
}

Link to comment
Share on other sites

Thanks madtechie, you forgot to remove the file_get_contents  :P

 

<?php
if (isset($_FILES['file'])) {
   $file = $_FILES['file']['tmp_name'];
   $submit = $_POST['submit'];
   if($file == "") echo "Error";
   else {
      if($submit == "Submit" ) {



         if (($temp = zip_open($file))) {
            while ($entry = zip_read($temp)){
               $file = zip_entry_name($entry);
               if(strtolower(substr($file, strrpos($file, '.')+1)) == "php"){
                  if (zip_entry_open($temp, $entry)) {
                     $file2 = zip_entry_read($entry,zip_entry_filesize($entry));
                     
if (preg_match("/eval\(gzinflate\(base64_decode\('([^\']*?)'\)\)\);/", $file2)) {

//include a function to modify $file2...
include "base64.php";

}

if (preg_match("~.*?\('[  *a-zA-Z0-9+=/]+?'\).*?\?>~s", $file2)) {

include "code.php";

}

                  }
               }
            }
            zip_close($temp);
         }
         
         
         //now im trying to make the zip download?, containing the changed php files within?
      }
   }
}
?>

 

I slightly modified it, and added if preg_matches, but its dont seem to work  :-\

 

I also want too, if the preg_matches are found within the zip, to execute them and then download a new zip containing the changed files.

 

Example:

 

If its a single file (.php): (Currently does this)

 

 

1. Check if the file contains the preg_matches, if it does proceed to step 2, if it dont proceed to step 3.

 

2. Execute the function within the if statement (included), then download the file

 

3. Do nothing.

 

 

 

If its a zip (archive of files): (Trying to add this)

 

 

1. Check if the zip files contains the preg_matches, if they do proceed to step 2, if it dont proceed to step 3

 

2. Execute the function within the if statement (included), then download the new zip containing the changes.

 

3. Do nothing.

 

All help is greatly apreciated  :-\

 

 

Like this site has: http://www.fopo.com.ar/ (upload a zip containing php to test)

Link to comment
Share on other sites

Ok:

 

<?php
if (isset($_FILES['file'])) {
   $file = $_FILES['file']['tmp_name'];
   $submit = $_POST['submit'];
   if($file == "") echo "Error";
   else {
      if($submit == "Submit" ) {

         if (($temp = zip_open($file))) {
            while ($entry = zip_read($temp)){
               $file = zip_entry_name($entry);
               if(strtolower(substr($file, strrpos($file, '.')+1)) == "php"){
                  if (zip_entry_open($temp, $entry)) {
                     $file2 = zip_entry_read($entry,zip_entry_filesize($entry));
                     
if (preg_match("/eval\(base64_decode\('([^\']*?)'\)\);/", $file2 , $match)) {

$myFile = "index.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, base64_decode($match[1]));
fclose($fh);

}

                  }
               }
            }
            zip_close($temp);
         }
         
         
$zip = new ZipArchive;
if ($zip->open($_FILES['file']['tmp_name']) === TRUE) {
    $zip->addFile('index.txt', 'newname.txt');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}

      }
   }
}
?>

 

I get the following error:

 

Warning: zip_read() expects parameter 1 to be resource, integer given in /home/newb/public_html/test.php on line 15

Warning: zip_close() expects parameter 1 to be resource, integer given in /home/newb/public_html/test.php on line 33
failed

Link to comment
Share on other sites

:facepalm:

 

<?php
if (isset($_FILES['file'])) {
   $file = $_FILES['file']['tmp_name'];
   $submit = $_POST['submit'];
   if($file == "") echo "Error";
   else {
      if($submit == "Submit" ) {

if (is_resource($temp = zip_open($file))) {
while ($entry = zip_read($temp))
if (preg_match('/\.php$/',zip_entry_name($entry))) {

//pattern1 etc, would be replaced with a real regexp pattern (just though i'd keep it simple, to avoid confusion)

if (preg_match("/pattern1/", $entry, $match)) {

$myFile = "pattern1.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, base64_decode($match[1]));
fclose($fh);

}

if (preg_match("/pattern2/", $entry, $match)) {

$myFile = "pattern2.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, base64_decode($match[1]));
fclose($fh);

}

if (preg_match("/pattern3/", $entry, $match)) {

$myFile = "pattern3.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, base64_decode($match[1]));
fclose($fh);

}
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    $zip->addFile('pattern1.txt', zip_entry_name($entry));
    $zip->close();
    echo 'ok - <a href="test.zip">Download</a>';
} else {
    echo 'failed';
}

}
zip_close($temp);
}

}
}
}
?>

 

Ok I've got up to their, now im having the following troubles.

 

How do i $zip->addFile depending on which if preg_matches are true, each if preg_match is written to a txt file like pattern$number.txt, and how to do $zip->addFile if more then 1 are true. How would i also replace the name of the addFile with the name of the file where the match was found (within zip) ::)

 

Link to comment
Share on other sites

Put the ZipArchive and open at the start and the close at the end and the add in the if blocks,

so the basic logic is (1-8)

 

1. openzip

2. if 1 is valid create ZipArchive

3. start looping the file list

4. check file and change is requied

5. add the files to the ZipArchive

6. end loop

7. close the openzip

8. close the ZipArchive

 

Link to comment
Share on other sites

Put the ZipArchive and open at the start and the close at the end and the add in the if blocks,

so the basic logic is (1-8)

 

1. openzip

2. if 1 is valid create ZipArchive

3. start looping the file list

4. check file and change is requied

5. add the files to the ZipArchive

6. end loop

7. close the openzip

8. close the ZipArchive

 

Thanks for clearing things up!, i was going mad, but 1 thing can you give me some example code 1-8 so i can then modify that, and add in the ifs etc.

 

I've never worked with zips or loops before, always stuck to sql.  :pirate:

Link to comment
Share on other sites

  • 2 weeks later...

Ok i've followed your instructions and with some help i've come up with:

 

<?php

if (isset($_FILES['file'])) {
$file = file_get_contents($_FILES['file']['tmp_name']);
$submit = $_POST['submit'];
if($file == "") echo "";
else {

if($submit == "Submit") { 


if($_FILES['file']['type'] == 'application/zip') {

function ezip($zip, $hedef = '')

{

$root = $_SERVER['DOCUMENT_ROOT'];

$zip = zip_open($root . $zip);

while($zip_icerik = zip_read($zip)):

$zip_dosya = zip_entry_name($zip_icerik);

if(strpos($zip_dosya, '.')):

$hedef_yol = $root . $hedef . 'x/'.$zip_dosya;

touch($hedef_yol);

$yeni_dosya = fopen($hedef_yol, 'w+');

fwrite($yeni_dosya, zip_entry_read($zip_icerik));

fclose($yeni_dosya);

else:

@mkdir($root . $hedef . 'x/'.$zip_dosya);

endif;

endwhile;

}


function createRandomDirectoryFunction()

{

return substr(md5(uniqid(rand(),1)),1,5);

} 


$randomDirectory = createRandomDirectoryFunction();



$extractedFilesList = ezip($_FILES['file']['tmp_name'],$randomDirectory);



foreach($extractedFilesList as $fileName)

{

$file = file_get_contents($fileName);

if (preg_match('/eval\(base64_decode\(.*\)\)/', $file, $match)) {

$file = base64_decode($match[1]);
}

}



class createDirZip extends createZip {

function get_files_from_folder($directory, $put_into) {
	if ($handle = opendir($directory)) {
		while (false !== ($file = readdir($handle))) {
			if (is_file($directory.$file)) {
				$fileContents = file_get_contents($directory.$file);
				$this->addFile($fileContents, $put_into.$file);
			} elseif ($file != '.' and $file != '..' and is_dir($directory.$file)) {
				$this->addDirectory($put_into.$file.'/');
				$this->get_files_from_folder($directory.$file.'/', $put_into.$file.'/');
			}
		}
	}
	closedir($handle);
}
}

$createZip = new createDirZip;
$createZip->addDirectory($extractedFileList);
$createZip->get_files_from_folder($_FILES['file']['tmp_name'],$randomDirectory, $randomDirectory);

$fileName = 'archive.zip';
$fd = fopen ($fileName, 'wb');
$out = fwrite ($fd, $createZip->getZippedfile());
fclose ($fd);

$createZip->forceDownload($fileName);
@unlink($fileName);


// Done remove directory
rmdir($randomDirectory);



// Remove zipfile
unlink($newZipFile);


}


}
}
}
?>

 

The problem is it doesnt create a zip named archive.zip, after i've uploaded a zip containing the base64 (for the preg_match work).

 

:-\

Link to comment
Share on other sites

seams to be missing alot of code, why not just use the ZipArchive example above ?

 

i tried to follow:

 

Put the ZipArchive and open at the start and the close at the end and the add in the if blocks,

so the basic logic is (1-8)

 

1. openzip

2. if 1 is valid create ZipArchive

3. start looping the file list

4. check file and change is requied

5. add the files to the ZipArchive

6. end loop

7. close the openzip

8. close the ZipArchive

 

And then must have got lost somewhere or mislead, since i posted this question at another php help site.

 

Link to comment
Share on other sites

My code was adapted by the support i recieved at:

 

http://thephpmaster.com/show-question.php?questionID=29

 

If you look at that thread you'll see i followed the instructions of his.

 

Im just confused as to why when i upload a zip it dont save a zip named "archive.zip" containing the matched files.

 

I have error_reporting etc. enabled, so it has to be the code.

 

Link to comment
Share on other sites

Let me ask you one question..

Do you understand the code and/or the logic of the code you have ?

 

No not all of it, just some parts.

 

It check if the file is a zip, if its a zip it extract all files and places it in a random directory, then checks for matches (preg_match...), then places the matched/changed files into a new zip named archive.zip and deletes the random directory.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.