I have built a Facebook app for a client, this app allows the user to enter their details and guess a figure to be entered into a competition. The app is run via an iframe.
Is there any possible way of only letting the user submit the form 5 times maximum within 24 hours (preferably by facebook profile or IP address), then echo an error if they try to enter a 6th time. I have a php script that gathers the data and exports it to a csv file.
PHP form code:
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['formName']))
{
$errorMessage .= "<li>You forgot to enter your name.</li>";
}
if(empty($_POST['formTown']))
{
$errorMessage .= "<li>You forgot to enter your town.</li>";
}
if(empty($_POST['formEmail']))
{
$errorMessage .= "<li>You forgot to enter your email.</li>";
}
$varName = $_POST['formName'];
$varTown = $_POST['formTown'];
$varAge = $_POST['formAge'];
$varEmail = $_POST['formEmail'];
$varOne = $_POST['hidden-one'];
$varTwo = $_POST['hidden-two'];
$varThree = $_POST['hidden-three'];
$varFour = $_POST['hidden-four'];
$varFive = $_POST['hidden-five'];
if(empty($errorMessage))
{
$fs = fopen("mydata.csv","a");
fwrite($fs,"\n" . $varName . ", " . $varTown . ", " . $varAge . ", " . $varEmail . ", " . $varOne . $varTwo . $varThree . $varFour . $varFive);
fclose($fs);
header("Location: thankyou.php");
exit;
}
}
?>
The obvious solution is to log form submits to a database. For each submit you log the time and an identifier for the user (IP address, Facebook account, etc). This data can be used to check how many times the user submitted the form in the last 24 hours. If this is more than X times, you do not store the data and inform the user.
But this solution assumes you have access to a database.
Related
I am doing a PHP assignment and am collecting information about a user and storing it in a file depending on if the user Subscribes or not. Disclaimer: I know it is better to do this stuff in a database and using mySQL, but we haven't learned it yet and are told to use PHP. I have radio buttons that determine whether to subscribe or unsubscribe. Here those are
<input type="radio" name="sub" value="subscribe" checked="checked" />
<input type="radio" name="sub" value="unsubscribe" />
I have the subscribed one to be checked by default. I get the result of the radio button in the variable $Action listed below. For some reason though, any time I try to "subscribe" I always get the die message, "Unable to create file!" and I am not sure why I am getting it. Here is my code below.
$Name = htmlspecialchars($_POST['name']);
$EmailAddress = htmlspecialchars($_POST['emailaddress']);
$Action = $_POST['sub'];
if($EmailAddress == "") {
print "<p>Error. No email address. Please try again.</p>";
$move = 0;
} else {
$move = 1;
}
if($move) {
// If the user subscribes, make a file for them.
if($Action == "subscribe") {
// Create a file for each user saved as their email address.
$myfile = fopen($_POST['emailaddress'] . ".txt", "w") or die("Unable to create file!");
$txt = "Name: " . $_POST['name'] . "\n"; // Add the name to the file
fwrite($myfile, $txt);
$txt = "Email Address: " . $_POST['emailaddress'] . "\n"; // Add the email address to the file
fwrite($myfile, $txt);
// Check which preferences are set. Add to file if they are checked.
if(isset($_POST['compositions'])) {
$txt = "Preference: " . $_POST['compositions'] . "\n"; // Add the first preference to the file if checked
fwrite($myfile, $txt);
}
if(isset($_POST['marchingband'])) {
$txt = "Preference: " . $_POST['marchingband'] . "\n"; // Add the second preference to the file if checked
}
if(isset($_POST['projects'])) {
$txt = "Preference: " . $_POST['projects'] . "\n"; // Add the third preference to the file if checked
}
if(isset($_POST['events'])) {
$txt = "Preference: " . $_POST['events'] . "\n"; // Add the fourth preference to the file is checked
}
fclose($myfile);
print "<p>Thank you for subscribing!</p>";
} else {
// If a user unsubscribes, delete their file.
unlink($_POST['emailaddress'] . ".txt");
print "<p>You have successfully unsubscribed.</p>";
}
}
Can anyone help me understand why I am getting the error message every time when I am filling out all the required fields like I am supposed to? Thanks.
I am trying to make a form for people to fill out that requests a service. They must for one of the fields enter a phone number. To ensure that the phone number is valid I have set up the PHP to send an SMS to the provided number using my providers API.
The sms sends okay and it sends with a PHP variable enclosed. (A Random int between 9999 and 99999.) This code is sent successfully but every submit the code changes as the function runs. The problem with this is that you receive the text but when you enter it in the code has already changed as you submitted the form to validate. I have tried using a button type in html but cant figure our how to run the PHP using it.
Below is the first form they fill out which sends the message.
<?php
$confirmcode = rand(9999, 99999);
//echo "<br/><br/><br/><br/><br/><br/>Confirmation Code:"."<br/><br/>$confirmcode<br/><br/><br/>";
if (isset($_POST['submit'])){
// Validation
//Check Name is non-blank
if( 0=== preg_match("/\S+/", $_POST['fname'])){
$errors['first_name'] = "Please enter your name.";
}
if (0=== preg_match("/^[\+0-9\-\(\)\s]{10,}+$/", $_POST['phone'])){
$errors['phone'] = "Please enter a phone number";
}
//Check Email has required symbols
if (0=== preg_match("/.+#.+\..+/", $_POST['email'])){
$errors ['email'] = "Please enter a valid email address.";
}
//End Validation
$errors = array();
$name = $_POST['fname'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$email = $_POST['email'];
//Sending Confirmation SMS code to confirm phone number.
// Declare the security credentials to use
$username = "############";
$password = "############";
// Set the attributes of the message to send
$message = "Hello " ."$name" ."Your confirmation code is: " ."$confirmcode".". " ."Please enter it .". "on he appraisal request form.";
$type = "1-way";
$senderid = "SanctuaryRE";
$to = $_POST['phone'];
// Build the URL to send the message to. Make sure the
// message text and Sender ID are URL encoded. You can
// use HTTP or HTTPS
$url = "http://api.directsms.com.au/s3/http/send_message?" .
"username=" . $username . "&" .
"password=" . $password . "&" .
"message=" . urlencode($message) . "&" .
"type=" . $type . "&" .
"senderid=" . urlencode($senderid) . "&" .
"to=" . $to;
// Send the request
$output = file($url);
// The response from the gateway is going to look like
// this:
// id: a4c5ad77ad6faf5aa55f66a
//
// In the event of an error, it will look like this:
// err: invalid login credentials
$result = explode(":", $output[0]);
//END SMS
header("Location: process.php");
}
?>
And the form they are pushed onto to confirm the code they were sent.
<html>
<div class="wrapper2">
<form action="" method="POST">
<input type="text" class="textfieldlong" placeholder="Confirmation Code" name="giventoken">
<input type="button" class="submit" value="Verify Phone Number" name="submit2" id="submit2">
</form>
</html>
<style>
.wrapper{
display:none;
}
</style>
</div>
<?php
include "index.php";
//$token = $_POST['giventoken'];
//if (!strcmp($confirmcode,$token)){
// echo "Match";
//}
echo "$confirmcode";
?>
The random int is generated right at the beginning. Please help! Thnx. :D
The random number is being created every time.
You will have to database the number for each specific user and then check when they enter the code. You cant expect the user to get the text and confirm immediately. The only real way to do this is to database it.
Setup a table with the userid and the code, then check when they confirm that you sent that code to that user.
I'm new to PHP and trying to create a form with all fields required, including one where a file must be selected. Here is what I would like to achieve:
user must complete 4 fields + upload a file
file can only be of a certain type + under a certain size
if user does not complete one of the requirements and clicks submit, the word "Required" appears next to the empty field
if selected file does not meet criteria, a different message appears
data is preserved in the fields that were filled in if the user left something blank and has to go back to fill it in.
when form submits, info goes into database + into an email
I am close but missing something. If I select a file that meets the requirements, the form submits even if the other fields are blank. As long as the form field is empty, the other fields behave correctly. What am I missing? I would appreciate any help. Thank you.
<?php require_once('../scripts/lcoa.php'); ?>
<?php
if (isset($_GET['jobid'])) {
$jobid = $_GET['jobid'];
}
if (isset($_GET['jobtitle'])) {
$jobtitle = $_GET['jobtitle'];
}
//This is the directory where resumes will be saved
$timestamp = time();
$folder = "../careers/resumes/";
$resume = ($_FILES['resume']['name']);
$target = $folder.basename($timestamp.$_FILES['resume']['name']);
$type = ($_FILES['resume']['type']);
$extension = strtolower(substr($resume, strpos($resume, '.') + 1));
$size = ($_FILES['resume']['size']);
$max_size = 3145728;
$name = ($_POST['name']);
$email = ($_POST['email']);
$phone = ($_POST['phone']);
$jobid = ($_POST['jobid']);
$jobtitle = ($_POST['jobtitle']);
$cover = ($_POST['coverletter']);
$error=array();
if(isset($name)){
if (empty ($name)){
$error['name']="<p class='error'>Required </p>";
}
}
if(isset($email)){
if (empty ($email)){
$error['email']="<p class='error'>Required </p>";
}
}
if(isset($phone)){
if (empty ($phone)){
$error['phone']="<p class='error'>Required </p>";
}
}
if(isset($cover)){
if (empty ($cover)){
$error['coverletter']="<p class='error'>Required </p>";
}
}
//Writes the resume to the server
if (isset ($resume)) {
if (empty ($resume)){
$error['resume']="<p class='error'>Resume Required </p>";
}
if (!empty ($resume)){
if(($extension=='doc'||$extension=='docx'||$extension=='txt'||$extension=='pdf')&&($type=='application/pdf'||'application/msword'||'application/vnd.openxmlformats-officedocument.wordprocessingml.document'||'text/plain')&&$size<=$max_size) {
if(move_uploaded_file($_FILES['resume']['tmp_name'], $target)) {
//Writes the information to the database
$insertSQL = "INSERT INTO applicants (id, name, email, phone, jobid, jobtitle, coverletter, resume) VALUES ('','".$_POST['name']."','".$_POST['email']."','".$_POST['phone']."','".$_POST['jobid']."','".$_POST['jobtitle']."','".$_POST['coverletter']."','".$resume."')";
mysql_select_db($database_lcoa, $lcoa);
$Result1 = mysql_query($insertSQL, $lcoa) or die(mysql_error());
//Sends Email
$sendto = "emailaddress";
$name = nl2br($_POST['name']);
$email = nl2br($_POST['email']);
$phone = nl2br($_POST['phone']);
$jobid = nl2br($_POST['jobid']);
$jobtitle = nl2br($_POST['jobtitle']);
$cover = nl2br($_POST['coverletter']);
$subject = "Submitted Job Application";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$headers = "From: " . strip_tags($email) . "\r\n";
$headers .= "Reply-To: ". strip_tags($email) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$msg = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<h2 style='font-weight:bold;border-bottom:1px dotted #ccc;'>Job Application Submitted</h2>\r\n";
$msg .= "<p><strong>Applied for:</strong> ".$jobtitle."</p>\r\n";
$msg .= "<p><strong>Job ID:</strong> ".$jobid."</p>\r\n";
$msg .= "<p><strong>Applicant Name:</strong> ".$name."</p>\r\n";
$msg .= "<p><strong>Email:</strong> ".$email."</p>\r\n";
$msg .= "<p><strong>Phone:</strong> ".$phone."</p>\r\n";
$msg .= "<p><strong>Cover Letter:</strong> ".$cover."</p>\r\n";
$msg .= "<a href='http://domain.com/".$target."'>Download Resume</a>\r\n";
$msg .= "</body></html>";
if(#mail($sendto, $subject, $msg, $headers)) {
echo "";
} else {
echo "false";
}
//Tells you if its all ok
echo "<div id='confirm-app'><p>Thank you for submitting your application. Resumes submitted will be reviewed to determine qualifications that match our hiring needs.<br /><br /> If you are selected you will be contacted by a member of our recruiting team.</p><br /><br /><a href='../careers/job-postings.php'>Return to current opportunities</a></div>";
}
}
else {
//Gives and error if its not
echo "<p style='color: #6D6E71; font-family: Arial,Helvetica,sans-serif; font-size: 13px;'>We accept resumes in <strong>.doc</strong>, <strong>.docx</strong>, <strong>.pdf</strong>, or <strong>.txt</strong> formats, 3MB or less. Please <a href='javascript:history.back(-1);'>go back</a> to upload a file that meets these requirements.<br /><br />If you continue to experience errors, please report them.</p>";
die();
}
}
}
?>
You have to add one more condition near if (!empty ($resume)) that checks your $error array empty if not empty then print the errors else insert or email etc
if (!empty ($resume) && empty($error)){
//do your stuff
}else{
//display errors
}
you are only testing to see if if (!empty ($resume)){ and the requirements for the file before you execute the database insert and email sending. you will have to test for other elements being correct as well. Since you are building an array called $error you can test to see if empty($error) before performing the database insert and email.
I'm having trouble creating a form that exports to a .CSV file in PHP. I created a fiddle for the HTML which is here:
http://jsfiddle.net/tqs6g/
I'm coding in PHP so I can't really show the full code on JSFiddle since it can't support the PHP but here's my PHP code:
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['brandname']))
{
$errorMessage .= "<li>Please enter a business/brand name.</li>";
}
if(empty($_POST['firstname']))
{
$errorMessage .= "<li>Please enter your first name.</li>";
}
$varBrand = $_POST['brandname'];
$varFName = $_POST['firstname'];
$varLName = $_POST['lastname'];
$varEmail = $_POST['email'];
$varSite = $_POST['website'];
if(empty($errorMessage))
{
$fs = fopen("mydata.csv","a");
fwrite($fs,$varBrand . ", " . $varFName . ", " . $varLName . ", " . $varEmail . ", " . $varSite . "\n");
fclose($fs);
exit;
}
}
?>
When I click Submit it successfully goes to 'thankyou.php' (which is set in the form action) but I can't figure out why it's not posting the correct error messages or filling in my 'mydata.csv' file upon click. Possibly it's a sight syntax error? Let me know if you need any more info, I know this is kind of confusing seeing as the PHP is separated from the Fiddle.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // better method to check for a POSt
... validation stuff ...
$data = array();
$data[] = $_POST['brandname'];
$data[] = $_POST['firstname'];
etc...
if (empty($errrorMessage)) {
$fs = fopen('mydata.csv', 'a') or die("Unable to open file for output");
fputcsv($fs, $data) or die("Unable to write to file");
fclose($fs);
exit();
} else {
echo $errormessage;
}
}
A few things of note:
1) using $_SERVER['REQUEST_METHOD'] to check for submit type is absolutely reliable - that value is always set, and will always be POST if a post is being performed. Checking for a particular form field (e.g. the submit button) is hacky and unreliable.
2) Using fputcsv() to write out to a csv file. PHP will do all the heavy work for you and you jus tprovide the function an array of data to write
3) Note the or die(...) constructs, which check for failures to open/write to the file. Assuming that a file is available/writeable is unreliable and will bite you at some point in the future. When dealing with "external" resources, always have error handling.
I am trying to create a web page using php. The problem is that sometimes I get server errors and sometime I get nothing in return at all. At one point the server changed the file type itself. I have NO idea what the problem can be.
And since I have actually no idea what the problem is I paste the entire file here, even though I expect that it's the first few rows that is the problem (I put it here: http://www.iandapp.com/smic/subscription.php) :
<?php header('Content-Type: text/html; charset=ISO-8859-1');
echo("<div id='subscribe'>");
$mail = $_POST['email1'];
//Set the locale format, etc. of date and time
date_default_timezone_set('Europe/Stockholm');
setlocale(LC_TIME, "sv_SV");
//Create the db-connection
$mysqli = mysqli_connect("mydb", "myuser", "mupsw", "myschema", "3306");
//If verifying the subscription, makse sure the db is updated accordingly
if($_GET['newid'] != ""){
//Make the subscriber a verified subscriber
$result = mysqli_query($mysqli,"UPDATE users SET subscriber = 1 WHERE id = " . $_GET['newid']);
if($result){
echo("<p>Welcome to our newsletter! We will send you information about any new application or update. This will not happen too often, but once it does we hope you will have the opportunity to look into our site again.<p/>");
echo("<p><br/>If you wish to unsubscribe from this mail-list, please visit out subscription page: http://" . $_SERVER['HTTP_HOST'] . "/subscription.php <p/>");
}else{
echo("<p>Somthing went wrong, please click the link again!<p/>");
}
}elseif($_POST['email1'] != ""){ //Only do things if there is an e-mail posted
//Make sure the ID is unique
do{
$rand_int = rand(100000000, 999999999);
$result = mysqli_query($mysqli, "SELECT id FROM users WHERE id = " . $rand_int);
$no_of_rows = mysqli_num_rows($result);
}while($no_of_rows != 0);
echo("RAND :".$rand_int);
//Create query for saving the new user e-mail
$query = "INSERT INTO users(id, email, first_name, surname) VALUES ('" . $rand_int . "', '".$_POST['email1']."', '". $_POST['first_name']."','".$_POST['surname']."')";
$re = mysqli_query($mysqli, $query);
echo("Result: ".$re);
//Check if mail already exist (Error code 1062 = dublicate entries for unique fields)
$existing = 0;
if(mysqli_errno($mysqli)==1062){
echo("It seems like your e-mail already is registered. Perhaps you have been a subscriber earlier? By clicking the link that you will receive in your mail box you subscribe to the newsletter again. ");
$existing = 1;
$result = mysqli_query($mysqli,"SELECT id FROM users WHERE email = '" . $_POST['email1'] . "'");
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$rand_int = $row['id'];
mysqli_query($mysqli,"UPDATE users SET waiting_for_unsubscribe = 0 WHERE email = '" . $_POST['email1'] . "'");
if(mysqli_errno($mysqli)){
echo("Error code " . mysqli_errno($mysqli) . "<br/>");
echo("Error text " . mysqli_errno($mysqli) . "<br/>");
}
//echo("ID------ " . $row['id'] . " ri---- " . $rand_int);
}
//Create the link for the user to verify the subscription
$url = "http://" . $_SERVER['HTTP_HOST'] . "/smic/subscription.php?newid=" . $rand_int;
$mymail = $_POST['email1'];
$esubject = "Please verify your subscription to iAndApp's newsletter ";
$body = "Click the link in order to verify your subscription (If you cannot click the link, just copy it and paste it into the adress field of your browser): " . $url;
$eemail = "NoReply#iandapp.com";
$sent = mail($mymail,$esubject,$body,"From: $eemailn");
if($sent){
if($existing != 1){
echo "<br/>An e-mail with a link has been sent to ". $mymail . ". Please click the link in order to verify your subscription";
}
}else{
echo "Something went wrong. Please try again and make sure you enter a correct e-mail adress.";
}
$existing = 0;
mysqli_free_result($result);
//If unsubscribing
}elseif($_POST['unsubscribedmail'] != ""){
//echo("Unsubscribe........");
//echo($_POST['unsubscribedmail']);
$result = mysqli_query($mysqli,"UPDATE users SET waiting_for_unsubscribe = 1 WHERE email = '" . $_POST['unsubscribedmail'] . "'");
//echo("Err code " . mysqli_errno($mysqli));
//echo("Err text " . mysqli_error($mysqli));
if(mysqli_errno($mysqli)){
echo("Error code " . mysqli_errno($mysqli) . "<br/>");
echo("Error text " . mysqli_errno($mysqli) . "<br/>");
}
$result = mysqli_query($mysqli,"SELECT id FROM users WHERE email = '" . $_POST['unsubscribedmail'] . "'");
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
//echo("ID------ " . $row['id']);
//Create the link for the user to verify that he/she unsubscribes
$url = "http://" . $_SERVER['HTTP_HOST'] . "/smic/subscription.php?unsubscribeid=" . $row['id'];
$mymail = $_POST['unsubscribedmail'];
$esubject = "Please verify that you want to unsubscribe from iAndApp's newsletter ";
$body = "Click the link in order to verify that you want to unsubscribe from iAndApp's newsletter (If you cannot click the link, just copy it and paste it into the adress field of your browser): " . $url;
$eemail = "NoReply#iandapp.com";
$sent = mail($mymail,$esubject,$body,"From: $eemailn");
if ($sent) echo "<br/>A mail with a link has been sent to ". $mymail . ". Please click the link in order to verify that you will unsubscribe from the newsletters.";
else echo "Something went wrong. Please try again and make sure you enter a correct e-mail adress.";
mysqli_free_result($result);
}elseif($_GET['unsubscribeid'] != ""){
$result = mysqli_query($mysqli,"UPDATE users SET subscriber = 0, waiting_for_unsubscribe = 0 WHERE id = " . $_GET['unsubscribeid']);
if($result){
echo("<p>You have now unsubscribed to the newsletter. Thank you for this time and we hope to see you again in the future. /iAndApp.<p/>");
}else{
echo("<p>Somthing went wrong, please click the link again!<p/> ".$result);
}
}else{
echo("<div class="subscribe">
<h4>Subscribe</h4>
<p>Subscribe to iAndApp's newsletter in order to get information about new and updated iPhone games and iPhone applications, that has been released by iAndApp. </p>
<form action="subscription.php" name="subscribe" method="post" onsubmit="return isValidEmailAndEqual()">
<p class="formlabel">Förnamn</p> <input type="text" name="first_name"/><br/>
<p class="formlabel">Efternamn</p> <input type="text" name="surname"/> <br/>
<p class="formlabel">E-mail</p> <input type="text" name="email1"/>
<br/>
<p class="formlabel">Repeat e-mail</p> <input type="text" name="email2"/> <br/>
<input class="inputsubmit" type="submit" value="Subscribe"/>
</form>
</div>");
echo("<div class="footer"></div>");
echo("<div class="subscribe">
<h4>Unsubscribe</h4>
<p>Fill in your e-mail address and submit in order to unsubscribe from iAndApp's newsletter. </p>
<form action="subscription.php" name="unsubscribe" method="post" onsubmit="return isValidEmail()">
<p class="formlabel">E-mail</p> <input type="text" name="unsubscribedmail"/><br/>
<input class="inputsubmit" name="submitbutton" type="submit" value="Unsubscribe"/>
</form>
</div>");
}
mysqli_close($mysqli);
echo("</div>");
?>
Of course, I don't expect you to go through and debug the entire application, but perhaps for the more expreienced folks out there, you know where to look.
I'm starting to get a bit stressed out here...
Please advice what the problem is and how I can solve it.
Thank you in advance!
eror in code:
echo("<div class="subscribe">
<h4>Subscribe</h4>
<p>Subscribe to i
in 1-st line you just close the string by 2-nd quote
you just need to correct code
You have to escape double quotes inside html tags or use single quotes. Right now, echo thinks it's closed after "<div class=". Use one of these:
echo "<div class=\"class\">";
or
echo '<div class="class">';
or
echo "<div class='class'>";
If you dont get any reposne from server (document is clear) or you have server errors but this is not all the time and sometimes script works fine it could be memory limit problem.
do{
$rand_int = rand(100000000, 999999999);
$result = mysqli_query($mysqli, "SELECT id FROM users WHERE id = " . $rand_int);
$no_of_rows = mysqli_num_rows($result);
}while($no_of_rows != 0);
This part of code dosn't look good for me, I suggest you to use auto_increment at id field in db (so id will be unique all the time)