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
Related
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.
The purpose of the script is to change the names of of a list of images within a directory for an ecommerce site. So specifically when the script is rand a user will type in a word or phrase that they would like a set or list of files to be prefixed with. The script will iterate over each file changing the prefix and appending the next available number starting from zero.
I'd like to display/render on the page to the user what files have been changed. right now when the script is ran it displays the current files within the directory, and then it list the changed files and their names within the directory.
How can i get the file list only to display when the script has finish processing the new names?
Why does the script not append the proper incremented number to the file name? It renames files the following order:
abc0.jpg
abc1.jpg
abc10.jpg
abc11.jpg
abc12.jpg
abc13.jpg
<?php
$display_file_list;
//Allow user to put choose name
if (isset($_POST['file_prefix'])){
$the_user_prefix = $_POST['file_prefix'];
//open the current directory change this to modify where you are looking
$dir = opendir('.');
$i=0;
//Loop though all the files in the directory
while(false !==($file = readdir($dir)))
{
//This is the way we would like the page to function
//if the extention is .jpg
if(strtolower(pathinfo($file, PATHINFO_EXTENSION)) =='jpg')
{
//Put the JPG files in an array to display to the user
$display_file_list[]= $file;
//Do the rename based on the current iteration
$newName = $the_user_prefix.$i . '.jpg';
rename($file, $newName);
//increase for the next loop
$i++;
}
}
//close the directory handle
closedir($dir);
}else{
echo "No file prefix provided";
}
?>
<html>
<body>
<form action="<?=$_SERVER['PHP_SELF']?>" method="POST">
<input type="text" name="file_prefix"><br>
<input type="submit" value="submit" name="submitMe">
</form>
</body>
</html>
<?php
foreach ($display_file_list as $key => $value) {
echo $value. "<br>";
}
?>
"How can i get the file list only to display when the script has finish processing the new names?"
I think this will work for you;
$path = "path/to/files";
$files = glob("{$path}/*.jpg");
$files_renamed = array();
foreach ($files as $i => $file) {
$name = "{$path}/{$prefix}{$i}.jpg";
if (true === rename($file)) {
$files_renamed[] = $name;
}
}
print_r($files_renamed);
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
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'];
I have a simple file uploader, which thanks to stackoverflow is now fully working, however when I copied the PHP code across to my main layout, once initialised to upload a file, but it is wrong format or size and it echos the error, it breaks the HTML below it. Im thinking its to do with the "exit;" after each echo? but could be wrong.
<?php
if($_POST['upload']) {
if($_FILES['image']['name'] == "")
{
#there's no file name return an error
echo "<br/><b>Please select a file to upload!\n</b>";
exit;
}
#we have a filename, continue
#directory to upload to
$uploads = '/home/habbonow/public_html/other/quacked/photos';
$usruploads = 'photos';
#allowed file types
$type_array = array(image_type_to_mime_type(IMAGETYPE_JPEG), image_type_to_mime_type(IMAGETYPE_GIF), image_type_to_mime_type(IMAGETYPE_PNG), 'image/pjpeg');
if(!in_array($_FILES['image']['type'], $type_array))
{
#the type of the file is not in the list we want to allow
echo "<br/><b>That file type is not allowed!\n</b>";
exit;
}
$max_filesize = 512000;
$max_filesize_kb = ($max_filesize / 1024);
if($_FILES['image']['size'] > $max_filesize)
{
#file is larger than the value of $max_filesize return an error
echo "<br/><b>Your file is too large, files may be up to ".$max_filesize_kb."kb\n</b>";
exit;
}
$imagesize = getimagesize($_FILES['image']['tmp_name']);
#get width
$imagewidth = $imagesize[0];
#get height
$imageheight = $imagesize[1];
#allowed dimensions
$maxwidth = 1024;
$maxheight = 1024;
if($imagewidth > $maxwidth || $imageheight > $maxheight)
{
#one or both of the image dimensions are larger than the allowed sizes return an error
echo "<br/><b>Your file is too large, files may be up to ".$maxwidth."px x ".$maxheight."px in size\n</b>";
exit;
}
move_uploaded_file($_FILES['image']['tmp_name'], $uploads.'/'.$_FILES['image']['name']) or die ("Couldn't upload ".$_FILES['image']['name']." \n");
echo "<br/>The URL to your photo is <b>" . $usruploads . "/" . $_FILES['image']['name'] . "</b>. Please use this when defining the gallery photos";
}
?>
<form name="uploader" method="post" action="" enctype="multipart/form-data">
<input type="file" name="image" style="width:300px;cursor:pointer" />
<input type="submit" name="upload" value="Upload Image" />
</form>
Indeed, when you call exit; it means "immediately stop all processing; this script is finished." Anything that comes after it — including HTML — will not be interpreted.
A better organization would be to make this code a function, to the effect of:
function uploadMyStuffPlease() {
if($_POST['upload']) {
if($_FILES['image']['name'] == "")
{
#there's no file name return an error
echo "<br/><b>Please select a file to upload!\n</b>";
return;
}
#we have a filename, continue
// ....
}
Now you can simply call uploadMyStuffPlease(), which will do as much processing as it can, and perhaps return early in the event of an error. Either way, the function will return, and so the rest of your script (including that HTML) can still be interpreted.
If you call exit; your PHP script won't be able to output anything anymore. That's why the layout is broken.
You should maybe try to keep the HTML parts out of your PHP code and especially avoid opening tags that you don't close afterwards (i.e. divs or anything).
That being said, it's probably safest to just put everything into a function that won't exit the script when finished (see other's posts).
if(isset($_POST['upload'])){
OR
if(!empty($_POST['upload'])){
And remove exit...