edvinson
asked on
Simple PHP Upload Script
Hi, trying to do a simple php upload script and am getting this error:
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in /hermes/bosweb/web199/b199 2/ipw.edvi nson/publi c_html/upl oads.php on line 28
Unable to upload the file.
It appears to upload but after it does it's thing, I get that error.
Here is script:
<?php
$uploadpath = 'uploads/'; // directory to store the uploaded files
$max_size = 3000000; // maximum file size, in KiloBytes
$alwidth = 6900; // maximum allowed width, in pixels
$alheight = 7800; // maximum allowed height, in pixels
$allowtype = array('wav', 'mp3', 'jpg'); // allowed extensions
if(isset($_FILES['fileup'] ) && strlen($_FILES['fileup'][' name']) > 1) {
$uploadpath = $uploadpath . basename( $_FILES['fileup']['name']) ; // gets the file name
$sepext = explode('.', strtolower($_FILES['fileup ']['name'] ));
$type = end($sepext); // gets extension
list($width, $height) = getimagesize($_FILES['file up']['tmp_ name']); // gets image width and height
$err = ''; // to store the errors
// Checks if the file has allowed type, size, width and height (for images)
if(!in_array($type, $allowtype)) $err .= 'The file: <b>'. $_FILES['fileup']['name']. '</b> not has the allowed extension type.';
if($_FILES['fileup']['size '] > $max_size*1000) $err .= '<br/>Maximum file size must be: '. $max_size. ' KB.';
if(isset($width) && isset($height) && ($width >= $alwidth || $height >= $alheight)) $err .= '<br/>The maximum Width x Height must be: '. $alwidth. ' x '. $alheight;
// If no errors, upload the image, else, output the errors
if($err == '') {
if(move_uploaded_file($_FI LES['fileu p']['tmp_n ame'], $uploadpath)) {
echo 'File: <b>'. basename( $_FILES['fileup']['name']) . '</b> successfully uploaded:';
echo '<br/>File type: <b>'. $_FILES['fileup']['type'] .'</b>';
echo '<br />Size: <b>'. number_format($_FILES['fil eup']['siz e']/1024, 3, '.', '') .'</b> KB';
if(isset($width) && isset($height)) echo '<br/>Image Width x Height: '. $width. ' x '. $height;
echo '<br/><br/>Image address: <b>http://'.$_SERVER['HTTP_HOST'].rtrim(dir name($_SER VER['REQUE ST_URI']), '\\/').'/'.$uploadpath.'</ b>';
}
else echo '<b>Unable to upload the file.</b>';
}
else echo $err;
}
?>
<div style="margin:1em auto; width:333px; text-align:center;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-da ta">
<p>Upload File:
<input type="file" name="fileup" />
</p>
<p><br/>
<input type="submit" name='submit' value="Upload" />
</p>
</form>
</div>
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in /hermes/bosweb/web199/b199
Unable to upload the file.
It appears to upload but after it does it's thing, I get that error.
Here is script:
<?php
$uploadpath = 'uploads/'; // directory to store the uploaded files
$max_size = 3000000; // maximum file size, in KiloBytes
$alwidth = 6900; // maximum allowed width, in pixels
$alheight = 7800; // maximum allowed height, in pixels
$allowtype = array('wav', 'mp3', 'jpg'); // allowed extensions
if(isset($_FILES['fileup']
$uploadpath = $uploadpath . basename( $_FILES['fileup']['name'])
$sepext = explode('.', strtolower($_FILES['fileup
$type = end($sepext); // gets extension
list($width, $height) = getimagesize($_FILES['file
$err = ''; // to store the errors
// Checks if the file has allowed type, size, width and height (for images)
if(!in_array($type, $allowtype)) $err .= 'The file: <b>'. $_FILES['fileup']['name'].
if($_FILES['fileup']['size
if(isset($width) && isset($height) && ($width >= $alwidth || $height >= $alheight)) $err .= '<br/>The maximum Width x Height must be: '. $alwidth. ' x '. $alheight;
// If no errors, upload the image, else, output the errors
if($err == '') {
if(move_uploaded_file($_FI
echo 'File: <b>'. basename( $_FILES['fileup']['name'])
echo '<br/>File type: <b>'. $_FILES['fileup']['type'] .'</b>';
echo '<br />Size: <b>'. number_format($_FILES['fil
if(isset($width) && isset($height)) echo '<br/>Image Width x Height: '. $width. ' x '. $height;
echo '<br/><br/>Image address: <b>http://'.$_SERVER['HTTP_HOST'].rtrim(dir
}
else echo '<b>Unable to upload the file.</b>';
}
else echo $err;
}
?>
<div style="margin:1em auto; width:333px; text-align:center;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-da
<p>Upload File:
<input type="file" name="fileup" />
</p>
<p><br/>
<input type="submit" name='submit' value="Upload" />
</p>
</form>
</div>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Please use the code snippet feature to post code here. It gives us line numbers and an easy-to-read unispace font.
The script I posted works correctly, so I would guess that the error might arise as a result of the changes you made to it. My first guess would be that there is HTML added to the end of the script without closing the PHP. You can use the ?> close PHP tag after the PHP and before the HTML.
The script I posted works correctly, so I would guess that the error might arise as a result of the changes you made to it. My first guess would be that there is HTML added to the end of the script without closing the PHP. You can use the ?> close PHP tag after the PHP and before the HTML.
ASKER
Got it, Thanks Ray. Trying an mp3 and adjusted the file types, getting this error:
Sorry, Upload Error Code: 1: The uploaded file exceeds the upload_max_filesize directive in php.ini
am assuming that things are working well and now I need to talk to my server company to change the php.ini file??
Sorry, Upload Error Code: 1: The uploaded file exceeds the upload_max_filesize directive in php.ini
am assuming that things are working well and now I need to talk to my server company to change the php.ini file??
ASKER
Ray, i was wrong, it doesn't seem to be working quite yet. Here are the errors.
Warning: move_uploaded_file(/hermes /bosweb/we b199/b1992 /ipw.edvin son/public _html/uplo ads/dsc_40 27.jpg) [function.move-uploaded-fi le]: failed to open stream: Permission denied in /hermes/bosweb/web199/b199 2/ipw.edvi nson/publi c_html/upl oads2.php on line 164
Warning: move_uploaded_file() [function.move-uploaded-fi le]: Unable to move '/tmp/php5dRPR4' to '/hermes/bosweb/web199/b19 92/ipw.edv inson/publ ic_html/up loads/dsc_ 4027.jpg' in /hermes/bosweb/web199/b199 2/ipw.edvi nson/publi c_html/upl oads2.php on line 164
ERROR: uploads/dsc_4027.jpg NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND
Included Entire page code:
Warning: move_uploaded_file(/hermes
Warning: move_uploaded_file() [function.move-uploaded-fi
ERROR: uploads/dsc_4027.jpg NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND
Included Entire page code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Venice Media Group - Uploads</title>
<meta name="keywords" content="Professional Photographer in Sarasota, Sarasota Wedding Photographer, Siesta Key Photographer, Venice, Florida, Island Photographics, Island Photography, Beach Portraits, Family Portraits, Senior Portraits, Weddings of Venice, Website Design, Audio Recording Studio, Large Format Printing, Video Production, Television Production, Children Photography, Banner Printing, 101 W. Venice Avenue # 10, Venice, FL 34285, (941) 485-0699, info@islandphotographicsinc.com, Old Photos copies and restored, Commercial Photography, Location Commercial Photography, sarasota florida photographer, southwest florida photographer, bradenton florida photographer, port charlotte florida photographer, north port florida photographer, englewood florida photographer, boca grand florida photographer, gasparilla florida photographer, family photography, family photographer, wedding photography, wedding photographer, venice photographer, venice florida photographer, portrait photography, portrait studio, senior portraits, beach portraits, venice wedding photographer, business executive headshots, sarasota">
<link href="css/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="container">
<div id="uploadform">
<?php // RAY_upload_example.php
error_reporting(E_ALL);
// MANUAL REFERENCE PAGES YOU MUST UNDERSTAND TO UPLOAD FILES
// http://php.net/manual/en/features.file-upload.php
// http://php.net/manual/en/features.file-upload.common-pitfalls.php
// http://php.net/manual/en/function.move-uploaded-file.php
// http://php.net/manual/en/reserved.variables.files.php
// MANUAL PAGES THAT ARE IMPORTANT IF YOU ARE DEALING WITH LARGE FILES
// http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
// http://php.net/manual/en/ini.core.php#ini.post-max-size
// http://php.net/manual/en/info.configuration.php#ini.max-input-time
// PHP 5.1+ SEE http://php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');
// ESTABLISH THE NAME OF THE DESTINATION FOLDER ('uploads' DIRECTORY)
$uploads = 'uploads';
if (!is_dir($uploads))
{
mkdir($uploads);
}
// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '9000000';
// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD
$nf = 3;
// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array
( 'jpg'
, 'gif'
, 'png'
, 'txt'
, 'pdf'
, 'mp3'
)
;
// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;
// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
?>
<h2>Upload <?php echo $nf; ?> file(s)</h2>
<!--
SOME THINGS TO NOTE ABOUT THIS FORM...
ENCTYPE IN THE HTML <FORM> STATEMENT
MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
ABSENCE OF ACTION= ATTRIBUTE IN FORM TAG CAUSES POST TO SAME URL
-->
<form name="UploadForm" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
<p>
Find the file(s) you want to upload and click the "Upload" button below.
</p>
<?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES
for ($n = 0; $n < $nf; $n++)
{
echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
}
?>
<br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files.
<input type="submit" value="Upload" />
</form>
<?php
die();
}
// END OF THE FORM SCRIPT
// WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
else
{
// THERE IS POST DATA - PROCESS IT
echo "<h2>Results: File Upload</h2>\n";
// ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
// echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n";
// ITERATE OVER THE CONTENTS OF $_FILES
foreach ($_FILES as $my_uploaded_file)
{
// SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
$error_code = $my_uploaded_file["error"];
if ($error_code == 4) continue;
// SYNTHESIZE THE NEW FILE NAME
$f_type = trim(strtolower(end (explode( '.', basename($my_uploaded_file['name'] )))));
$f_name = trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));
$my_new_file
= getcwd()
. DIRECTORY_SEPARATOR
. $uploads
. DIRECTORY_SEPARATOR
. $f_name
. '.'
. $f_type
;
$my_file
= $uploads
. DIRECTORY_SEPARATOR
. $f_name
. '.'
. $f_type;
// OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");
// IF THERE ARE ERRORS
if ($error_code != 0)
{
$error_message = $errors[$error_code];
die("Sorry, Upload Error Code: $error_code: $error_message");
}
// GET THE FILE SIZE
$file_size = number_format($my_uploaded_file["size"]);
// IF THE FILE IS NEW (DOES NOT EXIST)
if (!file_exists($my_new_file))
{
// IF THE MOVE FUNCTION WORKED CORRECTLY
if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
{
$upload_success = 1;
}
// IF THE MOVE FUNCTION FAILED
else
{
$upload_success = -1;
}
}
// IF THE FILE ALREADY EXISTS
else
{
echo "<br/><b><i>$my_file</i></b> already exists.\n";
// SHOULD WE OVERWRITE THE FILE? IF NOT
if (empty($_POST["overwrite"]))
{
$upload_success = 0;
}
// IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
else
{
$now = date('Y-m-d');
$my_bak = $my_new_file . '.' . $now . '.bak';
if (!copy($my_new_file, $my_bak))
{
echo "<br/><strong>Attempted Backup Failed!</strong>\n";
}
if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
{
$upload_success = 2;
}
else
{
$upload_success = -1;
}
}
}
// REPORT OUR SUCCESS OR FAILURE
if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
if ($upload_success == 1) { echo "<br/><strong>$my_file</strong> has been saved.\n"; }
if ($upload_success == 0) { echo "<br/><strong>It was NOT overwritten.</strong>\n"; }
if ($upload_success < 0) { echo "<br/><strong>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</strong>\n"; }
if ($upload_success > 0)
{
echo "$file_size bytes uploaded.\n";
if (!chmod ($my_new_file, 0755))
{
echo "<br/>chmod(0755) FAILED: fileperms() = ";
echo substr(sprintf('%o', fileperms($my_new_file)), -4);
}
echo "<br/><a target=\"_blank\" href=\"$my_file\">See the file $my_file</a>\n";
}
// END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
}
}
?>
</div>
</div>
</div>
</body>
</html>
ASKER
UPDATE: I changed script back from uploads to RAY_junk and it works fine.
How do I just change the folder to: uploads now?
Thank you
How do I just change the folder to: uploads now?
Thank you
The error seems to suggest that the target folder does not have the correct permissions for the http service to write to it. This is causing the move_uploaded_file call to fail.
You will need to change the permissions on the folder to allow the web service to have write permissions on it.
You will need to change the permissions on the folder to allow the web service to have write permissions on it.
ASKER
I've requested that this question be closed as follows:
Accepted answer: 0 points for edvinson's comment #a39461171
for the following reason:
Thank you Ray
Accepted answer: 0 points for edvinson's comment #a39461171
for the following reason:
Thank you Ray
ASKER
Yes, I meant to close out and award points. Not sure why it didn't yesterday but trying again. Thank you!
Thanks for the points and thanks for using EE!
ASKER
Parse error: syntax error, unexpected '<' in /hermes/bosweb/web199/b199
here is entire page:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Venice Media Group - Uploads</title>
<meta name="keywords" content="Professional Photographer in Sarasota, Sarasota Wedding Photographer, Siesta Key Photographer, Venice, Florida, Island Photographics, Island Photography, Beach Portraits, Family Portraits, Senior Portraits, Weddings of Venice, Website Design, Audio Recording Studio, Large Format Printing, Video Production, Television Production, Children Photography, Banner Printing, 101 W. Venice Avenue # 10, Venice, FL 34285, (941) 485-0699, info@islandphotographicsin
<link href="css/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="container">
<div id="uploadform">
<?php // RAY_upload_example.php
error_reporting(E_ALL);
// MANUAL REFERENCE PAGES YOU MUST UNDERSTAND TO UPLOAD FILES
// http://php.net/manual/en/features.file-upload.php
// http://php.net/manual/en/features.file-upload.common-pitfalls.php
// http://php.net/manual/en/function.move-uploaded-file.php
// http://php.net/manual/en/reserved.variables.files.php
// MANUAL PAGES THAT ARE IMPORTANT IF YOU ARE DEALING WITH LARGE FILES
// http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
// http://php.net/manual/en/ini.core.php#ini.post-max-size
// http://php.net/manual/en/info.configuration.php#ini.max-input-time
// PHP 5.1+ SEE http://php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set(
// ESTABLISH THE NAME OF THE DESTINATION FOLDER ('uploads' DIRECTORY)
$uploads = 'RAY_junk';
if (!is_dir($uploads))
{
mkdir($uploads);
}
// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8000000';
// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD
$nf = 3;
// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array
( 'jpg'
, 'gif'
, 'png'
, 'txt'
, 'pdf'
)
;
// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;
// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
?>
<h2>Upload <?php echo $nf; ?> file(s)</h2>
<!--
SOME THINGS TO NOTE ABOUT THIS FORM...
ENCTYPE IN THE HTML <FORM> STATEMENT
MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
ABSENCE OF ACTION= ATTRIBUTE IN FORM TAG CAUSES POST TO SAME URL
-->
<form name="UploadForm" enctype="multipart/form-da
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
<p>
Find the file(s) you want to upload and click the "Upload" button below.
</p>
<?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES
for ($n = 0; $n < $nf; $n++)
{
echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
}
?>
<br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong>
<input type="submit" value="Upload" />
</form>
<?php
die();
}
// END OF THE FORM SCRIPT
// WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
else
{
// THERE IS POST DATA - PROCESS IT
echo "<h2>Results: File Upload</h2>\n";
// ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
// echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n";
// ITERATE OVER THE CONTENTS OF $_FILES
foreach ($_FILES as $my_uploaded_file)
{
// SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
$error_code = $my_uploaded_file["error"]
if ($error_code == 4) continue;
// SYNTHESIZE THE NEW FILE NAME
$f_type = trim(strtolower(end (explode( '.', basename($my_uploaded_file
$f_name = trim(strtolower(current(ex
$my_new_file
= getcwd()
. DIRECTORY_SEPARATOR
. $uploads
. DIRECTORY_SEPARATOR
. $f_name
. '.'
. $f_type
;
$my_file
= $uploads
. DIRECTORY_SEPARATOR
. $f_name
. '.'
. $f_type;
// OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");
// IF THERE ARE ERRORS
if ($error_code != 0)
{
$error_message = $errors[$error_code];
die("Sorry, Upload Error Code: $error_code: $error_message");
}
// GET THE FILE SIZE
$file_size = number_format($my_uploaded
// IF THE FILE IS NEW (DOES NOT EXIST)
if (!file_exists($my_new_file
{
// IF THE MOVE FUNCTION WORKED CORRECTLY
if (move_uploaded_file($my_up
{
$upload_success = 1;
}
// IF THE MOVE FUNCTION FAILED
else
{
$upload_success = -1;
}
}
// IF THE FILE ALREADY EXISTS
else
{
echo "<br/><b><i>$my_file</i></
// SHOULD WE OVERWRITE THE FILE? IF NOT
if (empty($_POST["overwrite"]
{
$upload_success = 0;
}
// IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
else
{
$now = date('Y-m-d');
$my_bak = $my_new_file . '.' . $now . '.bak';
if (!copy($my_new_file, $my_bak))
{
echo "<br/><strong>Attempted Backup Failed!</strong>\n";
}
if (move_uploaded_file($my_up
{
$upload_success = 2;
}
else
{
$upload_success = -1;
}
}
}
// REPORT OUR SUCCESS OR FAILURE
if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
if ($upload_success == 1) { echo "<br/><strong>$my_file</st
if ($upload_success == 0) { echo "<br/><strong>It was NOT overwritten.</strong>\n"; }
if ($upload_success < 0) { echo "<br/><strong>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</strong>\n"; }
if ($upload_success > 0)
{
echo "$file_size bytes uploaded.\n";
if (!chmod ($my_new_file, 0755))
{
echo "<br/>chmod(0755) FAILED: fileperms() = ";
echo substr(sprintf('%o', fileperms($my_new_file)), -4);
}
echo "<br/><a target=\"_blank\" href=\"$my_file\">See the file $my_file</a>\n";
}
// END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
}
}
</div>
</div>
</div>
</body>
</html>