Large CSV download script timing out - php

I have a a script that can upload the contents of a CSV file and download the links to a local directory, the CSV file i need to upload to it is about 4056 lines long and 4056 FTP downloads, the script works fine but the web server times out when i use it.
even tried set_time_limit(0);
is there a way i could session the script and loop the process so it could do it's job for a few hours without interruptions.
<?php
/**
* Please change your upload directory according to your needs. Make sure you include the trailing slash!
*
* Windows C:\tmp\
* Linux /tmp/
*/
$uploaddir = '/tmp/';
if(isset($_FILES['userfile']['name'])){
// Read uploaded file
$lines = file($_FILES['userfile']['tmp_name']);
echo "Reading file ... <br/>";
$linecount = 0;
foreach($lines as $line ){
echo ++$linecount . ". FTP Url is : " .$line . "<br/>";
echo " Downloading " . $line . "<br/>";
$parsed_url_values = parse_url($line);
//TODO perhaps do a validation of the ftp url??
if($parsed_url_values['scheme'] == 'ftp'){
// set up basic connection
$conn_id = ftp_connect($parsed_url_values['host']);
// login with username and password
$login_result = ftp_login($conn_id, $parsed_url_values['user'], $parsed_url_values['pass']);
ftp_pasv($conn_id, true);
$path = rtrim($parsed_url_values['path'], '_');
$filename = basename($path);
if (ftp_get($conn_id, $uploaddir . $filename, $path , FTP_BINARY)) {
echo " Successfully downloaded the file " .$line . "<br/>";
} else {
echo " Could not save the file to " . $line . ". Please verify the url is correct and the file exists.<br/>";
}
} else {
echo " Sorry. This script was made for FTP downloads only.";
}
}
}
?>
<form enctype="multipart/form-data" action="" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
Select the file to upload : <input name="userfile" type="file" />
<input type="submit" value="Upload" />
</form>

You need to increase the execution time of your script by using max_execution_time. You can use this example, place it on top of your script:
<?php
ini_set('max_execution_time', 300); //300 seconds = 5 minutes
.. The rest of your script
Hope this will help you!

In my practice I often use step by step loading if i can't load data via cron or php cli.
Something like that (not tested):
<?php
$newFileName = '/path/to/file.csv';
$line = isset($_REQUEST['csvline']) ? (int) $_REQUEST['csvline'] : 0;
$handle = fopen($newFileName, "r");
//10 seconds for each step
$stepTime = 10;
$startTime = time();
$lineCounter = 0;
while (($fileop = fgetcsv($handle)) !== false)
{
//already loaded lines
$lineCounter++;
if ($lineCounter <= $line) continue;
//here goes your script logic
//stops when time goes out
if (time() - $startTime >= $stepTime) break;
}
//next you need to query this script again
//using js maybe (window.location or ajax call)
//so you can see loading progress or any other useful information
//like
if (!feof($handle)) {
echo "<script>window.location = '/your.php?csvline={$lineCounter}'<script>";
}
//you even can start loading from last line before script fails
But i'm sure that using cron is the best solution for your problem.

Related

PHP script saves empty image files when run as cron job

I have a script that downloads images from the external server and saves them in a folder at the root of the website. The script file is also in the root of the website.
folder for images: /public_html/images/
script: /public_html/script.php
When i run file manually (example.com/script.php) all downloaded image files are saved in the folder correctly. But when the file is executed by the cron job all the images are saved with sizes of 0 bytes.
I've tried to empty the folder before the cron job run. I've changed the permissions to 777. Log file when the script runs manually and as cron looks the same.
The cron job is set up in the cpanel crontab.
Please help me figure out what is going on.
$dir = "/home/example/public_html/images/";
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') continue;
unlink($dir.DIRECTORY_SEPARATOR.$item);
}
$ftp_server = 'www2.housescape.org.uk';
$ftp_conn = ftp_connect($ftp_server);
$ftp_user = 'user';
$ftp_pass = 'password';
ftp_set_option($ftp_conn, FTP_TIMEOUT_SEC, 3600);
if(ftp_login($ftp_conn, $ftp_user, $ftp_pass)){
ftp_pasv($ftp_conn, true);
$images = ftp_nlist($ftp_conn, '/images/');
$c = 0;
foreach($images as $image){
$c = $c + 1;
echo "ftp://user:password#www2.housescape.org.uk:21".$image." / ";
$urltoget="ftp://user:password#www2.housescape.org.uk:21".$image;
echo $thefile=basename($image);
echo "<br>";
$content = file_get_contents("ftp://user:password#www2.housescape.org.uk:21".$image);
file_put_contents("/home/example/public_html/images/".$thefile, $content);
}
if ($count1>0) { echo "No File Change"; }
ftp_close($ftp_conn);
}
else{
echo 'Failed Login!';
}
This is only a suggestion to help track down the error, not an answer:
Did you check whether the CRON PHP environment has allow_url_fopen enabled?
<?php
if (!ini_get('allow_url_fopen')) {
die("'allow_url_fopen' is not enabled in the php.ini");
}

Fine Uploader need to chunk a file and rejoin back

I am trying to integrate fine uploader [ Jquery wrapper ] for my PHP project. In that, i am trying to upload a 25MB file by using chunking option.
But what is happening here is, It chunks file and stores as blob0, blob1, blob2...
I want to my original file to be stored in the location. But here, the chunks get stored with a different name. What i have tired so far is,
<div id="jquery-wrapped-fine-uploader"></div>
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.fineuploader-3.5.0.js"></script>
<script>
$(document).ready(function () {
$('#jquery-wrapped-fine-uploader').fineUploader({
debug: true,
request: {
endpoint: 'upload.php',
},
chunking: {
enabled: true,
partSize: 2000000,
paramNames: {
partIndex: 'qqpartindex',
partByteOffset: 'qqpartbyteoffset',
chunkSize: 'qqchunksize',
totalFileSize: 'qqtotalfilesize',
totalParts: 'qqtotalparts',
filename: 'qqfile'
}
}
});
});
</script>
PHP
if ($_FILES["qqfile"]["error"] > 0)
{
echo "Return Code: " . $_FILES["qqfile"]["error"] . "<br>";
} else {
$partIndex = $_POST["qqpartindex"];
$fileName = $_POST["qqfile"];
move_uploaded_file($_FILES["qqfile"]["tmp_name"], "data/" . $_FILES["qqfile"]["name"].$partIndex);
$result['success'] = true;
echo json_encode($result);
}
I don't know where i went wrong and what i have missed. Please someone guide me.
The point is, this is a feature of the fine uploader. The chunks are given as separate files so that in case your upload gets corrupted, you would have a way to compare and discard chunks that are invalid. If you wish to just get the file, what you need is the following:
if ($_FILES["qqfile"]["error"] > 0)
{
echo "Return Code: " . $_FILES["qqfile"]["error"] . "<br>";
} else {
$partIndex = $_POST["qqpartindex"];
$fileName = $_POST["qqfile"];
move_uploaded_file($_FILES["qqfile"]["tmp_name"], "data/" . $_FILES["qqfile"]["name"].$partIndex);
// INSERT CODE HERE TO CHECK THE INTEGRITY OF "data/" . $_FILES["qqfile"]["name"].$partIndex
$file = fopen($filename, 'a');
$content = file_get_contents("data/" . $_FILES["qqfile"]["name"].$partIndex);
if (fwrite($file, $content)) $result['success'] = true;
fclose($file);
echo json_encode($result);
}
, where $filename is the name of the file you are uploading. I would tell you how to get it through this code, but it's probably easier to define it upstream. Also, depending on your upstream code, it will probably be more memory-efficient to do the fopen at the beginning of the upload, and fclose at the end of your code (e.g.
$file = FALSE;
if ($partIndex == 0) $file = fopen("filename");
instead of the line $file = fopen($filename, 'a'); But, in this case you need to fclose($file); only at the end of the upload (or not at all, it will be fclosed once the page loads). But once again, without seeing the rest of your code I cannot know what will work best in this particular case.

Rejoin split file on server using PHP

I am wondering if it is possible to do the following:
Split a file on the local computer to several pieces so I can upload
them on to the FTP server (avoiding this way the file size limit)
Upload all pieces to my web server
Using a PHP script rejoin them together into one file
I know about HJSplit but it is for the other way around situation (to split on server and then rejoin on local computer)
Does anyone know about any possible solution?
This site claims to have some packages for split and then join.
However I am not sure if they work.(Not Tried)
This could make splitting part:
<html>
<body>
<label >
<div align="right" >
</div>
</label>
<form method="POST" action="">
<table>
<tr>
<td>Here you Files to spilited</td>
<td>Value</td>
</tr>
<tr>
<td> For spilt Zip File to paste Its Url</td>
<td><input type="text" name="zipurl" /></td>
</tr>
<tr>
<td>Spilt to Valume Size: part</td>
<td><input type="text" name="spitsize" value="50"/></td>
</tr>
<tr>
<td>Mega bite (1 On/ 0 off) </td>
<td><input type="text" name="megabyte" value="1"/></td>
</tr>
<tr>
<td>Kilo Byte (1 On/ 0 off)</td>
<td><input type="text" name="kilobyte" value="0"/></td>
</tr>
</table>
<input type="submit" name="ssurlsubmit" value="submit" />
</form>
</body>
<?php
$mypath = getcwd();
$mypath = preg_replace('/\\\\/', '/', $mypath);
$targetfolder = $mypath.'/tmp';
echo 'targetfolder is: '.$targetfolder.'<br />';
if (!is_dir("$mypath/tmp")) {
mkdir("$mypath/tmp");
echo 'Dir'.$targetfolder.'created'.'<br />';
}
$targetfolder = $mypath.'/tmp'.'<br />';
/*
if(!file_exists($targetfolder)) {
if(mkdir($targetfolder)) {
echo "Created target folder $targetfolder".br();
}
else{
echo '$targetfolder can not be created'.br();
}
}else
{
echo $targetfolder.'$targetfolder exist '.br();
}
*/
?>
</html>
<?php
/*
--------------------------------------------------
filesplit.php HJSplit compatiple PHP file splitter
--------------------------------------------------
File name:
filesplit.php
Author:
Umit Tirpan 2007-03-22
Umit Tirpan 2008-03-12 [remote file support added]
Author's Website:
http://forum.iyinet.com/
Description:
This PHP script, splits the files into smaller pieces in binary.
It is compatiple with HJSplit, so you can re-join splitted files using HJSplit's Join utility.
It can split a file up to 999 pieces.
What is the use, why will I use this?
Some webmasters do not have shell access to their websites. This prevents them splitting big files, ie. MySQL backups, into smaller files. Splitting a 200Mb file into 10 x 20Mb file may be easy on webmaster to download in pieces.
How to run:
Make sure your webserver has write permission on the target folder.
Edit variables.
Upload (ftp) this file to your webserver or run on your PC.
For security reason, filename is hardcoded. You can modify code to accept $_GET['filename']
Run with your favorite browser.
http://www.<your-web-site>.com/filesplit.php
Or run on shell (ie. ssh)
php filesplit.php
It is Ok to share and modify this code and use in/with your applications. No restrictions.
*/
// ---------------------------
// Edit variables (3 variables)
// ---------------------------
// File to split, is its not in the same folder with filesplit.php, full path is required.
global $ssurl,$filename;
if (isset($_POST['zipurl'])) {
$url=$_POST['zipurl'];
$filename=$_POST['zipurl'];
echo "URL:".$url.'<br />';
}
// $filename = "http://www.iyinet.com/my-big-file.zip";
// Target folder. Splitted files will be stored here. Original file never gets touched.
// Do not append slash! Make sure webserver has write permission on this folder.
$mypath = getcwd();
$mypath = preg_replace('/\\\\/', '/', $mypath);
$targetfolder = $mypath.'/tmp';
echo 'targetfolder is: '.$targetfolder.'<br />';
if (!is_dir("$mypath/tmp")) {
mkdir("$mypath/tmp");
echo 'Dir'.$targetfolder.'created'.'<br />';
}
$targetfolder = $mypath.'/tmp';
// File size in Mb per piece/split.
// For a 200Mb file if piecesize=10 it will create twenty 10Mb files
$piecesize = 50; // splitted file size in MB
if (isset($_POST['spitsize'])) {
$piecesize=$_POST['spitsize'];
}
//$piecesize = 10; // splitted file size in MB
// ---------------------------
// Do NOT edit this section
// ---------------------------
$buffer = 1024;
if (isset($_POST['megabyte'])and $_POST['megabyte']=='1') {
//$piece=$_POST['megabyte'];
$piece = 1048576*$piecesize;
}
if (isset($_POST['kilobyte']) and $_POST['kilobyte']==1) {
//$piece=$_POST['kilobyte'];
$piece = 1024*$piecesize;
}
//$piece = 1048576*$piecesize;
$current = 0;
$splitnum = 1;
if(!file_exists($targetfolder)) {
if(mkdir($targetfolder)) {
echo "Created target folder $targetfolder".br();
}
echo '$targetfolder folder exist'.br();
}
if(!$handle = fopen($filename, "rb")) {
die("Unable to open $filename for read! Make sure you edited filesplit.php correctly!".br());
}
$base_filename = basename($filename);
/*
$ss=substr($base_filename,-4);
echo substr($base_filename,-4).'<br />';
if ($ss=='.zip')
{
$end='.zip';
$base_filename= removeFromEnd($base_filename, '.zip');
}
*/
$piece_name = $targetfolder.'/'.$base_filename.'.'.str_pad($splitnum, 3, "0", STR_PAD_LEFT). $end;
if(!$fw = fopen($piece_name,"w")) {
die("Unable to open $piece_name for write. Make sure target folder is writeable.".br());
}
echo "Splitting $base_filename into $piecesize Mb files ".br()."(last piece may be smaller in size)".br();
echo "Writing $piece_name...".br();
while (!feof($handle) and $splitnum < 999) {
if($current < $piece) {
if($content = fread($handle, $buffer)) {
if(fwrite($fw, $content)) {
$current += $buffer;
} else {
die("filesplit.php is unable to write to target folder. Target folder may not have write permission! Try chmod +w target_folder".br());
}
}
} else {
fclose($fw);
$current = 0;
$splitnum++;
$piece_name = $targetfolder.'/'.$base_filename.'.'.str_pad($splitnum, 3, "0", STR_PAD_LEFT);
echo "Writing $piece_name...".br();
$fw = fopen($piece_name,"w");
}
}
fclose($fw);
fclose($handle);
echo "Done! ".br();
exit;
function br() {
return (!empty($_SERVER['SERVER_SOFTWARE']))?'<br>':"\n";
}
function removeFromEnd($string, $stringToRemove) {
$stringToRemoveLen = strlen($stringToRemove);
$stringLen = strlen($string);
$pos = $stringLen - $stringToRemoveLen;
$out = substr($string, 0, $pos);
return $out;
}
?>
you could test it via :
http://restss2.frogcp.com/tmp/filesplit%2520%282%29.php

Problem with PHP (works on localhost, but errors on web server)

am having some trouble with PHP on the webserver I am using.
I am sure the answer is obvious but for some reason it is eluding me completely.
I have a php file which uploads two files, a before and an after shot of the client.
The script on my server(localhost) works fine, it uploads the files, renames the files to a timestamp and puts the images into there folders for further sorting by another script.
Yet when I upload it to the webserver, and some files work (i.e mel.jpg, test.jpg) but files like IMG_0042.jpg do not work, Im sure the answer is something simple, but is completely eluding me.
Im thinking the underscore may have something to do with it, but cannot for the life of my figure it out, any help greatly appreciated,
thanks very much.
<?php
if(!isset($_COOKIE['auth'])) {
header("Location: login12.php");
exit();
}
$page_title="test";
include('header.html');
// Upload and Rename File
if (isset($_POST['submitted'])) {
$filenamebef = $_FILES["uploadbef"]["name"];
$filenameaft = $_FILES["uploadaft"]["name"];
$file_basename_bef = substr($filenamebef, 0, strripos($filenamebef, '.'));
$file_basename_aft = substr($filenameaft, 0, strripos($filenameaft, '.'));
// get file extention
$file_ext_bef = substr($filenamebef, strripos($filenamebef, '.'));
$file_ext_aft = substr($filenameaft, strripos($filenameaft, '.'));
// get file name
$filesize_bef = $_FILES["uploadbef"]["size"];
$filesize_aft = $_FILES["uploadaft"]["size"];
$allowed = array('image/pjpeg','image/jpeg','image/JPG','image/X-PNG','image/PNG','image /png','image/x-png');
if ((in_array($_FILES['uploadbef']['type'], $allowed)) && in_array($_FILES['uploadaft']['type'], $allowed)) {
if (($filesize_bef < 200000) && ($filesize_aft < 200000)){
// rename file
$date = date("mdy");
$time = date("His");
$timedate = $time . $date;
$newfilenamebef = $timedate . $file_ext_bef;
$newfilenameaft = $timedate . $file_ext_aft;
if ((file_exists("upload/images/before" . $newfilenamebef)) && (file_exists("uploads/images/after" . $newfilenameaft))) {
// file already exists error
echo "You have already uloaded this file.";
} else {
move_uploaded_file($_FILES["uploadbef"]["tmp_name"], "uploads/images/before/" . $newfilenamebef) && move_uploaded_file($_FILES["uploadaft"]["tmp_name"], "uploads/images/after/" . $newfilenameaft);
echo "File uploaded successfully.";
}
}
} elseif ((empty($file_basename_bef)) && (empty($file_basename_aft))) {
// file selection error
echo "Please select a file to upload.";
} elseif (($filesize_bef > 200000) && ($filesize_aft > 200000)) {
// file size error
echo "The file you are trying to upload is too large.";
} else {
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed);
unlink($_FILES["uploadbef"]["tmp_name"]);
unlink($_FILES["uploadaft"]["tmp_name"]);
}
}
echo $newfilenamebef;
echo $newfilenameaft;
?>
<form enctype="multipart/form-data" action="uploading.php" method="post">
<input type="hidden" value="MAX_FILE_SIZE" value="524288">
<fieldset>
<legend>Select a JPEG or PNG image of 512kb or smaller to be uploaded : </legend>
<p><b>Before</b> <input type="file" name="uploadbef" /></p>
<p><b>After</b> <input type="file" name="uploadaft" /></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Submit" /></div>
<input type="hidden" name="submitted" value="TRUE" />
</form>
<?php
include('footer.html');
?>
You should but these two lines at the top of your index.php or bootstrap.php :
error_reporting( -1 );
ini_set( "display_errors" , 1 );
And see if some error messages turn up.
It is quite possible that problem is caused by wrong file permissions.
At a quick guess I would say that your localhost is not case sensitive, whereas your webserver is.
In other words, on your localhost IMG_12345.JPG is the same as img_12345.jpg. On your webserver, though, they are treated differently.
Without any actual reported errors, it's hard to be certain, but this is a common problem.
You're not checking for valid uploads properly. Something like the following would be FAR more reliable:
// this value is ALWAYS present and doesn't depend on form fields
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errmsgs = array();
if ($_FILES['uploadbef']['error'] !== UPLOAD_ERR_OK) {
$errs++;
$errmsgs[] = "'uploadebef' failed with code #" . $_FILES['uploadebef']['error'];
}
if ($_FILES['uploadaft']['error'] === UPLOAD_ERR_OK) {
$errs++;
$errmsgs[] = "'uploadeaft' failed wicode #" . $_FILES['uploadeaft']['error'];
}
if (count($errmsgs) > 0) {
print_r($errmsgs);
die();
}
... process the files here ...
}
As well, why re-invent the wheel to split up the file names?
$parts = path_info($_FILES['uploadaft']['name']);
$basename = $parts['basename'];
$ext = $parts['extension'];

splitting a file for upload via php

in php.ini and nginx configurations, there are limits that can be set which restrict the total amount of size a request can contain. 1mb for example.
so with that requirement, if a user wants to upload a file that is 10mb , i want to split the file into 1mb chunks and send it to multiple backend application servers where they all use shared storage. from here, i want to be able to merge the chunks or re-assemble them back to the final 10mb file.
is this possible with PHP front end / back end? I have a REST API which supports POST and will inspect all post requests for $_FILE[] -- I'm unsure how this could be managed on the backend
on the front end, when a user hits submit, the file starts to upload ... which means, if it's 10mb ... it'll fail -- SO, does this mean i need some fancy javascript to do the chunking / form submission -- if so, how is that then structured / communicated so that the backend knows what to do ...
This won't be possible with Javascript or PHP. Maybe with Flash or some other client technology.
you could use this code:
<html>
<body>
<label >
<div align="right" >
</div>
</label>
<form method="POST" action="">
<table>
<tr>
<td>Here you Files to spilited</td>
<td>Value</td>
</tr>
<tr>
<td> For spilt Zip File to paste Its Url</td>
<td><input type="text" name="zipurl" /></td>
</tr>
<tr>
<td>Spilt to Valume Size: part</td>
<td><input type="text" name="spitsize" value="50"/></td>
</tr>
<tr>
<td>Mega bite (1 On/ 0 off) </td>
<td><input type="text" name="megabyte" value="1"/></td>
</tr>
<tr>
<td>Kilo Byte (1 On/ 0 off)</td>
<td><input type="text" name="kilobyte" value="0"/></td>
</tr>
</table>
<input type="submit" name="ssurlsubmit" value="submit" />
</form>
</body>
<?php
$mypath = getcwd();
$mypath = preg_replace('/\\\\/', '/', $mypath);
$targetfolder = $mypath.'/tmp';
echo 'targetfolder is: '.$targetfolder.'<br />';
if (!is_dir("$mypath/tmp")) {
mkdir("$mypath/tmp");
echo 'Dir'.$targetfolder.'created'.'<br />';
}
$targetfolder = $mypath.'/tmp'.'<br />';
/*
if(!file_exists($targetfolder)) {
if(mkdir($targetfolder)) {
echo "Created target folder $targetfolder".br();
}
else{
echo '$targetfolder can not be created'.br();
}
}else
{
echo $targetfolder.'$targetfolder exist '.br();
}
*/
?>
</html>
<?php
/*
--------------------------------------------------
filesplit.php HJSplit compatiple PHP file splitter
--------------------------------------------------
File name:
filesplit.php
Author:
Umit Tirpan 2007-03-22
Umit Tirpan 2008-03-12 [remote file support added]
Author's Website:
http://forum.iyinet.com/
Description:
This PHP script, splits the files into smaller pieces in binary.
It is compatiple with HJSplit, so you can re-join splitted files using HJSplit's Join utility.
It can split a file up to 999 pieces.
What is the use, why will I use this?
Some webmasters do not have shell access to their websites. This prevents them splitting big files, ie. MySQL backups, into smaller files. Splitting a 200Mb file into 10 x 20Mb file may be easy on webmaster to download in pieces.
How to run:
Make sure your webserver has write permission on the target folder.
Edit variables.
Upload (ftp) this file to your webserver or run on your PC.
For security reason, filename is hardcoded. You can modify code to accept $_GET['filename']
Run with your favorite browser.
http://www.<your-web-site>.com/filesplit.php
Or run on shell (ie. ssh)
php filesplit.php
It is Ok to share and modify this code and use in/with your applications. No restrictions.
*/
// ---------------------------
// Edit variables (3 variables)
// ---------------------------
// File to split, is its not in the same folder with filesplit.php, full path is required.
global $ssurl,$filename;
if (isset($_POST['zipurl'])) {
$url=$_POST['zipurl'];
$filename=$_POST['zipurl'];
echo "URL:".$url.'<br />';
}
// $filename = "http://www.iyinet.com/my-big-file.zip";
// Target folder. Splitted files will be stored here. Original file never gets touched.
// Do not append slash! Make sure webserver has write permission on this folder.
$mypath = getcwd();
$mypath = preg_replace('/\\\\/', '/', $mypath);
$targetfolder = $mypath.'/tmp';
echo 'targetfolder is: '.$targetfolder.'<br />';
if (!is_dir("$mypath/tmp")) {
mkdir("$mypath/tmp");
echo 'Dir'.$targetfolder.'created'.'<br />';
}
$targetfolder = $mypath.'/tmp';
// File size in Mb per piece/split.
// For a 200Mb file if piecesize=10 it will create twenty 10Mb files
$piecesize = 50; // splitted file size in MB
if (isset($_POST['spitsize'])) {
$piecesize=$_POST['spitsize'];
}
//$piecesize = 10; // splitted file size in MB
// ---------------------------
// Do NOT edit this section
// ---------------------------
$buffer = 1024;
if (isset($_POST['megabyte'])and $_POST['megabyte']=='1') {
//$piece=$_POST['megabyte'];
$piece = 1048576*$piecesize;
}
if (isset($_POST['kilobyte']) and $_POST['kilobyte']==1) {
//$piece=$_POST['kilobyte'];
$piece = 1024*$piecesize;
}
//$piece = 1048576*$piecesize;
$current = 0;
$splitnum = 1;
if(!file_exists($targetfolder)) {
if(mkdir($targetfolder)) {
echo "Created target folder $targetfolder".br();
}
echo '$targetfolder folder exist'.br();
}
if(!$handle = fopen($filename, "rb")) {
die("Unable to open $filename for read! Make sure you edited filesplit.php correctly!".br());
}
$base_filename = basename($filename);
/*
$ss=substr($base_filename,-4);
echo substr($base_filename,-4).'<br />';
if ($ss=='.zip')
{
$end='.zip';
$base_filename= removeFromEnd($base_filename, '.zip');
}
*/
$piece_name = $targetfolder.'/'.$base_filename.'.'.str_pad($splitnum, 3, "0", STR_PAD_LEFT). $end;
if(!$fw = fopen($piece_name,"w")) {
die("Unable to open $piece_name for write. Make sure target folder is writeable.".br());
}
echo "Splitting $base_filename into $piecesize Mb files ".br()."(last piece may be smaller in size)".br();
echo "Writing $piece_name...".br();
while (!feof($handle) and $splitnum < 999) {
if($current < $piece) {
if($content = fread($handle, $buffer)) {
if(fwrite($fw, $content)) {
$current += $buffer;
} else {
die("filesplit.php is unable to write to target folder. Target folder may not have write permission! Try chmod +w target_folder".br());
}
}
} else {
fclose($fw);
$current = 0;
$splitnum++;
$piece_name = $targetfolder.'/'.$base_filename.'.'.str_pad($splitnum, 3, "0", STR_PAD_LEFT);
echo "Writing $piece_name...".br();
$fw = fopen($piece_name,"w");
}
}
fclose($fw);
fclose($handle);
echo "Done! ".br();
exit;
function br() {
return (!empty($_SERVER['SERVER_SOFTWARE']))?'<br>':"\n";
}
function removeFromEnd($string, $stringToRemove) {
$stringToRemoveLen = strlen($stringToRemove);
$stringLen = strlen($string);
$pos = $stringLen - $stringToRemoveLen;
$out = substr($string, 0, $pos);
return $out;
}
?>
for test check this address:
http://restss2.frogcp.com/tmp/filesplit%2520%282%29.php

Categories