PHP FTP Upload BLOB TEMP Image - javascript

I am trying to upload an Image of a Form via FTP.
But because I validate my Form with Javascript I can't offer PHP the File Object.
Instead I pass the temporary blob path of the image.
When I try to upload, it doesn't work.
If I take then the blob path and put it manually in the brwoser line it displayes the image which means my blob path isn't corrupt.
Can't PHP / FTP take an blob temp image as the source file?
Here is my Code:
Javascript and HTML
$(document).ready(function() {
$('#testImageSelect').change( function(event) {
var validation = false;
var message = "";
validation = validateImage();
if(validation){
message = "Javascript: Das Bild ist ok!";
$("#submitTest").attr("disabled",false);
}else{
message = "Javascript: Das Bild entspricht nicht den Anforderungen!";
$("#submitTest").attr("disabled",true);
}
document.getElementById("scriptresultJs").innerHTML = "<p>"+message+"</p>";
});
$("#submitTest").click(function () {
var message = "";
var dataSubmit = [];
var pic = document.getElementById("testImageSelect").files[0];
var pic_path = URL.createObjectURL(pic);
var picture = [];
picture = {
tmp_path: pic_path,
name: pic.name,
size: pic.size
}
dataSubmit = {
castingcity: "Coruscant",
forename: "Anakin",
lastname: "Skywalker",
geschlecht: "Männlich"
};
var result = "default";
result = $.ajax({
type: 'POST',
async: false, // WICHTIG!
url: 'http://hiddentalents.de/php/test.php',
data: ({
data: dataSubmit,
picture: picture
})
}).responseText;
message = result;
document.getElementById("scriptresultPHP").innerHTML = "<p>"+message+"</p>";
});
});
function validateImage() {
var validation = false;
var pic = $("#testImageSelect").val().split('/').pop().split('\\').pop();
var ext = pic.substring(pic.lastIndexOf('.') + 1);
if(ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG"){
validation = true;
}
else{
validation = false;
}
return validation;
}
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="screen">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>Servertesting</title>
</head>
<body>
<form role="form" method="post" action="" id="testForm" enctype="multipart/form-data">
<input type="file" id="testImageSelect" name="testImageSelect" required>
</form>
<button class="btn btn-default" id="submitTest" disabled>Abschicken</button>
<div id="scriptresultJs"></div>
<p id="scriptresultPHP"></p>
</body>
</html>
PHP
<?php
$db_host = "rdbms.strato.de";
$db_datenbank = "(name of database)";
$db_username = "(username)";
$db_password = "(password)";
$output = "";
SESSION_START();
# Datenbankverbindung herstellen
$datenbank = new mysqli($db_host, $db_username, $db_password, $db_datenbank);
# Hat die Verbindung geklappt ?
if ($datenbank->connect_errno) {
$output = $output . "\n" . "Fehler beim Verbinden mit der Datenbank: (" . $datenbank->connect_errno . ") " . $datenbank->connect_error;
}
//UTF 8 einstellen
mysqli_query($datenbank, "SET NAMES 'utf8'");
# Wurde überhaupt was eingetragen?
if(isset($_POST["data"])) {
//Image überprüfung:
$output = $output . "\n". $_POST["picture"]["tmp_path"];
$target_dir = "temp/";
$target_file_path = $target_dir . date('dmYHis_') . $_POST["picture"]["name"];
$uploadOk = 1;
$imageFileType = pathinfo($target_file_path,PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file_path)) {
$output = $output . "\n" . "Es tut uns leid, das gewählte Bild existiert bereits.";
$uploadOk = 0;
}
// Check file size
if ($_POST["picture"]["size"] > 1500000) {
$output = $output . "\n" . "Die Bilddatei ist leider zu groß.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "jpeg" && $imageFileType != "JPG" && $imageFileType != "JPEG" ) {
$output = $output . "\n" . "Leider sind nur JPG bzw. JPEG Dateien erlaubt. Sie haben eine " . $imageFileType . " Datei hochgeladen!";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$output = "Die Datei konnte leider nicht hochgeladen werden. Folgende Fehler sind verantwortlich:\n".$output;
// if everything is ok, try to upload file
} else {
//Upload Image
$ftp_server = "ftp.strato.de";
$ftp_user_name = "(username)";
$ftp_user_pass = "(password)";
$destination_file = $target_file_path;
$source_file = $_POST['picture']["temp_path"];
// Verbindung aufbauen
$conn_id = ftp_connect($ftp_server);
// Login mit Benutzername und Passwort
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// Verbindung überprüfen
if ((!$conn_id) || (!$login_result)) {
$output = $output . "\n" . "FTP-Verbindung ist fehlgeschlagen!";
$output = $output . "\n" . "Verbindungsaufbau zu $ftp_server mit Benutzername $ftp_user_name versucht.";
exit;
} else {
$output = $output . "\n" . "Verbunden zu $ftp_server mit Benutzername $ftp_user_name";
}
// Datei hochladen
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);
// Upload überprüfen
if (!$upload) {
$output = $output . "\n" . "FTP-Upload ist fehlgeschlagen!\nDie Datei $source_file konnte nicht auf dem Server $ftp_server als $destination_file hochgeladen werden!";
} else {
$output = $output . "\n" . "Datei $source_file auf Server $ftp_server als $destination_file hochgeladen";
}
// Verbindung schließen
ftp_close($conn_id);
//Datenbankeinträge machen:
$castingcity = mysqli_real_escape_string($datenbank,$_POST["data"]["castingcity"]);
$forename = mysqli_real_escape_string($datenbank,$_POST["data"]["forename"]);
$lastname = mysqli_real_escape_string($datenbank,$_POST["data"]["lastname"]);
$geschlecht = mysqli_real_escape_string($datenbank,$_POST["data"]["geschlecht"]);
$picture = $target_file_path;
//Insert Data (except Image)
$sql = "INSERT INTO candidates_temp (castingcity, forename, lastname, geschlecht, picture)
VALUES ('$castingcity', '$forename', '$lastname', '$geschlecht', '$picture')";
if ($datenbank->query($sql) === TRUE) {
$output = $output . "\n" . "Datenbank Werte eingetragen!";
} else {
$output = $output . "\n" . "Error: " . $sql . "<br>" . $datenbank->error;
}
}
}else {
$output = $output . "\n" . "POST Variable leer!";
}
$datenbank->close();
echo $output;
?>

Finally solved
If ound this Tutorial, and it works!!!

Related

$_GET in uploading image

my code is working if I use $_SESSION but I need to name the file what is in the URL.
this is the sample URL: localhost/boldr/updateimage.php?EMPLOYEE_ID=180627-027
I want to rename the uploaded image like profile180627-027 but it's not working in $_GET.
<?php
$id = $_GET['EMPLOYEE_ID'];
if (isset($_POST['submit'])){
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.',$fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if(in_array($fileActualExt, $allowed)){
if($fileError == 0){
if($fileSize < 1000000){
$fileNameNew = "profile".$id.".".$fileActualExt;
$fileDestination = 'img/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE employees SET image=0 WHERE EMPLOYEE_ID='$id'";
$result = mysqli_query($conn, $sql);
header("Location: updateimage.php?EMPLOYEE_ID=$id");
}else{
echo "Your file is to big";
}
}else{
echo "There was an error!";
}
}else{
echo "You cannot upload files of this file";
}
}
echo "<form action='updateimage.php' method='POST' enctype='multipart/form-
data'>
<input type='file' name='file'>
<button type='submit' name='submit'>Upload</button>
</form>";
?>
How about trying this in your form part:
action='updateimage.php?EMPLOYEE_ID=$id'

Ajax Jquery and PHP form validation, 404 error

I am trying to process a form with ajax, jquery and php and I am getting a 404 error, searched before I posted but I did not find the answer to help me fix my problem, this is the .js file :
$(document).ready(function() {
$('form #error-message').hide();
$('#submit').on('click' , function(e) {
e.preventDefault();
var valid = '';
var required = " is required";
var fname = $('form #fname').val();
var lname = $('form #fname').val();
var dbirth = $('form #dbirth').val();
var adress1 = $('form #adress1').val();
if (fname = '' || fname.lenght <= 2) {
valid += '<p><span>X</span> Full Name ' + required + '</p>';
}
if (lname = '' || lname.lenght <= 2) {
valid += '<p><span>X</span> Full Name ' + required + '</p>';
}
if (dbirth = '' || dbirth.lenght <= 2) {
valid += '<p><span>X</span> Full Name ' + required + '</p>';
}
if (adress1 = '' || adress1.lenght <= 5) {
valid += '<p><span>X</span> Full Name ' + required + '</p>';
}
if(valid != '') {
$('form #error-message').removeClass().addClass('warning')
.html('<h1>Please complete all the fields</h1>' + valid);
} else {
var contactData = $( 'form' ).serialize();
console.log(contactData);
$.ajax({
type: 'POST',
url: 'ajaxform/process.php',
data: contactData,
success: function() {
$('#error-message').removeClass().addClass('success')
.html("<h1>Thank you for contacting me. I will reply as soon as i can!</h1>");
},
error: function() {
$('#error-message').removeClass().addClass('alert-error')
.html("An error has occured. Please try again later")
},
complete: function() {
$('form')[0].reset();
}
});
}
});
});
and this is the .php file :
<?php
sleep(1);
$to = 'yourcompany#gmail.com';
$subject = 'My form contact';
if( isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['dbirth']) && isset($_POST['adress1'])) {
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$sdate = trim($_POST['dbirth']);
$adress1 = trim($_POST['adress1']);
if(!empty($fname) && !empty($lname) && !empty($dbirth) && !empty($adress1)) {
$full_name = $fname . " " . $lname;
$body = $full_name . "\n" . $adress1;
$headers = "From {$full_name} " . $dbirth;
mail($to, $subject, $body, $headers);
}
} else {
header('location: ../index.html');
}
?>
I suggest you phpmailer. You can download it at this link.
<?php
require_once('class.phpmailer.php');
sleep(1);
$to = 'yourcompany#gmail.com';
$subject = 'My form contact';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 1; // will send erros and messages
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Host = "smtp.gmail.com";
$mail->Port = 587; //Gmail smtp port
$mail->Username = "youremail#gmail.com";
$mail->Password = "yourpassword";
$mail->SetFrom($headers);
$mail->Subject = $subject;
if( isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['dbirth']) && isset($_POST['adress1'])) {
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$sdate = trim($_POST['dbirth']);
$adress1 = trim($_POST['adress1']);
if(!empty($fname) && !empty($lname) && !empty($dbirth) && !empty($adress1)) {
$full_name = $fname . " " . $lname;
$body = $full_name . "\n" . $adress1;
$headers = "From {$full_name} " . $dbirth;
$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
header('location: ../index.html');
}
}
}
?>

php | Defend move_upload_file or delete files from input[type="file"] using jQuery

I have an input[type="file"] had multiple option. I made it preview function so that user can delete the image by clicking the button before submit. The images are deleted well on browser by remove() function however the problem is the values of input including the deleted images are posted when i submit. I don't know how to delete real value of input.
I've tried to figure it out to delete in the server side.
This is the part of html code.
<div class="col-xs-4 vcenter from-group">
<span class="glyphicon glyphicon-asterisk" style="color:red;"></span><label for="inputScreenshots">스크린샷</label>
<p style="display:inline; padding-left:270px; color:red; font-size: 12px">* 이미지 사이즈 : 800 X 450</p>
<input type="file" id="inputScreenshots" name="inputScreenshots[]" class="form-control" accept="image/*" multiple>
<div id="filenameList" style="width : 400px">
<div id="insertScreenshots" style="margin : 30px; position :relative;">
<input type="hidden" name="screenshots_filename[]" value="<?=$screenshot_urls?>">
</div>
</div>
This is the php code where im trying to defend uploading images.
$ss_upload="false";
if (isset($_POST["del_screenshots"])){
// del_screenshots are images that deleted from client.
$ds_count = $_POST["del_screenshots"];
foreach($ds_count as $del) {
echo "<br/> del_screenshots : ".$del;
}
}
$ss_count = sizeof($_FILES['inputScreenshots']['tmp_name']);
// ss_count is the size of all images including deleted images from input field.
echo "<br/>ss_cout : ". $ss_count;
for ($i = 0; $i < $ss_count; $i++) {
$tmpFilePath = $_FILES['inputScreenshots']['tmp_name'][$i];
$tmp_filename = $_FILES['inputScreenshots']['name'][$i];
// tmp_filename is the posted real file name.
echo "<br/> tmp_filename".$i. " : " .$tmp_filename;
//=========================================================================
for ($j = 0; $j < sizeof($ds_count); $j++) {
// Compare all images name and deleted images name
if (strcmp($ds_count[$j] , $tmp_filename) == 0) {
echo "<br/>".$ds_count[$j] . " == " . $tmp_filename . "==> " ."true";
// The $tmp_filename has to be deleted. not to be uploaded to server.
// $tmp_filename = null;
}else {
echo "<br/>".$ds_count[$j] . " == " . $tmp_filename . "==> " ."false";
// This files are okay to be uploaded to server.
}
}
//=========================================================================
$ext = pathinfo($tmp_filename, PATHINFO_EXTENSION);
// $ext = pathinfo($_FILES['inputScreenshots']['name'][$i], PATHINFO_EXTENSION);
echo "<br/>". $i . " ext (pathinfo) : ". $ext;
if ($ext == "") {
continue;
$ss_upload="false";
}
$newFilePath = uniqid().".".$ext;
if ($screenshots != "") {
$screenshots .= "+";
}
$screenshots .= $newFilePath;
// $screenshots has be uploaded to DB except the deleted images. (ex : uniqFileName.png + uniqFileName.png + .. )
echo "<br/> 1) screenshots : ". $screenshots;
move_uploaded_file($tmpFilePath, $SS_PATH."/".$newFilePath);
$ss_upload="true";
}
I want to defend uploading the deleted images but it is no matter to use unlink() in somewhere. The point is how cant i make the string except the deleted images.
=========================================================================
I suppose there is another way to do in jQuery but i have no idea.
I'll put the code below.
$("#inputScreenshots").change(function(){
$("#filenameList div.notyet").remove();
for(var i = 0, len = this.files.length; i < len; i++){
var file = this.files[i];
var fr = new FileReader();
fr.onload = screenshots_processFile(file);
fr.readAsDataURL(file);
}
});
var screenshots_processFile = function screenshots_processFile(file) {
return (function(file) {
return function(e) {
var div = document.createElement("div");
$(div).addClass("notyet").css({
margin: "30px",
position: "relative"
});
var html = [,'<img src="" width="100%" id="tmp_screenshots">'
,'<button type="button" class="close img-close" aria-label="Close"><span aria-hidden="true">×</span></button>'
].join("");
$(div).append(html);
$(div).find("button").click(function() {
alert("remove");
//=========================================================== * TODO : remove the files in server!
var targetDom = document.getElementById( "filenameList" );
var targetInput = document.createElement("input");
targetInput.setAttribute("name", "del_screenshots[]" );
targetInput.setAttribute("type","hidden");
targetDom.appendChild(targetInput);
alert(file.name);
targetInput.setAttribute("value", file.name);
//===========================================================
$(this).parent().remove();
});
$(div).find("img").attr("src", e.target.result);
$("#filenameList").append(div);
}
})(file)
};
How can i do this? Does anyone have an idea?
-----------------------------------------------------------------------------------------------------------
I solved it like this. I know my code is so dirty :-/
$ss_upload="false";
if (isset($_POST["del_screenshots"])){
$ds_count = $_POST["del_screenshots"];
foreach($ds_count as $del) {
echo "<br/> del_screenshots : ".$del;
}
//echo "<br/> << TEST >>"."<br/>ds_count[0] : " . $ds_count[0] . "<br/>ds_count[1] : " . $ds_count[1] ;
}
$ss_count = sizeof($_FILES['inputScreenshots']['tmp_name']);
echo "<br/>ss_cout : ". $ss_count;
for ($i = 0; $i < $ss_count; $i++) {
$tmpFilePath = $_FILES['inputScreenshots']['tmp_name'][$i];
$tmp_filename = $_FILES['inputScreenshots']['name'][$i];
echo "<br/> tmp_filename".$i. " : " .$tmp_filename;
$ss_del_mode="false";
//=========================================================================
if (isset($_POST["del_screenshots"])) {
for ($j = 0; $j < sizeof($ds_count); $j++) {
if (strcmp($ds_count[$j] , $tmp_filename) == 0) {
echo "<br/>".$ds_count[$j] . " == " . $tmp_filename . "==> " ."true";
$ss_del_mode = "true";
}
}
}
//=========================================================================
$ext = pathinfo($tmp_filename, PATHINFO_EXTENSION);
// $ext = pathinfo($_FILES['inputScreenshots']['name'][$i], PATHINFO_EXTENSION);
echo "<br/>". $i . " ext (pathinfo) : ". $ext;
if ($ext == "") {
continue;
$ss_upload="false";
}
if ($ss_del_mode == "true") {
echo "<br/> ss_del_mode [[[[ " . $ss_del_mode. " ]]]]";
$newFilePath = "";
} else {
$newFilePath = uniqid().".".$ext;
echo "<br/> ss_del_mode [[[[ " . $ss_del_mode. " ]]]]";
}
if ($screenshots != "") {
if ($ss_del_mode != "true"){
echo "<br/> ss_del_mode [[[[ " . $ss_del_mode. " ]]]]". " --> screenshots";
$screenshots .= "+";
}
}
$screenshots .= $newFilePath;
echo "<br/> 1) screenshots (newFilePath) : ". $screenshots;
if ($newFilePath != "") {
move_uploaded_file($tmpFilePath, $SS_PATH."/".$newFilePath);
}
$ss_upload="true";
}

Upload image with PHP and AngularJS

I am working on a admin panel which is going to add data on a SQLite DB using AngularJS and PHP and then show it in HTML. All good with data as arrays text date etc. The problem that I have is to upload an Image in a specified folder and store the path in my DB.
This is my PHP which store data in DB
<?php
try {
if (
empty($_POST['item']) ||
empty($_POST['description']) ||
empty($_POST['release']) ||
empty($_POST['demo']) ||
empty($_POST['type']) ||
empty($_POST['live']) ||
empty($_POST['client'])
) {
throw new PDOException("Invalid Request");
}
$item = $_POST['item'];
$description = $_POST['description'];
$release = $_POST['release'];
$demo = $_POST['demo'];
$type = $_POST['type'];
$live = $_POST['live'];
$client = $_POST['client'];
$objDb = new PDO('sqlite:../database/database');
$objDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO 'items'
('id', 'item', 'description', 'release', 'demo', 'type', 'live', 'client')
VALUES (null, ?, ?, ?, ?, ?, ?, ?)";
$statement = $objDb->prepare($sql);
if (!$statement->execute(array($item, $description, $release, $demo, $type, $live, $client))) {
throw new PDOException("The execute method failed");
}
And this is my PHP which upload Images in a specified folder
<?php
if (isset($_POST['submit'])) {
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 1000000)
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
} else {
echo "<span>Your File Uploaded Succesfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <b>already exists.</b> ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
echo "<b>Stored in:</b> " . "upload/" . $_FILES["file"]["name"];
}
}
} else {
echo "<span>***Invalid file Size or Type***<span>";
}
}
?>
And this is my insert function from angular
$scope.insert = function() {
if ($scope.goodToGo()) {
var thisData = "item=" + $scope.item;
thisData += "&description=" + $scope.description;
thisData += "&release=" + $scope.release;
thisData += "&demo=" + $scope.demo;
thisData += "&client=" + $scope.client;
thisData += "&type=" + $scope.type;
thisData += "&live=" + $scope.live;
thisData += "&image=" + $scope.image;
$http({
method : 'POST',
url : urlInsert,
data : thisData,
headers : {'Content-Type' : 'application/x-www-form-urlencoded'}
})
.success(function(data){
if(_recordAddedSuccessfully(data)){
$scope.items.push({
id : data.item.id,
item : data.item.item,
description : data.item.description,
release : data.item.release,
demo : data.item.demo,
client : data.item.client,
client_name : data.item.client_name,
type : data.item.type,
type_name : data.item.type_name,
live : data.item.live,
live_name : data.item.live_name,
image : data.item.image,
done : data.item.done
});
$scope.clear();
}
})
.error(function(data, status, headers, config){
throw new Error('Something went wrong with inserting');
});
}
};
Have anyone any idea how to do this?
If you are uploading image then content type should be set to multipart/form-data i.e
headers : {'Content-Type' : 'multipart/form-data'}
rest looks fine.

Verify reCaptcha google in FrontEnd php ajax jquery

I'm trying to create a form with reCaptcha.
Although I'm not an expert with javascript and ajax I succeed to cretae form and verify it with ajax before submit but when I added reCaptcha to my form I couldn't verify it FrontEnd. (In Backend, it works very well and the form is sent only if all field and captcha are all correctly filled)
I want to create something to alert user when he didn't fill the reCaptcha.
Below my code:
/********** index.php *************/
<?php
$siteKey = 'public key'; // votre clé publique
?>
<form action="process.php" id="contact" method="POST">
<label for="nom" class="label-style">Nom</label>
<input class="w-input field-style" id="nom" name="nom" onkeyup="checkFilled('nom');" type="text">
<span id="msg_nom"></span>
<label for="email" class="label-style">Email</label>
<input class="w-input field-style" id="email" name="email" onkeyup="checkFilledEmail('email');" type="email">
<span id="msg_email"></span>
<label for="sujet" class="label-style" >Sujet</label>
<input class="w-input field-style" id="sujet" name="sujet" onkeyup="checkFilled('sujet');" type="text">
<span id="msg_sujet"></span>
<label class="label-style" for="message">Message</label>
<textarea class="w-input messageform" id="message" name="message" onkeyup="checkFilled('message');" rows="10" cols="80"></textarea>
<span id="msg_message"></span>
<div class="g-recaptcha" data-sitekey="<?php echo $siteKey; ?>"></div>
<span id="msg_captch"></span>
<span id="msg_all"></span>
<input class="w-button simple-button" type="submit" value="Envoyer" />
</form>
<script type="text/javascript">
function checkFilled(variable) {
var inputVal = document.getElementById(variable).value;
if (inputVal == "") {
document.getElementById(variable).style.borderColor = "red";
}
else{
document.getElementById(variable).style.borderColor = "green";
}
}
function checkFilledEmail(variable) {
fld_value = document.getElementById(variable).value;
is_m_valid = 0;
if (fld_value.indexOf('#') >= 1) {
m_valid_dom = fld_value.substr(fld_value.indexOf('#')+1).length;
if (m_valid_dom >= 1) {
is_m_valid = 1;
}
}
if (is_m_valid) {
document.getElementById(variable).style.borderColor = "green";
} else {
document.getElementById(variable).style.borderColor = "red";
}
}
$(function(){
$("#contact").submit(function(event){
var nom = $("#nom").val();
var sujet = $("#sujet").val();
var email = $("#email").val();
var message = $("#message").val();
var dataString = nom + sujet + email + message;
var captch = $('.g-recaptcha').val();
var msg_all = "Merci de remplir tous les champs";
var msg_alert = "Merci de remplir le champs: ";
var msg_captch = " merci de remplir captcha";
$("#msg_all").html('');
$("#msg_nom").html('');
$("#msg_email").html('');
$("#msg_sujet").html('');
$("#msg_message").html('');
if(dataString == "")
{
document.getElementById('nom').style.borderColor = "red";
document.getElementById('email').style.borderColor = "red";
document.getElementById('sujet').style.borderColor = "red";
document.getElementById('message').style.borderColor = "red";
$('html, body').animate({
scrollTop: $("#msg_nom").offset().top
}, 500);
}
else if(nom == "")
{
var el10=document.getElementById('nom');
el10.style.borderColor = "red";
}
else if(email == "")
{
document.getElementById('email').style.borderColor = "red";
}
else if(sujet == "")
{
document.getElementById('sujet').style.borderColor = "red";
}
else if(message == "")
{
document.getElementById('message').style.borderColor = "red";
}
else
{
$.ajax({
type : "POST",
url: $(this).attr("action"),
data: $(this).serialize(),
success : function(){
$("#msg_all").html(" <p style='text-align:center; margin-bottom:40px;'>Formulaire bien envoyé</p> ");
$(':input','#contact')
.not(':button, :submit, :reset, :hidden')
.val('');
$("#msg_nom").html('');
$("#msg_email").html('');
$("#msg_sujet").html('');
$("#msg_message").html('');
document.getElementById('nom').style.borderColor = "";
document.getElementById('email').style.borderColor = "";
document.getElementById('sujet').style.borderColor = "";
document.getElementById('message').style.borderColor = "";
$('html, body').animate({
scrollTop: $("#msg_nom").offset().top
}, 500);
},
error: function(){
$("#msg_all").html("<p style='text-align:center; margin-bottom:40px;'>Erreur dappel, le formulaire ne peut pas fonctionner</p>");
document.getElementById('nom').style.borderColor = "";
document.getElementById('email').style.borderColor = "";
document.getElementById('sujet').style.borderColor = "";
document.getElementById('message').style.borderColor = "";
}
});
}
return false;
});
});
</script>
/************ process.php **************/
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://www.google.com/recaptcha/api.js"></script>
<?php
require 'recaptchalib.php';
$secret = 'private key'; // votre clé privée
// CONDITIONS NOM
if ( (isset($_POST["nom"])) && (strlen(trim($_POST["nom"])) > 0) ):
$nom = stripslashes(strip_tags($_POST["nom"]));
else:
echo "Merci décrire un nom <br />";
$nom = "";
endif;
// CONDITIONS SUJET
if ( (isset($_POST["sujet"])) && (strlen(trim($_POST["sujet"])) > 0) ):
$sujet = stripslashes(strip_tags($_POST["sujet"]));
else:
echo "Merci décrire un sujet <br />";
$sujet = "";
endif;
// CONDITIONS EMAIL
if ( (isset($_POST["email"])) && (strlen(trim($_POST["email"])) > 0) && (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) ):
$email = stripslashes(strip_tags($_POST["email"]));
elseif (empty($_POST["email"])):
echo "Merci décrire une adresse email <br />";
$email = "";
else:
echo "Email invalide :(<br />";
$email = "";
endif;
// CONDITIONS MESSAGE
if ( (isset($_POST["message"])) && (strlen(trim($_POST["message"])) > 0) ):
$message = stripslashes(strip_tags($_POST["message"]));
else:
echo "Merci décrire un message<br />";
$message = "";
endif;
$cap = 0;
$reCaptcha = new ReCaptcha($secret);
if(isset($_POST["g-recaptcha-response"]))
{
$resp = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
if ($resp != null && $resp->success)
{
$cap = 1;
}
else
{
echo "verify your CAPTCHA, it is incorrect <br />";
$cap = 0;
}
}
else
{
echo "ERROR captcha <br />";
$cap = 0;
}
// Les messages d"erreurs ci-dessus s'afficheront si Javascript est désactivé
// PREPARATION DES DONNEES
$ip = $_SERVER["REMOTE_ADDR"];
$hostname = gethostbyaddr($_SERVER["REMOTE_ADDR"]);
$destinataire = 'myEmail#gmail.com';
$objet = $sujet;
$contenu = "Nom de l'expéditeur : " . $nom . "\r\n";
$contenu .= $message . "\r\n\n";
$contenu .= "Adresse IP de l'expéditeur : " . $ip . "\r\n";
$contenu .= "DLSAM : " . $hostname;
$headers = "From: " . "contact#exemple.com" . " \r\n"; // ici l"expediteur du mail
$headers .= "Reply-to: " . $email . " \r\n"; // ici l"expediteur du mail
$headers .= 'Content-Type: text/plain; charset=ISO-8859-1; DelSp=Yes; format=flowed'. "\r\n";
$headers .= 'Content-Disposition: inline' . "\r\n";
$headers .= 'Content-Transfer-Encoding: 7bit' . "\r\n";
$headers .= 'MIME-Version: 1.0';
// SI LES CHAMPS SONT MAL REMPLIS
if ( (empty($nom)) && (empty($sujet)) && (empty($email)) && (!filter_var($email, FILTER_VALIDATE_EMAIL)) && (empty($message)) ):
echo "echec";
elseif ( $cap==0 ):
echo "captcha error <br />";
// ENCAPSULATION DES DONNEES
else:
mail($destinataire,$objet,utf8_decode($contenu),$headers);
echo "Formulaire envoyé";
unset($_POST);
unset($message);
unset($sujet);
unset($email);
unset($nom);
endif;
// Les messages d"erreurs ci-dessus s"afficheront si Javascript est désactivé
?>
What I want is:
To alert user who missed to check captcha exactly like I did to verify other field before submit. I want to verify all my form before submitting ( In frontEnd). and the code above check all field in frontEnd except of captcha.
How can I verify if captcha is checked or no in frontEnd.
Any info that allow me to keep coding.
I find the solution, if We want to verify reCaptcha before submitting we have to add this simple code in submit (It will allow us to know if the reCaptcha is cheked or no):
var msg_captch = " You need to check Captcha";
var captch = jQuery('#g-recaptcha-response').val();
if(!captch)
{
$("#msg_captch").html(msg_captch);
}
Please see the code above to know what is 'msg_captch'

Categories