I am using ajax to resend the verification email to my user who registered on-site. The code is working fine on my chrome browser but not on firefox. In the Firefox networking tab, I can see it blocked my post request. How can I solve this issue, I am not getting any kind of errors, it's just not working.
Firefox networking tab screenshot.
And this is how I am using ajax, I can't use jQuery that's why I am using vanilla js method.
<!DOCTYPE html>
<head>
<title>Verification</title>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("email_send").addEventListener("click", function() {
function postAjax(url, data, success) {
var params = typeof data == 'string' ? data : Object.keys(data).map(
function(k){ return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) }
).join('&');
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open('POST', url);
xhr.onreadystatechange = function() {
if (xhr.readyState>3 && xhr.status==200) { success(xhr.responseText); }
};
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(params);
return xhr;
}
postAjax('send_verification.php', { }, function(data){
if (data === "verified"){
window.location ="login.php";
} else if (data === "sent"){
document.getElementById('mydiv').innerHTML = '<span class="prego">Sent Again...</span>';
}else if (data === "error"){
document.getElementById('mydiv').innerHTML = '<span class="prego">Unable Sent Again...</span>';
}
document.getElementById('mydiv').innerHTML = '<span class="prego">Just checking</span>';
console.log(data+" getting something");
});
});
</script>
</head>
<body>
<div class="text-center">
<img src="images/sucess.gif" alt="sucess">
<h4>A verification link have been sent to your email, Please flow instructions to activate your account.</h4>
<br>
<h4 class="text-center">Didn't get one? <a id="email_send" action="send_mail" href=""> click to resend.</a> </h4>
<div id="mydiv">
</div>
</div>
</body>
</html>
Also, I tried fetch() method for this, but fetch is also getting blocked for some reason.
This is the request I am making using ajax.
<?php
session_start();
include 'connection.php';
if(isset($_SESSION['email'])){
$email = $_SESSION['email'];
$email_check = $con->prepare("SELECT * FROM `user_reg` WHERE email =?");
$email_check->bind_param("s",$email_i);
$email_i = $email;
$email_check->execute();
$result = mysqli_stmt_get_result($email_check);
$email_count = mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
$token = bin2hex(random_bytes(25));
if ($email_count>0){
if($row['status']==="inactive"){
$insert_query = $con->prepare("UPDATE `user_reg` SET `token`=? WHERE `email`=?");
$insert_query->bind_param("ss", $token_i, $email_i);
$token_i = $token;
$email_i = $email;
$query = $insert_query->execute();
if ($query){
$username = $row['username'];
$url = "";
$subject = "Email verification";
include 'templates/email_con.php';
include 'templates/email_verifiy_tempate.php';
if (mail($email, $subject, $body, $headers)){
$_SESSION['msg']="Check your email for activation of your account";
echo "Email Sent...";
header('location:login.php');
}else{
echo "Email not sent, please check your email";
}
$insert_query->close();
}else{
echo "error";
}
}else{
$_SESSION['msg']="You are alredy verified, login to continue";
echo "verified";
}
}else{
echo "Email dosen't exists, please sign up";
}
}else {
header('location:login.php');
}
Related
Hello, I've recently been building a contact page for my html website and it seems to not send my message to my email at all!
It continues with ->
I am a little confused also why its not sending the message, and the default errors don't pop up with saying "this is required to be filled".
Here is my PHP code (sending the message) :
<?php
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$phone = htmlspecialchars($_POST['phone']);
$website = htmlspecialchars($_POST['website']);
$message = htmlspecialchars($_POST['message']);
if(!empty($email) && !empty($message)){
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
$receiver = "MYEMAILHERE";
$subject = "From: $name <$email>";
$body = "Name: $name\nEmail: $email\nPhone: $phone\nWebsite: $website\n\nMessage:\n$message\n\nRegards,\n$name";
$sender = "From: $email";
if(mail($receiver, $subject, $body, $sender)){
echo "Your message has been sent";
}else{
echo "Sorry, failed to send your message!";
}
}else{
echo "Enter a valid email address!";
}
}else{
echo "Email and message field is required!";
}
?>
Here is my JS code (creating the message) :
const form = document.querySelector("form"),
statusTxt = form.querySelector(".button-area span");
form.onsubmit = (e)=>{
e.preventDefault();
statusTxt.style.color = "#0D6EFD";
statusTxt.style.display = "block";
statusTxt.innerText = "Sending your message...";
form.classList.add("disabled");
let xhr = new XMLHttpRequest();
xhr.open("POST", "src/php/message.php", true);
xhr.onload = ()=>{
if(xhr.readyState == 4 && xhr.status == 200){
let response = xhr.response;
if(response.indexOf("required") != -1 || response.indexOf("valid") != -1 || response.indexOf("failed") != -1){
statusTxt.style.color = "red";
}else{
form.reset();
setTimeout(()=>{
statusTxt.style.display = "none";
}, 3000);
}
statusTxt.innerText = response;
form.classList.remove("disabled");
}
}
let formData = new FormData(form);
xhr.send(formData);
}
Here is my HTML code before end of my body (linking the js) :
<script src="src/js/contact.js"></script>
Is there anything i'm missing? Could it be not linking correctly? Im also sending this using an online website, not locally.
Using Githubpages, which does not support PHP. That is the problem.
I am having problems creating a PHP session following a successful AJAX call. Here is the AJAX code:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id = profile.getId();
var em = profile.getEmail();
var name = profile.getName();
var pic = profile.getImageUrl();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('confirm-login').style.display = 'block';
}
};
xhttp.open("GET", "./assets/inc/profile.php?id="+id+"&e="+em+"&n="+name+"&p="+pic, true);
xhttp.send();
}
This part works perfectly. I only include it for completeness sake.
Here's the contents of profile.php
<?php
$id = $_GET["id"];
$email = $_GET["e"];
$name = $_GET["n"];
$pic = $_GET["p"];
require_once("db.php");
$result = $mysqli->query("SELECT googleid FROM user_tbl WHERE googleid = '$id' LIMIT 1");
if($result->num_rows == 0) {
$sql = "INSERT INTO user_tbl (googleid, email, fullname, pic, loc) VALUES ('$id', '$email', '$name', '$pic', '')";
if (mysqli_query($mysqli, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . mysqli_error($mysqli);
}
} else {
echo "already exists";
}
$mysqli->close();
session_start();
$_SESSION['gid'] = $id;
?>
All of this code works except for session_start(); and $_SESSION['gid'] = $id; when I return to another PHP page (which correctly has session_start(); at the very top of the page) the variable has not been created in profile.php
Any help as to what I'm doing wrong would be much appreicated.
You can't start a session after the script has sent output. (There should have been output to that effect; if there wasn't, try changing PHP's warnings.) The session_start() call must come before any echo call that is actually executed.
On an unrelated topic, you will want to learn how to escape your database parameters.
directly to say I don't know JS clearly(so I don't understand any logic to store image in sql) ... I am just a learner[1st year CE student)... I learned backend though(sql,php) and I have to submit this project but I am stock.... I am completely unknown to store image directly to sql as I click 'continue' button.... all my friends are new to it and I don't have enough time to learn JS... There were many solution avilable but I don't understand any of them... please help me to maintain my code.... thanks
<?php include('server.php'); ?>
<!DOCTYPE html>
<html>
<head>
<title>HIMALAYA COLLEGE EXIBITION</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Tangerine">
</head>
<body>
<br>
<br>
<br>
<div class="capture">
<video id="video" width="400" height="300" title="capture your photo" autoplay></video>
<button id="snap" name="snap">Snap Photo</button>
<br>
<canvas id="canvas" width="400" height="300"></canvas>
<br><br>
Continue
</div>
<script>
// Grab elements, create settings, etc.
var video = document.getElementById('video');
// Get access to the camera!
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
// Not adding `{ audio: true }` since we only want video now
navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
video.src = window.URL.createObjectURL(stream);
video.play();
});
}
//setup
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var video = document.getElementById('video');
// Trigger photo take
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 400, 300);
});
</script>
<br>
</body>
</html>
So your script is already capable of taking snapshots from the video. Now you have to convert the canvas data to a blob and send it to your server through ajax. This is not especially difficult with modern browsers.
document.getElementById('snap').addEventListener('click', function() {
context.drawImage(video, 0, 0, 400, 300);
canvas.toBlob(function (blob) {
var req = new XMLHttpRequest();
req.open('POST', 'uploadimage.php');
req.onload = function () {
console.log('upload complete, server response:', req.response);
};
console.log('uploading snapshot...');
req.send(blob);
});
});
Open your console (F12) to see log messages. In production you’ll have to produce HTML feedback for the user.
The server part is a bit more complicated. First, create a PHP script named uploadimage.php. This script will retrieve uploaded file using the php://input stream.
As usual when dealing with user-submitted data, you need to perform some security checks. You want to verify that the uploaded file is an image type (see mime_content_type).
You also need to authenticate the user to not allow everyone (or any bot) to upload things to your server. I won’t tell you how to do it, it’s out of the scope of this topic.
Last thing, we need to choose a file name that won’t collide with an existing one. A good candidate is a string based on the current time (see microtime). You may also want to add a prefix related to the authenticated user.
(Edit: well, sorry, I forgot you wanted it stored in a database. Tell me if you manage to adapt this script. If not, I’ll write a more appropriate response.)
<?php
header('Content-Type: text/plain; charset=utf-8');
define('PREFIX', 'banana-');
$fd = fopen('php://input', 'rb');
$mimeType = mime_content_type($fd);
fclose($fd);
$matchResult = preg_match('#^image/(\w+)#', $mimeType, $matches);
if ($matchResult === false) {
header('HTTP/1.0 500 Internal Server Error');
echo "Couldn't parse MIME type";
}
else if ($matchResult === 0) {
header('HTTP/1.0 400 Bad Request');
echo "Wrong MIME type";
}
else {
$fileExt = $matches[1];
$fileName = PREFIX . number_format(microtime(true), 6, '-', '') . '.' . $fileExt;
$putResult = file_put_contents($fileName, file_get_contents('php://input'));
if ($putResult === false) {
header('HTTP/1.0 500 Internal Server Error');
echo "Couldn't write file";
}
else {
echo 'Ok';
}
}
Edit 2: Updating as I progress. The problem is more complex than I thought. It appears that we can’t use php://input when we want to mix the blob with other POST data – these will be required for authentication.
For now I have a functional backend script to receive and store the image, but without authentication.
<?php
header('Content-Type: text/plain; charset=utf-8');
ini_set('html_errors', '0');
function sendError($message, $code = 500) {
header("HTTP/1.0 $code");
die($message);
}
$fd = fopen('php://input', 'rb');
$mimeType = mime_content_type($fd);
fclose($fd);
$matchResult = preg_match('#^image/#', $mimeType);
if ($matchResult === false) {
sendError("Couldn't parse MIME type");
}
if ($matchResult === 0) {
sendError('Wrong MIME type', 400);
}
$mysqli = new mysqli('localhost:3306', 'root', '', 'registration');
if ($mysqli->connect_error) {
sendError($mysqli->connect_error);
}
$mysqli->set_charset('utf8mb4') or sendError($mysqli->error);
$username = 'Homer';
$contents = file_get_contents('php://input');
$query = 'INSERT INTO uploads (username, file) VALUES (?, ?)';
$stmt = $mysqli->prepare($query) or sendError($mysqli->error);
$stmt->bind_param('ss', $username, $contents) or sendError($stmt->error);
$stmt->execute() or sendError($stmt->error);
echo 'Ok';
Edit 3: Here we are. To upload mixed content via ajax, a FormData is of greater help. To receive it on the server side, do the classic way with $_FILES.
I eventually figured out that, in order to authenticate the user, the best way is to use the session. In fact you don’t even need additional request parameters, but let’s stick with the FormData solution, as you may want to send metadata and some security measures, e.g. a CSRF token.
Here’s the updated client script:
document.getElementById('snap').addEventListener('click', function() {
context.drawImage(video, 0, 0, 400, 300);
canvas.toBlob(function (blob) {
var formData = new FormData();
formData.append('snapshot', blob);
formData.append('image-description', 'MFW Im writing an answer on SO');
var req = new XMLHttpRequest();
req.open('POST', 'uploadimage.php');
req.onload = function () {
console.log('upload complete, server response:', req.response);
};
console.log('uploading snapshot...');
req.send(formData);
});
});
And the updated server script:
<?php
header('Content-Type: text/plain; charset=utf-8');
ini_set('html_errors', '0');
function sendError($message, $code = 500) {
header("HTTP/1.0 $code");
die($message);
}
session_start();
if (!isset($_SESSION['username'])) sendError('Please log in', 401);
if (!isset($_FILES['snapshot'])) sendError('Missing file', 400);
$fd = fopen($_FILES['snapshot']['tmp_name'], 'rb');
$mimeType = mime_content_type($fd);
fclose($fd);
$matchResult = preg_match('#^image/#', $mimeType);
if ($matchResult === false) {
sendError("Couldn't parse MIME type");
}
if ($matchResult === 0) {
sendError('Wrong MIME type', 400);
}
$mysqli = new mysqli('localhost:3306', 'root', '', 'registration');
if ($mysqli->connect_error) {
sendError($mysqli->connect_error);
}
$mysqli->set_charset('utf8mb4') or sendError($mysqli->error);
$username = $_SESSION['username'];
$contents = file_get_contents($_FILES['snapshot']['tmp_name']);
$query = 'INSERT INTO uploads (username, file) VALUES (?, ?)';
$stmt = $mysqli->prepare($query) or sendError($mysqli->error);
$stmt->bind_param('ss', $username, $contents) or sendError($stmt->error);
$stmt->execute() or sendError($stmt->error);
echo 'Ok';
A note about HTTP codes: I tried to respond with somehow meaningful codes like REST API endpoints do. But I think HTTP codes are a matter of personal opinion, and I don’t claim I chose the more appropriate ones. Feel free to change them, or not to use them at all.
https://stackoverflow.com/users/2221034/watilin
in mysql......database name-registration ..... table-name:users....column:username,batch,password_1,password_2,image(blob)....
I am using apache as server(XAMPP) and all pages(registration.php,login.php) are connected to server.php shown bellow
<?php
session_start();
$username = "";
$errors = array();
/*if( ! empty( $_POST )) {
print_r($_POST);}*/
//connect to the database
$db = mysqli_connect('localhost:3306', 'root', '', 'registration');
/*if($db->connect_error){
echo'sorry';
}*/
//if register button is clicked
//link with the register
if(isset($_POST['register'])){
$username = $_POST['username'];
$batch = $_POST['batch'];
$password_1 = $_POST['password_1'];
$password_2 = $_POST['password_2'];
//ensure that the form are filled properly
if(empty($username)){
array_push($errors,"Username is required!!!");
}
if(empty($batch)){
array_push($errors,"Batch is required!!!");
}
if(empty($password_1)){
array_push($errors,"Password is required!!!");
}
if($password_1 != $password_2)
{
array_push($errors,"password do not match!!!");
}
//if no error save user to database
if (count($errors)==0)
{
$password = md5($password_1);//encrypt password before storing in database(security)
//$sql = "INSERT INTO users (username,batch,password) VALUES ('$username', '$batch', '$password')";
mysqli_query($db,"INSERT INTO users (username, batch, password_1, password_2) VALUES ('$username', '$batch', '$password','$password')");
$_SESSION['username'] = $username;
$_SESSION['success'] = "you are now registered ^_^";
header('location: index.php'); //redirect to home page
}
}
//log user in from login page
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password_1'];
//ensure that the forms are filled properly
if(empty($username)) {
array_push($errors, "Username is required");
}
if(empty($password))
{
array_push($errors, "Password is required");
}
if(count($errors) == 0) {
$password = md5($password);//encrypting password
$query = "SELECT * FROM users WHERE username='$username' AND password_1='$password'";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) == 1) {
//log user in
$_SESSION['username'] = $username;
$_SESSION['success'] = "you are now logged in ^_^";
header('location: index2.php');//redirecting to home page
}
else{
array_push($errors,"wrong username or password");
}
}
}
?>
I am attempting to send a webhook to my discord server when data is inserted into the table, however the function is not being called... Currently it just echos "sendlog()" as shown here: http://prntscr.com/cxqgk5
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
$token = $_POST["token"];
$type = $_POST["type"];
$pid = $_POST["pid"];
$sid = $_POST["sid"];
$gid = $_POST["gid"];
$name = $_POST["name"];
$players = $_POST["players"];
$max = $_POST["max"];
$cdesc = $_POST["cdesc"];
$sus = $_POST["sus"];
if($token == 'DS_443'){
$con = mysqli_connect("localhost","**","**","**");
if(mysqli_connect_errno()){
echo(mysqli_connect_error());
}
if($type == 'edit' and $players !=NULL and $sid !=NULL){
$con->query("UPDATE OnlineServers SET ServerCurrent='$players' WHERE ServerID='$sid'");
} elseif($type == 'remove' and $sid !=NULL){
$con->query("DELETE FROM OnlineServers WHERE ServerID='$sid'");
} elseif($type == 'add' and $sid !=NULL and $gid !=NULL and $name!=NULL and $players !=NULL){
$con->query("INSERT INTO OnlineServers (GameId,GameName,GameMax,ServerCurrent,ServerID,Command) VALUES ('$gid','$name','$max','$players','$sid','TEST')");
?>
sendLog();
<?php
} elseif($type == 'call'){
$con->query("INSERT INTO Calls (Caller,CallerID,CallID,CallDesc,Suspect,SuspectID,ServerID,GameID) VALUES ('$pid','$name','$cdesc','$sus')");
}
} else {
?>
sendLog();
<?php
}
?>
<script>
function sendLog(){
var hookurl = "webhookurl"
let tosend = {
'Server added;',
'Game Name: ',
'Game ID: ',
'Server ID: ',
},
var msgJson = {
"attachments": [
{
"color": "#CC09EF",
"text": tosend,
"footer": "Infius Game Logs",
"footer_icon": "http://deersystems.net/assets/images/nfius.png",
}
]
}
post(hookurl, msgJson);
}
</script>
<script>
function post(url, jsonmsg){
xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
var data = JSON.stringify(jsonmsg);
xhr.send(data);
xhr.onreadystatechange = function() {
if(this.status != 200){
alert("ttt");
}
}
}
</script>
</body>
java script function should be wrapped inside script tags
<script type="text/javascript">
sendLog();
</script>
OR
<?php
echo '<script type="text/javascript">',
'sendLog();',
'</script>'
;
?>
You have output sendLog(); whithout script tag so, it will be consider normal text. If you want to call that function then you need it between script tag.
Also, you should have clean formatting of code. And avoid multiple script tag on same pages. add all js code in single script tag.
I am using the jQuery Form Post plugin from malsup, with the following code:
//Post a form
function PostForm(FormID, Target) {
var $t = Math.round(new Date().getTime() / 1000);
try{
var options = {
target: Target,
beforeSubmit: function () {
jQuery(Target).html('<div id="frmLoadingImageWrapper"><img src="/assets/images/ajax-loader.gif" alt="loading..." height="11" width="16" /></div>');
jQuery(Target).slideDown('slow');
},
success: function (html) {
setTimeout(function () {
jQuery(Target).html(html);
jQuery(FormID)[0].reset();
if($('#captcha-gen').length){
$.get('/inc/captcha.php?_=' + $t, function(data){
$('#captcha-gen').html(data);
});
}
}, 100);
},
error: function(e){
var $html = e.responseText;
jQuery(Target).html($html);
jQuery(Target).slideDown('fast');
if($('#captcha-gen').length){
$.get('/inc/captcha.php?_=' + $t, function(data){
$('#captcha-gen').html(data);
});
}
setTimeout(function() {
jQuery(Target).slideUp('fast');
}, 3500);
}
};
jQuery(FormID).ajaxSubmit(options);
}catch(err){
alert(err.message);
}
}
When I submit my form to /inc/mail.php the actuall PHP code shows in my Target instead of getting processed.
How can I fix this issue? All other PHP scripts work as they should, including other ajax pulled php scripts.
Here is the mailer code, it's using PHP SMTP
<?
require("/inc/class.phpmailer.php");
//form validation vars
$formok = true;
$errors = array();
//sumbission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('m/d/Y');
$time = date('H:i:s');
//form data
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$captcha = $_POST['secAnswer'];
$valid = true;
if(!is_string($email) || !(strlen($email)>0) || !ValidateEmail($email)){
$valid = false;
}
if(!is_string($name) || !(strlen($name)>0) || !ValidateText($name)){
$valid = false;
}
if(!is_string($message) || !(strlen($message)>0) || !ValidateText($message)){
$valid = false;
}
if(!CheckCAPTCHA($captcha)){
$valid = false;
}
sleep(1.5);
if($valid){
$mail = new PHPMailer();
$mail->IsMail(); // send via SMTP
$mail->From = $email; // SMTP username again
$mail->AddAddress("kevin#pirnie.us"); // Your Adress
$mail->Subject = "New mail your site!";
$mail->IsHTML(true);
$mail->CharSet = 'UTF-8';
$mail->Body = "<p>You have recieved a new message from the enquiries form on your website.</p>
<p><strong>Name: </strong> {$name} </p>
<p><strong>Email Address: </strong> {$email} </p>
<p><strong>Phone: </strong> {$phone} </p>
<p><strong>Message: </strong> {$message} </p>
<p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p>";
if(!$mail->Send())
{
echo "Mail Not Sent <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Mail Sent";
}else{
echo "Mail Not Sent. Please make sure all fields are filled out correctly.";
}
function ValidateEmail($str){
$atIndex = strrpos($str, "#");
if (is_bool($atIndex) && !$atIndex){
return false;
}else{
if (filter_var($str, FILTER_VALIDATE_EMAIL)) {
$domain = substr($str, $atIndex + 1);
return (checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"));
}else{
return false;
}
}
}
function ValidateText($str){
return (bool)preg_match("/^[a-zA-Z0-9 _-]+$/", $str);
}
function CheckCAPTCHA($str){
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/captcha.class.php');
$csc = new ResponsiveCaptcha();
if($csc->checkAnswer($str)){
return TRUE;
}else{
return FALSE;
}
}
Make sure that your server supports the short PHP open tag <?
If not : change the short_open_tag value in your php.ini file
or use <?php