Use this code
<?php
$code=rand(1000,9999);
?>
<script>
function myfun(){
var x = document.getElementById('captcha1').value;
var y = <?php echo $code ?>;
if (x == y) {
return true;
}
else{
return false;
}
}
<script>
<form>
<span-><?php echo $code;?></span>
<input id="captcha1" name="captcha" type="text">
<input id="button" type='submit' onclick=" return myfun();" value='Submit'>
</form>