제출 이벤트 처리시에는 javscript
을 사용하십시오. 프로그램 상태의 저장은 다양한 방법으로 수행 될 수 있습니다. 이 예에서는 값을 저장하기 위해 두개 숨겨진 필드를 사용했을
<input type="hidden" name="DifficultyChoice" id="hiddDiff" value="-1" />
<input type="hidden" name="toolChoice" id="hiddTool" value="-1" />
나는 두 함수
changeDifficulty
및
int
전달되는
changeTools
만들었고, 이들은 물론
hidden fields
값을 설정.
Hidden fields
은 수신 PHP
파일로 전달되는 name
을 가지고 있기 때문에 사용됩니다. 따라서 각 button
에 names
을 사용할 필요가 없습니다. 대신 javascript
이 two functions
및 two hidden fields
와 함께 당신을 위해 그것을 할 수 있습니다 :
편집
: 영업뿐만 아니라 수신 서버 측 요청 이후 내가 작업, 예를 들어 원래의 대답을 교체했다.
이 프로그램은 두 PHP
파일 a_test.php
및 b_tesp.php
, 한 javascript
파일 a_test.js
로 구성되어 있습니다. 이 예제가 작동하려면 모두 같은 폴더에 있어야합니다.
프로그램 순서 :a_test.php
이 a_test.js
를 사용하여 b_test.php
에 POST
데이터를 전송합니다. b_test.php
이 데이터를 수신하고 유효성 검사를 시도합니다. 모든 것이 정상이면 이미지가 업로드되고, 그렇지 않으면 오류 메시지가 나타납니다.
파일 a_test.php
:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<script src="a_test.js"></script>
</head>
<body>
<form id="formUploadFile" name="formUploadFile" action="b_test.php" enctype="multipart/form-data" method="post" >
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size ?>">
<p align="left">
<label for="file" >First, Choose your image!</label>
<input type="file" name="img_1" />
</p>
<h5>Would you like to use colored pencils or paint?</h5>
<div class="btn-group">
<input type="button" class="btn btn-primary" value="Colored Pencils" onclick="changeTools(0)" />
<input type="button" class="btn btn-primary" value="Paint" onclick="changeTools(1)" />
</div>
<h5>Then, Choose your Difficulty!</h5>
<div class="btn-group">
<input type="button" class="btn btn-success" value="Kids" onclick= "changeDifficulty(0)" />
<input type="button" class="btn btn-success" value="Novice" onclick="changeDifficulty(1)" />
<input type="button" class="btn btn-success" value="Intermediate" onclick="changeDifficulty(2)" />
<input type="button" class="btn btn-success" value="Advanced" onclick="changeDifficulty(3)" />
</div>
<input type="hidden" name="difficultyChoice" id="hiddDiff" value="-1" />
<input type="hidden" name="toolChoice" id="hiddTool" value="-1" />
</form>
</body>
</html>
파일 a_test.js
:
function changeDifficulty(number)
{
var toolChoice = parseInt(document.getElementById('hiddTool').value)
var difficulty = document.getElementById('hiddDiff');
var form = document.getElementById('formUploadFile');
difficulty.value = number;
// if the toolChoice is set
if(toolChoice != -1)
{
// Show the values, for testing purposes
console.log("Tools: " + toolChoice + " Difficulty: " + difficulty.value);
form.submit();
}
}
function changeTools(number)
{
var difficulty = parseInt(document.getElementById('hiddDiff').value)
var toolChoice = document.getElementById('hiddTool');
var form = document.getElementById('formUploadFile');
toolChoice.value = number;
// If the difficulty is set
if(difficulty != -1)
{
console.log("Tools: " + toolChoice.value + " Difficulty: " + difficulty);
form.submit();
}
}
파일 b_test.php
:
<?php
// make a function to check if `int` so you don't have to retype for each variable
function checkIfInt($var)
{
// Here we use a fix to let `0` also be validated as `int`
if (filter_var($var, FILTER_VALIDATE_INT) || filter_var($var, FILTER_VALIDATE_INT) === 0)
{
return true;
}
else
{
return false;
}
}
function checkImageValidityAndUpload()
{
// Check if file was uploaded without errors
if($_FILES["img_1"]["error"] == 0)
{
// allowed image types
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
// some (incoming) file properties
$filename = $_FILES["img_1"]["name"];
$filetype = $_FILES["img_1"]["type"];
$filesize = $_FILES["img_1"]["size"];
// Verify file extension (here we are comparing the file extension to the keys of $allowed array)
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed))
{
echo "Error: Please select a valid file format.<br/>";
return false;
}
// Verify file size - 5MB maximum (5MB is example, you can set anything)
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize)
{
echo "Error: File size is larger than the allowed limit.<br/>";
return false;
}
// Verify MYME type of the file (here we are comparing the file MYME type to the $allowed array values)
if(in_array($filetype, $allowed))
{
// Check whether file exists before uploading it (upload/ is example folder, change to your image folder)
if(file_exists("upload/" . $_FILES["img_1"]["name"]))
{
echo $_FILES["img_1"]["name"] . " already exists.<br/>";
return false;
}
else
{
move_uploaded_file($_FILES["img_1"]["tmp_name"], "upload/" . $_FILES["img_1"]["name"]);
return true;
}
}
else
{
echo "Error: There was a problem uploading your file. Please try again.<br/>";
return false;
}
}
else
{
echo "Error: " . $_FILES["img_1"]["error"]."<br/>";
return false;
}
}
// MAIN program starts here - Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$tools = array("Colored Pencils", "Paint");
$difficulties = array("Kids", "Novice", "Intermediate", "Advanced");
// check if all needed variables are set and valid, and if the image is valid and uploaded successfully
if(isset($_POST['difficultyChoice']) && isset($_POST['toolChoice']) && isset($_FILES['img_1']) &&
checkIfInt($_POST['difficultyChoice']) && checkIfInt($_POST['toolChoice']) &&
checkImageValidityAndUpload())
{
$diff = intval($_POST['difficultyChoice']);
$tool = intval($_POST['toolChoice']);
echo 'Tools choice: '.$tools[$tool].' Difficulty choice: '.$difficulties[$diff].'<br/>';
echo 'image has been uploaded successfully';
// do something
}
else
{
echo 'Something went wrong. Program will not continue';
die();
}
}
else
{
echo 'There was no POST request.';
die();
}
?>
다음
코드입니다
나는 이것이 쓰여지는 방식으로, 다른 버튼을 선택할 때마다 버튼이 -1로 재설정되도록한다고 생각합니다. 각 함수의 시작 부분에서 요소 ID로 변수를 설정하고 요소 ID가있는 유일한 영역은 값이 -1로 설정 되었기 때문입니다. 또한, PHP 사이트에서 이러한 버튼의 가치를 얻는 방법은 무엇입니까? – clutch1020
@ clutch1020 이제 이미지, difficultChoice 및 toolChoice를'b_test.php'라는 파일에 제출할 예제 파일'a_test.php'에 대한 예제 (방금 테스트했습니다)를 업로드 할 것입니다. 파일'a_test.php'는 자바 스크립트 파일'a_test.js'를 사용합니다. 이 파일들을 모두 같은 폴더에 넣으십시오. 'b_test.php'에서 남긴 주석을 읽고 프로그램이 수신 측에서 어떻게 작동하는지 이해하십시오. 폴더가 존재하는지 프로그램이 확인하지 않기 때문에'upload folder'를 기존 폴더로 설정하십시오. – Ivan86
@ clutch1020 확인. 나는 편집했다. 코드를 새로운 파일에'복사/붙여 넣기 (copy/paste) '하고 파일 이름을 지정하여 작업 한 것을 확인하십시오. 이미지를 업로드하는 것은 보안 위험이 크고 올바르게 검사해야하기 때문에 서버 측 코드의 양 ('b_test.php')이 필요합니다. – Ivan86