[英]Need assistance with PHP $_FILE File Upload Script
I am creating an upload script with PHP and HTML that could have any number of file uploads. 我正在创建一个包含PHP和HTML的上传脚本,可以上传任意数量的文件。 I loop through and echo out any number of file uploads and name each one "fileField1", "fileField2" and so on using a loop.
我循环并回显任意数量的文件上传,并使用循环命名每个“fileField1”,“fileField2”等。
Now I want to retrieve the name of the file in that field. 现在我想检索该字段中文件的名称。 Can I use a variable in another loop like this?
我可以在另一个循环中使用变量吗?
$fileField = 'fileField'.$i;
$fileName = $_FILES[$fileField]['name']; // Name of file
This is contained within the loop, will this work? 这包含在循环中,这会起作用吗?
I believe I am experiencing an error... 我相信我遇到了错误......
Variable $i is increased by one each time ($i++) 变量$ i每次增加一($ i ++)
EDIT 编辑
Notice the comment that I never reach... 请注意我从未达到的评论......
Here is the whole loop: 这是整个循环:
$i = 1;
while ($i <= $numberOfFields) {
$fileField = 'fileField'.$i;
$titleId = 'title'.$i;
$genreId = 'genre'.$i;
$fileName = $_FILES[$fileField]['name']; // Name of file
if($fileName !=""){
$randNum = rand(1000000000,9999999999); //Generate random number
$newFileName = $fileName."-".$randNum; //Rename file
if (file_exists($baseUrl."images/".$newFileName)){
echo $newFileName." already exists. ";
}else{
if(isset($_POST[$titleId]) && !empty($_POST[$titleId])){
// Assign url, title, genre
$url = 'images/'.$newFileName;
$title = $_POST[$titleId];
$genre = $_POST[$genreId];
// Execute final query and upload
$sql = "INSERT INTO images (url,title,genre) VALUES (:url,:title,:genre)";
$q = $conn->prepare($sql);
$q->execute(array(':url'=>$url,
':title'=>$title,
':genre'=>$genre));
if(copy($_FILES['fileField']['tmp_name'],'../images/'.$newFileName)) {
$NOTICE = 'File successfully uploaded!';
// I AM NEVER REACHING THIS NOTICE WHICH IS ECHOED LATER ON IN THE CODE
}
}else{
$NOTICE = "Please fill out the title for picture ".$i;
break;
}
}
}else{
$NOTICE = "Please select a file to upload in slot ".$i;
break;
}
$i++;
}
if(copy($_FILES['fileField']['tmp_name'],'../images/'.$newFileName)) {
I believe should be: 我相信应该是:
if(move_uploaded_file($_FILES['fileField']['tmp_name'],'../images/'.$newFileName)) {
And yes, you can put variables in [] like that. 是的,您可以将变量放在[]中。 So long as they're valid and won't result in an undefined offset error.
只要它们有效并且不会导致未定义的偏移误差。
Don't use copy
. 不要使用
copy
。 Use move_uploaded_file
first, before you do anything with the uploaded file. 在对上传的文件执行任何操作之前,请先使用
move_uploaded_file
。 Files are uploaded to a special, temporary location. 文件上传到特殊的临时位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.