Congratulations to AcaCandy on her 100,000th post!
There's no such thing as a stupid question, but they're the easiest to answer.
JoinTour
Login
 
Tag Cloud
acer black screen blue screen boot bsod computer connection crash css dell drive driver drivers email error ethernet excel firefox firefox 3 freeze hard drive internet internet explorer itunes laptop linux malware monitor network networking nvidia outlook outlook 2003 outlook 2007 outlook express partition password problem router slow software sound trojan usb video virus vista windows windows xp wireless
Web Design & Development
Search
Search in:
 
Advanced Search
Tech Support Guy Forums > Internet & Networking > Web Design & Development >
Solved: Php upload script


HELLO AND WELCOME! Before you can post your question, you'll have to register -- it's completely free! Click here to join today! We highly recommend that you print a copy of our Guide for New Members. Enjoy!

Closed Thread
 
Thread Tools
aconite's Avatar
Senior Member with 172 posts.
 
Join Date: Feb 2006
Experience: Intermediate
22-May-2008, 07:24 PM #1
Solved: Php upload script
Hi,

I have found an upload script in hotscripts and have implemented it into the website, I followed the installation steps to 'give write permissions to php on the upload folder (php must be allowed to move uploaded files to this folder'.
I typed <?php chmod ('_uploadedfiles_xxxx',640); ?> into notepad and saved it as php in the uploaded_xxxx folder, when I went to test it the error message I got was Error:invalid response received from server.
This is the code which is quite long and thanks for any help received
Code:
<?php
    @set_time_limit(90); // try to change to maximum allowed execution time for this page
    define('CFG_UPLOADFOLDER','_uploadedfiles_xxxx/'); 
    $bSecure = (isset($_SERVER['HTTPS']))? true : false;

    include('inc.ErrorHandling.php');
    include('inc.init.php');
    include('class.DataException.php');
    include('class.File.php');




function ProduceJavaScriptResponse($aResponse){
$response = <<<EOD
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="Cache-Control" content="no cache" >
<meta http-equiv="Pragma" content="no_cache" >
<meta name="language" content="en" >
</head>
<body>
<script type="text/javascript">{code}</script>
</body></html>
EOD;

    // encode into JSON
    $jsResponse = 'window.parent.'. $_REQUEST['callback'] .'('. json_encode($aResponse) .');';
    $response = str_replace('{code}', $jsResponse, $response);
    return $response;
}




// Upload file
$errorMessage = '';
$aResponse = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
############################################################

    if (!headers_sent()){
        Header("Pragma: no-cache");
		Header("Cache-Control: no-cache");
		Header('Expires: '. GMDate("D,d M Y H:i:s") .' GMT');
	}

    $blacklist = array('.php', '.phtml', '.php3', '.php4');
    foreach ($blacklist as $item) {
       if (preg_match("/$item\$/i", $_FILES['_file']['name'])){
           $errorMessage = 'Uploading PHP files is not allowed!';
       }
    }

    try{
        if ($errorMessage == ''){
            $maxAllowedSize = null; // no limit (see FAQ)
            $aAllowedContenTypes = null; // any file (see FAQ)
            $oFile = File::UploadFile('_file', CFG_UPLOADFOLDER, $maxAllowedSize, $aAllowedContenTypes);
        }
    }catch(Exception $e){
        $errorMessage = 'An error occured:'. $e->getMessage();
    }


    // produce response
    if (isset($_REQUEST['output']) && $_REQUEST['output'] == 'js'){
        if (!isset($_REQUEST['callback']) || empty($_REQUEST['callback'])){
        // ERROR: BAD AJAX call

            $errorMessage = "Bad Ajax call! URL argument \'callback\' was not specified.";
            die('<script type="text/javascript">alert("'. $errorMessage .'");</script>');

        }else if(empty($errorMessage) && $oFile){
        // SUCCESS (file was uploaded)

            $aResponse['result'] = 'success';
            $aResponse['file'] = array('size'          => $oFile->getSize(),
                                       'sizeFormatted' => $oFile->FormatFileSize($oFile->getSize()),
                                       'name'          => $oFile->getName()
                                      );

        }else{
        // UPLOAD ERROR

            $aResponse['result'] = 'failure';
            $aResponse['message'] = 'Upload error ('. $errorMessage .').';

        }

        $response = ProduceJavaScriptResponse($aResponse);

    }else{
        $response = file_get_contents('fileUploaded.tpl.php');

        $aValues = array($oFile->getName(), $oFile->FormatFileSize($oFile->getSize()));
        $aPlaceHolders = array('{filename}', '{filesize}');
        $response = str_replace($aPlaceHolders,$aValues,$response,$count);

    }
    die($response);


############################################################
}


?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
            "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <meta name="language" content="en" >
        <meta name="description" content="Secure file uploading : a page for uploading files securely">
        <meta name="author" content="attila szabo (www.w3net.eu)" >
        <meta name="robots" content="noindex,nofollow" >
        <title><?php if($bSecure){echo 'Secure ';}?>File Upload form</title>
        <link media="handheld" href="css/handheld.css" type="text/css" rel="stylesheet">
        <link rel="stylesheet" type="text/css" media="all" href="css/main.css">
        <script type="text/javascript" src="js/common.js"></script>
        <script type="text/javascript" src="js/FileListing.js"></script>
        <script type="text/javascript" src="js/PageController.js"></script>
    </head>
<body id="home">
<table border="0" cellpadding="0" cellspacing="0" width="627" align="center">
<tr>
	<td>
	<div id="logo">
	<img src="../images/logoGreyPurple.gif" width="627" height="75" border="0" alt="" /></div>	</td>
</tr>
</table>


<table border="0" cellpadding="0" cellspacing="0" width="627" align="center">
<tr>
	<td>
	<div id="imgHeader">
	<img src="../images/acounts.jpg"  width="627" height="33" border="0" alt="" /></div>
	
	<div id="nav">
	<ul>
		<li><a href="index.html">Home</a></li>
		<li><a href="about.html">About</a></li>
		<li><a href="HowWeWork.html">How we work</a></li>
		<li><a href="requirementsForm.html">Requirements Form</a></li>
		<li><a href="servicesAndRates.html">Services &amp; Rates</a></li>
		<li><a href="contact.html">Contact</a></li>
	</ul>
	
</div>
</table>	

<div id="container">
	<ul id="skip">
		<li><a href="#main">Skip to main content</a></li>
		<li><a href="#form">Skip to the upload form</a></li>
	</ul>
<iframe id="uploadIfr" src="blank.htm" name="uploadIfr" class="hiddenUploadIframe" title="ignore this frame"></iframe>

    <!-- @@@ listing of uploaded files -->
    <div id="uploadedFiles">
    </div>
    <!-- end listing of uploaded files @@@ -->

	<a name="main"></a>
    <h1><?php if($bSecure){echo 'Secure file';}else{echo 'File';}?> uploading</h1>
    <?php 
    if($bSecure){
    ?>
    <p class="message" id="annotationSecure">
    Uploading files using this web page is secure. This webpage transmits the file using a high-level encryption so that 
    only I will be able to access the information. 
    Web pages beginning with &quot;https&quot; instead of &quot;http&quot; enable secure information transmission.
    </p><?php
    }else{
        echo "<p></p>";
    }
    ?>


    <div id="frmAttachFile_ErrorMessage" class="form_boxErrorMsg" style="display: none"></div>

    <!-- @@@ file upload form -->
    <div id="fileuploadForm"><a name="form"></a>
    <form name='frmUploadFile' id="frmUploadFile" action="index.php" method="post" enctype="multipart/form-data" > <!-- uploadIfr -->
        <fieldset title="Choose the file to upload">
            <legend> 1: Choose a file to upload</legend>
            <p>Click the button to browse the file system of your computer. Find and select the file you want to upload.</p>
            
            <label for="fileInput" class="form_label">File:</label>
            <input type="file" accept="" name="_file" id="fileInput" >
        </fieldset>
        <fieldset id="confirmation" title="Confirmation">
            <legend> 2: Upload file</legend>
            <p>When you have selected the file to upload, click on the <strong>Upload</strong> button.</p>
            <div class="actionBar" id="submitBtnBox">
                <input type="submit" value="Upload" >
            </div>
                
        </fieldset>
    </form>
    </div>
    <!-- end file upload form @@@ -->
</div>
</div>
</body></html>
This is the css
Code:
BODY {
	margin: 50px 0px 0px 0px;      
	padding: 0px 0px 0px 0px;
	font-family: arial, helvetica, sans-serif;

/* part 1 of 2 centering hack */
	color:#000;
	background:#C2CACB;
	font-family:  arial, helvetica, sans-serif;
	font-size: x-small; /* for IE5/Win */
	voice-family: "\"}\""; 
	voice-family: inherit;
	font-size: small; /* for compliant browsers */
} 
html>body {font-size:small;}

#container {
	font-size: 110%;
	margin-right: auto;
	margin-left: auto; 	/* opera does not like 'margin:20px auto' */
	background: #fff;
	border:solid 1px #FFFFFF;
	text-align:left; /* part 2 of 2 centering hack */
	width: 627px; /* ie5win fudge begins */
	voice-family: "\"}\"";
	voice-family:inherit;
	width: 627px;
}

form {
    margin: 0;
}

#skip {
	display: none;
}

h1 {
    font-size: 170%;
    background: transparent url(../imgs/green_up.gif) no-repeat right;
    padding-right: 40px;
    padding-right: 30px;
    display: inline;
}

#uploadedFiles {
    margin-bottom: 20px;
}

#fileuploadForm {
    margin-right: auto;														 
	margin-left: auto; 	/* opera does not like 'margin:20px auto' */
	background: #fff;
	border:solid 1px #FFFFFF;
	text-align:left; /* part 2 of 2 centering hack */
	width: 625px; /* ie5win fudge begins */
	voice-family: "\"}\"";
	voice-family:inherit;
	width: 627px;                           
}

fieldset {
    border-left:0;
    border-right:0;
    border-bottom:0;
    padding: 0.5em;
}

legend {
    background-color:#B2CBE7;
    color:#000;
    font-weight:bold;
    margin:0px;
    padding:5px 10px;		
}

#confirmation {
    margin-top: 2em;
}

.actionBar {
    background-color:#B2CBE7;
    padding: 0.6em;
    text-align: center;
    
}

.actionBar input {
    font-size: 110%;
}
  
.hiddenUploadIframe {
    width:0;
    height:0;
    border:0;
    position: absolute;
    top: -1000px;
}



/* Msg boxes
------------------------------ */
.message {
	margin: 1.5em 0;
/*	padding: 15px;*/
	font-size: 90%;
	line-height: 1.5em;	
	border-left: none;
	border-right: none;
}

.success {
	background-color: #A2D489;
	border-top: 3px solid #339900;
	border-bottom: 3px solid #339900;
}

.error {
	background-color: #FFDDCC;
	border-top: 3px solid #DD0000;
	border-bottom: 3px solid #DD0000;
}

.alert {
	background-color: #FFF3CE;
	border-top: 3px solid #FDDC9A;
	border-bottom: 3px solid #FDDC9A;
}

#annotationSecure {
    background: #FFFFAA ;
    padding:2px;
/*  padding-left: 15px;*/
}



/* Uploaded files
------------------------------ */
table {
    border-collapse:collapse;
}
#uploadedFiles caption {
    line-height: 2.1em;
    text-align: left;
    padding-left: 20px;
    background: #fff url(../imgs/lock.png) no-repeat left;
}
#uploadedFiles th,
#uploadedFiles td{
    border:1px solid #CCCCCC;
    padding:0.5em;
}

#uploadedFiles thead{
    background-color:#DDDDDD;
}

#uploadedFiles tr.rowodd {
    background-color:#FFFFFF;
}
#uploadedFiles tr.roweven {
    background-color:#F2F2F2;
}


/* Busy page
------------------------------ */
#dropSheet{
  background-color/**/: #000000;
  background-image: url(imgs/dots.gif);
  background-image/**/: none;
  opacity: 0.35;
  filter: alpha(opacity=35);
}
div.busyDialog {
    background-color: #ECB7B2;
    font-size: 110%;
    font-weight: bold;
    margin: 0;
    padding: 0;
}
div.busyDialog p {
    margin:0;
    padding: 5px;
}

/*	Footer	*/

#footer {
	width:627px; 
	height:20px;
	background-color:#FFFFFF;
	font-family:Arial, Helvetica, sans-serif;
	font-size:0.8em;
	color:black;
	text-align:center;
	font-weight:normal;
	padding-top:1%;
}

/*Links - a, a:visited*/	
a {
	text-decoration: none;
	color:  #000000;
	}
	
a:visited {
	color:#000000;
	text-decoration:none;
}


/*	Misc	*/

.margin {  /*margin between content &amp; footer*/		
	margin-top:1.5%;
}	

#nav {
	width:627px;		
	float:left;
	font-family:Arial, Helvetica, sans-serif;
	font-size:1.0em;
	color:#ffffff;
}

#nav ul {
	background-color:#ffffff;
	text-align:left;
	font-size:1.0em;
	font-family:Arial, Helvetica, sans-serif;
	margin-left:0.95%;
	padding-left:0;
	margin-top:-.55%;
}

#nav li {
	list-style-type:none;
	padding:1.6em 1em;
	display:inline;
	color:#5F5E61;
}

#imgHeader {
	margin-top:2%;
}

Last edited by aconite : 23-May-2008 08:04 AM.
Bobathome's Avatar
Member with 43 posts.
 
Join Date: Aug 2007
Experience: Intermediate
28-May-2008, 12:37 PM #2
If your on a Windows, you don't need to do the CHMOD stuff.

I'm not 100% on that, but I have never needed to do it.

If not, you can try this file upload. I used it when I was learning PHP, and it works great.
haswalt's Avatar
Computer Specs
Senior Member with 416 posts.
 
Join Date: Nov 2004
Location: South Coast, UK
Experience: Advanced
02-Jun-2008, 01:04 AM #3
Well your server masy not allow chmod commands from php, servers can be setup to block certain system commands for security.

If you have FTP access try connecting and chmodding the folder that way.

Anyway is 644 enough i woudl have though you'd need something 755 for the uplaods to work correctly.

Harry
__________________
LQD Internet Limited
We've just got better! With the launch of our new site we have SLASHED our prices and upped the offering. Check it out!

10% Discount for ALL Tech Support Guy Members
Simply use the promo code of "T3CHGUY" when ordering to recieve your 10% discount on all shared and reseller hosting packages.
aconite's Avatar
Senior Member with 172 posts.
 
Join Date: Feb 2006
Experience: Intermediate
02-Jun-2008, 08:48 AM #4
thanks haswalt,

I am a newbie to php so am not quite sure how to write a 'write permissions' to a folder on my server called 'upload'. Would I just open up notepad and type
Code:
<?php 'upload',755); ?>
and save as permissions.php.
haswalt's Avatar
Computer Specs
Senior Member with 416 posts.
 
Join Date: Nov 2004
Location: South Coast, UK
Experience: Advanced
02-Jun-2008, 09:10 AM #5
Hi Aconite.

Here is a link to the php manual for chmod:

http://uk3.php.net/chmod

but basically you would need to do this:

PHP Code:
<?php

chmod
("uploads"0755);

?>
note that 0755 is required to be correct. 0755 give read/write/execute to owner and read/write to nobody and group.

the first parameter is the file location so i am assuming your permissions.php file would be alongside the uploads directory.

otherwise with FTP connect to the server, navigate to the uploads dir (not into it though). Right click on it and select permissions/chmod. Then tick the boxes, it will show you the value up above usually. or you can enter the number 755 in manually to change the permissions.

This works on smartFTP, Filezilla and few others that i know of for sure.

Harry
__________________
LQD Internet Limited
We've just got better! With the launch of our new site we have SLASHED our prices and upped the offering. Check it out!

10% Discount for ALL Tech Support Guy Members
Simply use the promo code of "T3CHGUY" when ordering to recieve your 10% discount on all shared and reseller hosting packages.
aconite's Avatar
Senior Member with 172 posts.
 
Join Date: Feb 2006
Experience: Intermediate
02-Jun-2008, 04:37 PM #6
Bobathome,
Thanks for the link, followed the tutorial but found it frustrating as I couldn't figure out why it is not working. This is the link

Under the //allow MIME file types
I typed $filetype = array ('application/vnd.ms-excel');
$ftype = false
;

As I only want microsoft excel files to be uploaded but when I tried to upload the 5workbookspreadsheet requirements document1.xls, I got a message saying "5workbookspreadsheet requirements document1.xlscannot be uploaded.
Acceptable file formats are: .xls". I don't understand?

I have an uploads folder in the excelpros directory and the permissions.php file is under the excelpros directory. Any help greatly appreciated

Code:
<?php
//define constant which contains the maximum file size in bytes
define('MAX_FILE_SIZE',50000);

if (array_key_exists('btn', $_POST)) {

// define new constant which contains the path to the upload folder
define('UPL_FLD','uploads/');

//find the extension
$flext = pathinfo($_FILES['frmfile']['name']);
$ext = strtolower($flext['extension']);

//create new file name
$file = str_replace('','_', $_POST['frmname'].'.'.$ext);
$file = strtolower($file);

//create variable and assign the formatted value of MAX_FILE_SIZE to it
$maxfs = number_format(MAX_FILE_SIZE/1024,1).'KB';
$fsize = false;

//check the file size
if($_FILES['frmfile']['size'] > 0 && $_FILES['frmfile']['size'] <= MAX_FILE_SIZE){

$fsize = true;

}

//allow MIME file types
$filetype = array ('application/vnd.ms-excel');
$ftype = false;

//check if uploaded file type is allowed
foreach($filetype as $type) {

if ($type == $FILES['frmfile']['type']){

	$ftype = true;
	break;
	
	}

}

if ($ftype && $fsize && $_POST['frmname']!= ''){

	switch($_FILES['frmfile']['error']){

	case 0:
	// move file to the 'uploads' folder
	$upload = move_uploaded_file($_FILES['frmfile']['tmp_name'],UPL_FLD.$file);
	if ($upload){

		$msg = $_FILES['frmfile']['name'].'uploaded successfully';

		} else {

			$msg = 'Error.<br />Please try again.';
		}
		break;

		case 3:
		$msg = 'Error.<br />Please try again.';
		break;

		default:
		$msg = 'Error - please contact administrator';

	}

} elseif($_FILES['frmfile']['error'] == 4){

	$msg = 'Please select file';

} elseif($_POST['frmname'] == ''){

	$msg = 'Please provide your full name';

} else {

	$msg = $_FILES['frmfile']['name'].'cannot be uploaded.<br/>';
			if(!$ftype){
				$msg .= 'Acceptable file formats are: .xls<br/>';
			}
			if(!$fsize){
				$msg .= 'Maximum file size is '.$maxfs;
			}

}

}
?>
HTML
Code:
<?php if (isset($msg)) {echo'<p class="warning">'.$msg.'</p>';}?>	
	
  <form action="" method="post" enctype="multipart/form-data" name="frm_upload" id="frm_upload">
  <table border="0" cellspacing="0" cellpadding="0" id="tbl_upload">
  <tr>
  <th scope="row"><label for="frmname">Full name:</label></th>
  <td><input type="text" name="frmname" id="frmname" class="frmfld" /></td>
  </tr>
  <tr>
  <th scope="row"><label for="frmfile">File:</label></th>
  <td><input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE;?>" /><input name="frmfile" type="file" id="frmfile" size="30" /></td>
  </tr>
  <tr>
  <th scope="row"> </th>
  <td>
  <label for="btn" id="sbm">
  <input type="submit" name="btn" id="btn" value="Upload" />
  </label>  </td>
  </tr>
  </table>
  </form>

Last edited by aconite : 02-Jun-2008 05:01 PM.
Closed Thread

Tags
php

THIS THREAD HAS EXPIRED.
Are you having the same problem? We have volunteers ready to answer your question, but first you'll have to join for free. Need help getting started? Check out our Welcome Guide.


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
WELCOME TO TECH SUPPORT GUY! Are you looking for the solution to your computer problem? Join our site today to ask your question -- for free! Our site is run completely by volunteers who help people like you solve computer problems. See our Welcome Guide to get started.



Thread Tools


You Are Using:
Server ID
Advertisements do not imply our endorsement of that product or service.
All times are GMT -4. The time now is 06:52 PM.
Copyright © 1996 - 2008 TechGuy, Inc. All rights reserved.
Powered by vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Powered by Cermak Technologies, Inc.