Uploading a file in PHP
I'm trying to upload a file using PHP.
My folder structure is the following:
I have a directory called schemas
in my root htdocs folder. Inside this folder, I want to create a new folder for every user; in this folder I'll be storing user-specific files.
For now, my code is incomplete (doesn't check whether or not the folder/file already exists and might error on this), but I'm just trying to get the basics to work.
<?php
if ($_FILES ["bestand"] ["error"] > 0) {
//for error messages: see http://php.net/manual/en/features.fileupload.errors.php
switch ($_FILES ["bestand"] ["error"]) {
case 1 :
$msg = "U mag maximaal 2MB opladen.";
break;
default :
$msg = "Sorry, uw upload kon niet worden verwerkt.";
}
} else {
//check MIME TYPE - http://php.net/manual/en/function.finfo-open.php
$allowedtypes = array ("application/pdf" );
$filename = $_FILES ["bestand"] ["tmp_name"];
$finfo = new finfo ( FILEINFO_MIME_TYPE );
$fileinfo = $finfo->file ( $filename );
if (in_array ( $fileinfo, $allowedtypes )) {
//move uploaded file
$dir = "schemas";
chdir("schemas");
$user_folder = str_replace(" ", "", $_POST['schema']);
mkdir( $user_folder, 0777);
// echo getcwd();
// closedir($open);
$folder = "/schemas/" . $user_folder . "/" . $_FILES ["bestand"] ["name"];
echo $folder;
echo $user_folder;
if (move_uploaded_file ( $_FILES ["bestand"] ["tmp_name"], $folder )) {
$msg = "Uw schema is succesvol geupload!";
} else {
$msg = "Upload mislukt.";
}
} else {
$msg = "U kan enkel een pdf uploaden.";
}
}
echo $msg . "<br />";
?>
When I try this, I get the following warnings:
Warning: move_uploaded_file(/schemas/loesp/loopschema-0-tot-5-kilometer.pdf) [function.move-uploaded-file]: failed to open stream: No such file or directory in /Applications/MAMP/htdocs/Sportjefit2/uploadenfile.php on line 30
Warning: move_开发者_如何学JAVAuploaded_file() [function.move-uploaded-file]: Unable to move '/Applications/MAMP/tmp/php/phpMsxxsu' to '/schemas/loesp/loopschema-0-tot-5-kilometer.pdf' in /Applications/MAMP/htdocs/Sportjefit2/uploadenfile.php on line 30
The script does create the folder (in this case loesp
) but does not seem to upload or move the actual file. I'm stumped.
The problem is that you're using an absolute path, which starts in the root of the entire machine. You should use a relative path, and it should start from the current working directory.
You already are inside the schemas
folder (after the call to chdir), so $folder should be set to this:
$folder = $user_folder . "/" . $_FILES ["bestand"] ["name"];
精彩评论