Page 1 of 1

Problem with fsockopen and extra bytes being written.

Posted: Mon Nov 18, 2002 5:11 am
by littlebigman_uk
I am trying to create a php page that will download a zip file onto a clients machine. I have managed to create the php page and it downloads ok. The BIG problem i have is that it is adding some extra bytes to the size of the file. I have tested this using a text file with the values 1 - 10. I then renamed the extension to .zip. I downloaded the file then renamed the extension back to .txt. The file was perfect but it was 10 bytes bigger than the original file????

This is fine for text files but it doesn't work for true zip files as i get an error when i try to unzip it.The code is below. Can someone help please.


<?php
$fp=fsockopen("localhost",80,$errno,$errstr,30);
if (!$fp)
{
echo "Could not connect to server!<br>\n";
echo $errstr;
flush();
return false;
}

$gSource = $_GET['source'];
$gTarget = $_GET['target'];

$pSource = "GET ";
$pSource .= "/sourcefiles/";
$pSource .= $gSource;
$pSource .= " HTTP/1.0\n\n";

$pTarget = $gTarget;
$pTarget .= $gSource;

echo $pSource;
echo $pTarget;

?>

<html>
<h1 align="center"><b>File Download</b></h1>
<div align="center">
<center>
<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" id="AutoNumber1">
<tr>
<td width="100%" colspan="2">
<h3 align="left">Download</h3>
</td>
</tr>
<tr>
<td width="50%">Filename:</td>
<td width="50%"><?php echo $gSource; ?>&nbsp;</td>
</tr>
<tr>
<td width="50%">Save To:</td>
<td width="50%"><?php echo $gTarget; ?>&nbsp;</td>
</tr>
</table>
</center>
</div>
<p>&nbsp;

<?php
$errno=fputs($fp,$pSource);
if ($errno == 31)
{
echo "File Not Found!";
flush();
return false;
}

$cstring = "<br>\n";
$cstring .= fgets($fp,512);
$cstring .= "<br>\n";
$cstring .= fgets($fp,512);
$cstring .= "<br>\n";
$cstring .= fgets($fp,512);
$cstring .= "<br>\n";
$cstring .= fgets($fp,512);
$cstring .= "<br>\n";
$cstring .= fgets($fp,512);
$cstring .= "<br>\n";
$cstring .= fgets($fp,512);
$cstring .= "<br>\n";
$cstring .= fgets($fp,512);
$cstring .= "<br>\n";
$cstring .= fgets($fp,512);
$cstring .= "<br>\n";
$cstring .= fgets($fp,512);
$cstring .= "<br>\n";
$cstring .= fgets($fp,512);
$cstring .= "<br>\n";

echo $cstring;
echo "<br>\n";
echo "Start Download:";
//return false;
flush();
while (!feof($fp))
{
$result.= fread ($fp,10240);
}
fclose ($fp);

$length=strlen($result);
echo "OK ($length)<BR>";
flush();
echo "Saving to $pTarget ...";
flush();
$fh=fopen($pTarget,"w");
if ($fh!=false)
{
fwrite($fh, $result);
flock($fh,3);
fclose($fh);
echo "OK<BR>";
flush();
}
else
{
echo "Unable to save";
flush();
}
echo $result;
?> </p>
</html>