PHP form requires to be submitted twice - php

I'm writing an application that allows users to upload reference letters for potential employees.
Every reference is sent an email containing a unique string at the end of the url. So, for example, an address would look similar to: www.mywebaddress?url=503241a20b5085_18720621.
To determine if the unique string is valid (i.e. exists in the database) I need to do a query search. However, when a reference attempts to access the URL he needs to answer a security question. So, I also need to check if the answer is valid, if he has previously uploaded, etc to determine what page to redirect him to.
But because of the query, my code requires the user to click "Submit" twice. This is really annoying, but I'm not sure how to fix it.
Here is a relevant excerpt of my code:
if ( isset ($_GET['url']) ) {
$query = "SELECT * FROM ref_info WHERE url='" . $_GET['url'] . "'";
$result = $db->execute($query);
if ( empty ($result) ) {
//error message
} else {
$url = $_GET['url'];
if ( $_SESSION['validated'] ) {
if ( $result[0]['uploaded'] ==1 ) {
$_SESSION['uploaded'] =true;
} else {
$_SESSION['uploaded'] =false;
}
include_once("process_upload.php");
} else {
if ( empty($result[0]['answer']) ) {
include_once("security.php");
} else {
include_once("security_check.php");
}
}
}
}
Is there anything I can do so that the form only needs to be submitted once?
Thanks in advance for any suggestions!!

if ( isset ($_GET['url']) ) {
$query = "SELECT * FROM ref_info WHERE url='" . $_GET['url'] . "'"; //that is really not secure. Take a look at mysql_real_escape_string or something like that in yor $db
$result = $db->execute($query);
if ( empty ($result) ) {
//error message
} else {
$url = $_GET['url'];
if (empty($result[0]['answer']) ) { // page is just opened,form is not yet submitted - ask sequrity question
include_once("security.php");
} else { //oh. Submit is done - let me check if it is Ok
include_once("security_check.php");
}
if ( $_SESSION['validated'] ) { //validation is Ok? Yeah. Answer is not posted yet, so validation fails and we do nothing. Just show a form with a question
if ( $result[0]['uploaded'] ==1 ) {
$_SESSION['uploaded'] =true;
} else {
$_SESSION['uploaded'] =false;
}
include_once("process_upload.php");
}
}
}

Related

Comparison of words from the database and output of the result

I need to check the words received from the database with the user's entered word and if there is a match, then output its value from the database, and if not, then output what the user entered.
The code below works fine if there is a match.
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta, ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace, $d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
}
}
}
}
I'm an amateur in PHP, just learning. And I can't figure out how to output $d_typeplace if no match is found.
I tried to add
else {
echo $d_typeplace;
}
, but I get an array of words from the user entered.
I will be grateful for any help. Also for any suggestions for improving this code.
---Addition---
I apologize for my English. This is a problem in the Russian language, I need to take into account the morphology. To do this, the database has a list of words and their analog, for example, X = Y. I get these words and compare what the user entered. If he entered X, then we output Y. If he led Z, which is not in the database, then we output Z.
Thus, we check $d_typeplace with $d_typeplace_raw and if there is a match, we output $d_typeplace_morf, which is equal to $d_typeplace_raw. And if not, then $d_typeplace (it contains the value that the user entered).
Oh, I'm sorry, I understand myself that I'm explaining stupidly)
I cannot quite understand what you are asking: you need to output the string entered by the user, but you can only print an array?
If this is the case, I think you parsed the string before, in order to therefore you need to do join again the values contained in the array.
Try with:
else {
echo implode(" ", $d_typeplace);
}
--- EDITED ---
Try with:
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta, ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
$found = false;
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace, $d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
$found = true;
break;
}
}
if (!$found) {
echo $d_typeplace;
}
}
}
But I think it would be more efficient, if you implemented the second code snippet written by #Luke.T
I'm presuming you were trying to add the else like this?
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta, ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace, $d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
} else {
echo $d_typeplace;
}
}
}
}
Which was outputting an array because the for loop was continuing, if you add a break like so...
echo $d_typeplace;
break;
It should stop outputting an array. Depending on your use case you could however perform similar functionality directly in your sql query using LIKE ...
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('
SELECT ego_slovoforma_v_predlozhnom_padezhe
FROM dEzpra_jet_cct_tip_mest_obrabotki
WHERE vozmozhnyi_variant_mesta LIKE %' . $d_typeplace . '%');
if ($typeplace_results) {
//Echo result
} else {
echo $d_typeplace;
}
}

vTiger Event Handler to check if record exists

I am working on vTiger 6.5 and I am trying to figure a way to see if a record exists in a custom module of mine. I want to check whether the 'policynumber' is new before saving, here is my code so far. For some reason it seems to act randomly depending on my module number chosen.
class isaHandler extends VTEventHandler {
function handleEvent($eventName, $entityData) {
global $adb;
$moduleName = $entityData->getModuleName();
if($moduleName=='isa'){
if($eventName == 'vtiger.entity.beforesave.modifiable') {
$isNew = $entityData->isNew('policynumber');
if ($isNew == false) {
echo "Duplicate policy number";
exit;
}
}
if($eventName == 'vtiger.entity.beforesave') {}}
if($eventName == 'vtiger.entity.beforesave.final') {
$price = $entityData->get('currentamount');
if($price > 20000){
echo "Please go back and enter less than 20000";
exit;
}
if($eventName == 'vtiger.entity.aftersave') {}
}
}
At the moment I am currently using an echo just to see the result. But later on I will perform more than this.
isNew()
Returns true if new record is being created, false otherwise.
More info is here
you should write a custom query to check policynumber already exist or not in your function:
if($eventName == 'vtiger.entity.beforesave.modifiable') {
global $adb;
$result = $adb->pquery("SELECT your-field-name FROM table_name WHERE policynumber=?", array($policynumbervalue));
if($result && $adb->num_rows($result)) {
echo "This policy number exist";
die();
}else{
// write your overwrite code
}
} //end if($eventName == 'vtiger.entity.beforesave.modifiable')
Update:
I am assuming there is field i.e. policynumber in your form, you enter some value in this field and submit the form. so you will get entered policy number value from this:
$policynumbervalue = $entityData->get('policynumber'); //this is vtiger standard way
if this does not work, you can simply use php global variable $_REQUEST['policynumber'] but I is not a good practice.
Hope this will help.
This is the update to my answer, I simply done an if statement on the number of rows displayed.
if($eventName == 'vtiger.entity.beforesave.modifiable') {
$policynumbervalue = $entityData->get('policynumber');
$sql = $adb->pquery("SELECT policynumber FROM vtiger_isa WHERE policynumber=?",array($policynumbervalue));
$nrows = $adb->num_rows($sql);
if($nrows > 0){
echo "<script type=\"text/javascript\">window.alert('ISA policy number already exists, you will be redirected to the updata module.');
window.location.href = '/vtigercrm/index.php?module=isa&view=List';</script>";
exit;
}

PHP/SQL syntax: passing variable to SQL query

I am getting tired trying to see what is wrong. I have two php. From the first I am sending a variable 'select1' (basically the id) to the second and than I want to update that record uploading a pdf file.
$id = "-1";
if (isset($_GET['select1'])) {
$id = mysql_real_escape_string($_GET['select1']);
}
if(isset($_POST['Submit'])) {
$my_upload->the_temp_file = $_FILES['upload']['tmp_name'];
$my_upload->the_file = $_FILES['upload']['name'];
$my_upload->http_error = $_FILES['upload']['error'];
if ($my_upload->upload()) { // new name is an additional filename information, use this to rename the uploaded file
mysql_query(sprintf("UPDATE sarcini1 SET file_name = '%s' WHERE id_sarcina = '%s'", $my_upload->file_copy, $id));
}
}
If I put a line with a valid id, like:
$id = 14;
it is working. What I am doing wrong? Thank you!
If you need to accept both post & get, then you should try something like the code below to retrieve the variable.
$var = 'select1';
if( isset( $_POST[$var] ) ) {
$id = $_POST[$var];
} else if( isset( $_GET[$var] ) ) {
$id = $_GET[$var];
} else {
$id = -1;
}
You are using both GET and POST at the same time. As far as I can see, this condition is not returning True
if (isset($_GET['select1']))
Edit: If you don't find any answer in above; maybe some more information/code can help getting to a solution.

PHP setcookie issue

After a user signs in and his password is verified, I need to store his username in a cookie. I tried to simply add setcookie() when the password is successfully verified in the section that looks like if ( $password_match == $user_login_password ) {... but for some reason it doesn't seem to be working. I can't set cookies when a user successfully logins with correct password/username. Is there some reason you can't setcookies from inside a function?
public function write($p) {
if ( $_POST['user_login_username'] )
$user_login_username = mysql_real_escape_string($_POST['user_login_username']);
if ( $_POST['user_login_password'] )
$password = mysql_real_escape_string($_POST['user_login_password']);
$password .= 'some_Salt';
$user_login_password = hash('sha256', $password);
} elseif ( $user_login_username && $user_login_password ) {
$q = "SELECT * FROM users WHERE username = '$user_login_username'";
$r = mysql_query($q);
if ( $r !== false && mysql_num_rows($r) > 0 ) {
while ( $a = mysql_fetch_assoc($r) ) {
$password_match = stripslashes($a['password']);
}
if ( $password_match == $user_login_password ) {
echo $this ->display_login('Correct!');
setcookie('user','some_username');
} else {
echo $this ->display_login('Wrong Password!');
}
} else {
echo $this ->display_login('That username does not exist.');
}
return;
} else {
return false;
}
}
I'd do this that way:
function mysetcookie($name, $value, $timestamp=null, $directory='/') {
return setcookie($name, $value, time()+$timestamp, $directory);
}
And I'd be using mysetcookie() instead of setcookie() :) And I'd consider reading this:
http://php.net/manual/en/function.setcookie.php
Ahh I got it. Protocol restriction with setcookie, I was trying to set it after the tags. Thanks to everyone who looked, I should have read the documentation better. Sorry!

Validating $_GET

How do i validate $_GET thats the number coming from correct source.
My url look like : index.php?page=items&catID=5
When users put something like 3 which is doesn't exist on catID. I want it to display error message.
$catID = intval($_GET["catID"]);
if($catID) {
$checkSQL = mysql_query("SELECT * FROM category WHERE category_type='2'");
while($checkROW = mysql_fetch_array($checkSQL)) {
$checkCAT != $checkROW["categoryID"];
echo "err msg";
}
This i can come up so far but it doesn't working as it fire error msg even in correct page.
Thank you
wallk makes a good point, there is a missing if. but if i read this correctly, wouldn't something along the lines of this be more what you are going for? Right now the line:
if($catID) {
is actually only checking if catID (or, catID from the $_GET) is non-zero (not false). My guess if you are looking to check if catID is the categoryID returned from SQL?
$catID = intval($_GET["catID"]);
checkcat($catID);
function checkcat($check_category) {
$checkSQL = mysql_query("SELECT * FROM category WHERE category_type='2'");
while($checkROW = mysql_fetch_array($checkSQL)) {
if ( $check_category != $checkROW["categoryID"] ) {
echo "err msg";
} else {
echo "not an error message";
}
}
}
Expounding on what you are looking for, how about something like this then?
$catID = ($_GET["catID");
if ( !is_numeric($catID) ) {
echo "Not a numeric category!"
} else {
$checkSQLQuery = "SELECT * FROM category WHERE categoryID = '{$catID}' AND category_type='2'"
$resultSQL = mysql_query($checkSQLQuery, $db);
/* NOTE!: Guessing on what your database resouce
pointer is - it isn't included in the origin snippet.
Although, the last opened should be used by default if
this is left out. */
if ( mysql_num_rows($resultSQL) < 1 ) {
echo "Error message, category ID not found"
} else {
echo "Found it!"
}
}
Oh, I see. The first line inside the while loop should have an "if":
while ($checkROW = mysql_fetch_array($checkSQL)) {
if ($checkCAT != $checkROW["categoryID"])
echo "err msg";
It looks like you'll be wanting to use mysql_fetch_assoc(), rather than mysql_fetch_array().

Categories