PHP get value from url and pass it to text field - php

Hi I am a jsf programmer and want to integrate a documents repositary developed using php in my jsf application. So what i am doing is when the user clicks a link from my jsf screen it gets a value for the link pass it to the php url and opens a page where the user can add docs.
I am getting the value from url and displaying it in the page. But what i want is instead of user entering the *number field(please look at the screen shot) the value from URL should pass automatically to the database as number and the number field should be removed . Please look at screen shots.
and the code snippets
<td class="ThRows">*Number</td>
$cellvalue = "";
if ((!isset($_GET["add_fd9"])) && (!isset($_POST["add_fd9"]))) {
$itemvalue = "";
} else {
$itemvalue = qsrequest($_GET["add_fd9");
then
fieldPrompts[_No] = "*Number";
pgitm_No= document.getElementsByName("add_fd9")[0];
I dont understand where to pass the url value

Try it :
$cellvalue = "";
if (!isset($_REQUEST["add_fd9"])) {
$itemvalue = "";
} else {
$itemvalue = qsrequest($_REQUEST["add_fd9"]);
}

Use
$_REQUEST
as
<input type="text" name="text1" value="<?php echo isset($_REQUEST['add_fd9'])?$_REQUEST['add_fd9']:'';?>">

Related

How can I require a captcha to load a page?

I would like a simple PHP captcha script that would require the user so solve a captcha to load the website page. Preferably a captcha that doesn't need a third party such as reCAPTCHA, all done locally.
EDIT: Ended up making a text box to enter the link you would like to protect and it would automatically generate a captcha protected link, and a deletion link to delete the protected link.
You can look at the example here:
https://code.tutsplus.com/tutorials/build-your-own-captcha-and-contact-form-in-php--net-5362
I would also recommend using the timer on your page since bots are becoming better at passing capchas. By timer, I mean time between landing on the page and creating an account/submitting the form.
This is VERY simple. Usually no one is going to put any effort to bypass the captcha unless you have something worth while aka $$$$.
Just post an image with a question. Like What is 345 x 100,000 + 957?
The have an small form with a <input> for them to answer.
You could have any number of images and answers.
$captcha[] = array($answer,$image);
$captcha[] = array($answer,$image);
$captcha[] = array($answer,$image);
Then
$cnt = count($captcha) - 1;
$rec = rand(0,$cnt);
$answer= captcha[$rec][0];
$image = captcha[$rec][1];
echo '<img scr="$image"/>';
echo '<form action="$url" method="post">';
echo '<input type = "text" name="answer" /></form>';
$id = intval(str_replace('.','',$_SERVER['REMOTE_ADDR']));
file_put_contents("$id.txt",$answer);
The in the $url page:
$id = intval(str_replace('.','',$_SERVER['REMOTE_ADDR']));
$answer = intval(file_get_contents("$id.txt"));
unlink("$id.txt");
$pass = false;
if $answer == intval($_POST['answer']){$pass = true;}

Constant Variables in PHP after page reloads

im very new to PHP, so please excuse me if this is a stupid question.
So here is the scenario.
Im writing a PHP all in one page that gets a random word from an array, scrambles the word, then lets the user guess the word.
now im using the isset(), so it declares the variable, then once submit is clicked, it will get in user input via _POST().
Now the problem
I need the calculated variable to remain constant, but once the page reloads, it regenerates the variable.
is there anyway i can get pass this?
<?php
function GetShuffWord()
{
$arrayName = array('word1','word2','word3','word4','word5');
$randWordIndex = rand(0,4);
$randomWord = $arrayName[$randWordIndex];
$shuffledWord = str_shuffle($randomWord);
return $shuffledWord;
}
if(!isset($_POST['Submit']))
{
define("shuffledWord", GetShuffWord());
$tempWord = shuffledWord;
// showing the user shuffled word
echo " <h1 style='font-size: 50px' align = 'center'> {$tempWord}
</h1>";
}
else
{
$tempWord = shuffledWord;
echo " <h1 style='font-size: 50px' align = 'center'>{$tempWord} </h1>";
echo "else part";
}
?>
another problem is that if i declare the variable in the if, i cannot use variable in the else with out re-generating it.
You can just include the value as a hidden input field in your form.
<input type="hidden" name="myCalculatedValue" value="<?= $tempWord ?>" />
Then when the form is submitted you can just get it via $_POST['myCalculatedValue']
You can use session and put a check that if session has it already dont overwrite.
And when u want to overwrite you can do so as well by passing another flag to the script in your post request.

How to call upon a PHP function on button click?

I am trying to setup a website that converts a Steam user ID into an auth ID. It will ask for the visitor to input their regular Steam ID and then hit a button to convert it to auth ID. Steam provides us with the function for ID conversion from one type to the other.
Steam function for converting IDs:
function convert_steamid_to_accountid($steamid)
{
$toks = explode(":", $steamid);
$odd = (int)$toks[1];
$halfAID = (int)$toks[2];
$authid = ($halfAID*2) + $odd;
echo $authid;
}
Below is my attempt at setting up a basic HTML page that gets user input and then uses the function to convert that input to something else.
<INPUT TYPE = "Text" VALUE ="ENTER STEAM:ID" NAME = "idform">
<?PHP
$_POST['idform'];
$steamid = $_POST['idform'];
?>
Also, this is what the default Steam user ID looks like:
STEAM_0:1:36716545
Thank you for all the help!
If you can make it into two seperate files, then do so.
foo.html
<form method="POST" action="foo.php">
<input type="text" value="ENTER STEAM:ID" name="idform" />
<input type="submit" />
</form>
foo.php
<?php
function convert_steamid_to_accountid($steamid)
{
$toks = explode(":", $steamid);
$odd = (int)$toks[1];
$halfAID = (int)$toks[2];
$authid = ($halfAID*2) + $odd;
echo $authid;
}
$id = $_POST['idform'];
convert_steamid_to_accountid($id)
?>
if you don't have an option of making two seperate files, you can add the php code to 'foo.html' file and make the form to submit to the same file. However if you do this, check if the file is getting requested the first time, or it is requested because the form is submitted, BEFORE you call convert_steamid_to_accountid() function.
You can do this by:
if ($_SERVER['REQUEST_METHOD']=='POST'){
// your php code here that should be executed when the form is submitted.
}

checkbox status "checked" by default problem

I have a page with search form on it and table with search results below. In search form i have checkbox "Search in this category". What i'm doing to check it by default :
if(!isset($_SESSION['inthiscat'])){
$_SESSION['inthiscat'] = 'on' ;
$checked = 'checked';
}
$_GET['inthiscat'] = $_SESSION['inthiscat'];
checkbox code : INPUT type="checkbox" name="inthiscat"<?=$checked?>.
Link to next page of results index.php?inthiscat=$_GET['inthiscat'].
So the problem is when i uncheck "Search in this category" its still checked when i going to next page of results. How to fix it and what i'm doing wrong? Session startet of course.
Firstly, do you really need SESSION variables for this? If you want box to be checked when GET parameter is not specified, you do not need SESSIONs at all.
Assuming you want to preserve the behaviour in case someone removes the GET parameter:
<?php
session_start();
//......
//......
$checked='checked';
if(isset($_REQUEST['inthiscat'])) {
// Form input and url GET parameters take precedence
if($_REQUEST['inthiscat'] != 'checked') { $checked = ''; };
} else if(isset($_SESSION['inthiscat'])) {
// Next, use session variable if it exists
if($_SESSION['inthiscat'] != 'checked') { $checked = ''; };
};
$_SESSION['inthiscat']=$checked;
?>
Note:
1) Assigning values to GET array is not a good practice.
2) I assume you are using correct syntax for your FORM submit.
3) IMO, you could remove the SESSION variable as you are explicitly passing as GET parameter in the subsequent urls. Or dont use the GET parameter in urls.
Problem is: when you uncheck the checkbox and go to the next page, $_SESSION['inthiscat'] will still be unset - where did you change it?
Here is the code:
if (isset($_GET['inthiscat'])) {
$_SESSION['inthiscat'] = $_GET['inthiscat'];
}
if (!isset($_SESSION['inthiscat'])) {
$checked = 'checked';
} else {
if ($_SESSION['inthiscat'] == 'on') {
$checked = 'checked';
} else {
$cheked = '';
}
}
Assuming this HTML: <INPUT type="checkbox" name="inthiscat" checked="<?=$checked?>" value="on" />
So what it does is:
Looks for the GET data and, if there is, assigns it (can be 'on' or '') to the SESSION;
If there is no SESSION (that means, no GET as well) it's the first page of that kind the user visits, so checked;
If there is a SESSION for inthiscat, it means it's not the first page and GET data has been assigned to the SESSION. So, if it's on, it displays the mark; else, it does not.

Prevent duplicate record insert on manual page refresh

I have a problem which has only just surfaced itself.
I'm working in a MVC environment. The method names in my interface class match those of the request module and action i.e. ?module=test&action=action would result in a method called public function test_action() { }
In this particular problem, I have a form which submits to itself. If validation passes, a record is created and I then show the template of another module. This module expects a series of post variables as it is used in two modules.
The problem I'm having is that, if the user successfully passes the validation and attempts to F5 the page, another new record is created etc.
How can I prevent this from happening?
Normally I would header redirect after a successful insert but in this instance I can't.
I would take it a complete other way. I even find redirection an incorrect way of handling this, since changing locations is not meant to overcome logic/form troubles.
The correct solution is:
Add a unique hash to your form in a hidden input
Store the hash in a server-side session
When the form is send, validate the hidden input hash with the hash on your server
Only execute row insertion when the form validates correctly.
If you are working with Zend Framework, there is a Zend_Form_Element_Hash class for you.
Developer error:
You need to create a handler page which:
validating sent data
insert row
redirect user
You can / should re-direct to a new page after successful insertion.
As you are working in MVC, you can add a new controller that just calls the view you want to show.
Here is what I do it. This is working for me. Hope it can help anyone else.
//+++ start token +++
//This is to prevent duplicate entry on page reload (F5). 19. If I enter all values, press Record in journal and then press F5, the same values are recorded one more time. Need to prevent
// 3rd. $token_hash_from_input get value of input field name name="' .$_SESSION['token_hash'] .'"
$token_hash_from_input = $_SESSION['token_hash'];
//echo $token_hash_from_input .' token_hash_from_input<br>';
//echo $_POST[$token_hash_from_input] .' $_POST[$token_hash_from_input]<br>';
//var_dump($token_hash, $_POST);
// 4th. $_SESSION['token'] created/set in 1st. Then it as if goes around (at first to input field then after page reload returns here). However $_POST[$token_hash_from_input] is value received directly from input field. User click post and input field value is passed to $_POST[$token_hash_from_input]. Here I compare both.
if ( $_SESSION['token'] != htmlspecialchars($_POST[$token_hash_from_input]) ) {
$token_error .= 'yes';
//echo 'session token and token from input field are not the same <br> ';
}
else {
//echo 'session token is equal to post$token_hash)<br>';
}
// 1st. Create token and pass it to session
$token = sha1(uniqid(mt_rand(), true));
$_SESSION['token'] = $token;
//echo $_SESSION['token'] .' new $_SESSION[token]<br>';//after each page reload new token created. Then this token passed to input form (hidden field). value="' .$_SESSION['token'] .'"
// 2nd. Create token_hash and pass it to session. Token hash is to name input fields name and id. I may not use $token_hash and $_SESSION['token_hash']. Instead of this I can use name="token" and id="token".
$token_hash = sha1(uniqid($time_when_form_submitted .'token' .$_SERVER["REMOTE_ADDR"]));
//echo $token_hash .' $token_hash<br>';
$_SESSION['token_hash'] = $token_hash;
//echo $_SESSION['token_hash'] .' new SESSION$token_hash<br>';
// +++ end token +++
Input field like this
<input type="hidden" name="' .$_SESSION['token_hash'] .'" id="' .$_SESSION['token_hash'] .'" value="' .$_SESSION['token'] .'">
or
<input type="hidden" name="<?php echo $_SESSION['token_hash'] ?>" id="<?php echo $_SESSION['token_hash'] ?>" value="<?php echo $_SESSION['token'] ?>">
I suppose code can be improved (I have no good knowledge php etc)
"Normally I would header redirect after a successful insert but in this instance I can't."
are you facing some error in doing that?
If for whatever reason you can't redirect (Which sounds peculiar) you can use the 'same'
mechanism used for data validation to flush the forms after a successful insert.
But that's a really ugly way to go.
One of most common issue which many of the web developers face in their web applications, is that the duplicate records are inserted to the Database on page refresh. If the web page contains some text box and a button to submit the textbox data to the database. In that case when the user insert some data to the textbox and click on the submit button, it will save the record to the Database and then if the user refresh the web page immediately then the same record is again saved to the database as there is no unique keys that can be used to verify the existence of the data, so as to prevent the multiple insertion.
From this behavior we can definitely know that, on the page fresh the button click event is fired.
To avoid this problem we can try this method as discuss below.
On page load event save the date/time stamp in a session variable, when the page is first loaded, a Session variable is populated with the current date/time as follows:
*void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
}*
On the page's PreRender event, a ViewState variable is set to the value of the Session variable as follows:
void Page_PreRender(object obj,EventArgs e)
{
ViewState["update"] = Session["update"];
}
Then these two values are compared to each other immediately before the database INSERT command is run.
If they are equal, then the command is permitted to execute and the Session variable is updated with the current date/time, otherwise the command is bypassed as given below:
void btnSubmit_Click(object obj, EventArgs e)
{
string name = "";
string qualification = "";
if (Session["update"].ToString() == ViewState["update"].ToString())
{
if (txtName.Text != "" || txtName.Text != null)
{
name = txtName.Text.ToString();
}
if (txtQualification.Text != "" || txtQualification.Text != null)
{
qualification = txtQualification.Text.ToString();
}
//--- Insert data function should be execute here
string strSql = "INSERT INTO Testdata (Name,Qualification) VALUES ('" + name + "','" + qualification + "')";
SqlConnection ANConnection = new SqlConnection(ConnectionString);
ANConnection.Open();
SqlCommand ANCommand = new SqlCommand(strSql, ANConnection);
ANCommand.ExecuteNonQuery();
ANConnection.Close();
ANConnection.Dispose();
//--End of save data
lblMessage.Text = "Inserted Record Sucessfully
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
else
{
lblMessage.Text = "Failure – Due to Page Refresh";
txtName.Text = "";
txtQualification.Text = "";
}
}

Categories