i'm building a form + form validation class , and i also wanted to add captcha to this.
The captcha image is showing, however it itsn't storing anything in the $_SESSION.
I am using this captcha script:
https://github.com/gesf/captcha.class.php
Now in my controller i use this :
$data['regform']->addfield('user_captcha', 'Human verification', 'captcha', 'captcha' );
And that generates the following :
<label>
<span>Human verification</span>
<img name="user_captcha" src="http://www.websiteurl.com/dev/misc/captcha.php?c=1"><input type="text" name="user_captcha" value="" />
</label>
The image is showing like it should. However i'm not able to validate the input because it's not writing to the session. Now in the image file captcha.php it loads the class Captcha , and in this class constructor it tries to write to the session :
function Captcha($letter = '', $case = 5) {
$this->_capCase = $case;
if (empty($letter)) {
$this->StringGen();
} else {
$this->_capLength = strlen($letter);
$this->_capString = substr($letter, 0, $this->_capLength);
}
#session_start();
$_SESSION['asd'] = 'asd';
$_SESSION["CAPTCHA_HASH"] = sha1($this->_capString);
$this->SendHeader();
$this->MakeCaptcha();
}
My session always stays empty. But when i try the following :
<?php $_SESSION['bleh'] = 'asd'?>
<?php echo $form; ?>
It adds 'bleh' to the session like it should.
I really can't see why it won't write to the session..
could someone help me out ??
Thanks!!
Make sure, that session_start() is called before any output for every single page. As I can see, you are using # operator, that shuts up some errors. Can you remove it and tell us what does it output?
Also, your sessiaon_start() call is somewhere in the middle of the script. Perhaps there are some other output before that.
Related
I am making a website in CodeIgniter and for one of these pages I need to insert information into a database, however every time I enter information into my form and submit it, the page refreshes like it had been submitted but nothing enters the database.
Controller:
public function insertjob()
{
$this->load->helper('form');
$data['title']="Add a new job";
$this->load->view("insertjob", $data);
}
public function addingjob()
{
$jobtype=$this->input->post('jobtype');
$jobinfo=$this->input->post('jobinfo');
$this->load->model("cmodel");
if($this->cmodel->addjob($jobtype, $jobinfo)){
$data['msg']="New job addition successful";
}else{
$data['msg']="There was an error please try again";
}
$this->load->view("confirmation",$data);
Model:
function addjob($jobtype,$jobinfo)
{
$newjob=array("jobtype"=>$jobtype,"jobinfo"=>$jobinfo);
return $this->db->insert('clientjobs', $newjob); exit;
View:
</p>
<?php
echo form_open('client/insertjob');
echo form_label('Job:', 'Job');
echo form_input('jobtype');
echo form_label('Job information:', 'Job information');
echo form_input('jobinfo');
echo form_submit('Add job', 'Submit Post!');
echo form_close();
?>
Try removing the exit from your model:
function addjob($jobtype,$jobinfo)
{
$newjob=array("jobtype"=>$jobtype,"jobinfo"=>$jobinfo);
return $this->db->insert('clientjobs', $newjob);
}
It's not neccessary and could be breaking the database class, as well as halting any execution for the application.
Here's your problem:
echo form_open('client/insertjob');
If you look at your HTML code in your browser, you'll see something like this:
<form action="client/insertjob">
There will probably be a whole bunch of other attributes in your form tag - they're not important for this answer.
That action attribute is telling the browser where to go after you click submit. Where is it going? Back to the insertjob method. But it needs to go to your addingjob method - that's where the database update is actually being done. So change the form_open call to:
echo form_open('client/addingjob');
As I see your are using 2 controller functions for posting, page 1 to page 2. You have error on form open you should post your data to addingjob not insertjob.
echo form_open('client/addingjob');
will fix your issue but I highly recommend you to use, one controller for form submit. Below code will send post to same url. And you could add some attributes on it.
<?php
$attributes = array('class' => 'form-horizontal');
echo form_open($this->uri->uri_string(),$attributes); ?>
I have a file called admin.php in which I have a button with the name send. What I want to do is when I click it, to make visible a link on the user's page, user.php. How can I do this?
I have a file with all my functions called functions.php in which I have a function called onSubmit($var); I initialize the variable $var is admin.php with the value $_POST['send'] but when I call the function in the file user.php I have no way of telling him who the variable $var is so I get 'undefined index'.
Is there another way to do this?
EDIT Added code
This is admin.php
<input type="button" name="send" value="Submit" /><br/>
require 'functions.php';
$posted = $_POST['send'];
onSubmit($posted);
This is user.php
require 'functions.php';
onSubmit($var); //here it says undefined index var because it doesn't know who the variable is
if($isSent == 1) {
<a style="visibility:visible;" href="test3.html" id="test3">Test3</a> <br/>
}
And this is functions.php
global $isSent;
function onSubmit($var) {
if(isset($var)) {
$isSent = 1;
}
}
Basically you need to use sessions like below:
if(isset($_SESSION['makeVisible']) && $_SESSION['makeVisible'] == true){
echo '<button>Button init</button>'; //you could also use html like the comment below.
}
/*
if(condition){?> <!-- this is now html --> <button>Button init</button><?}
*/
Then to set this variable on your admin page use:
if(isset($_POST['submitButton'])){
$_SESSION['makeVisible'] == true;
}
You'll also need a form for this method to work but there are other methods but I prefer this one.
<form name="buttonMakerThing" method="POST">
<input name="submitButton" value="Make button init Visible" type="submit"/>
</form>
Without an action the form defaults to 'POSTING' the form information to the current page. Making the condition if(isset($_POST)) return true.
You will need to add a $_SESSION declaration at the top of every php page you have on your site for this to work. It MUST go on the very first line of every page! for example:
01: | <?php session_start();
02: |//rest of script;
Please look more into $_SESSIONS for unnsetting/destroying your sessions and more uses for them :) http://php.net/manual/en/reserved.variables.session.php
Right I've done a bit of research on Caching and this is what I've come up with. It might not be 100% correct but it's a start as like I've said I've never tried it myself lol
In your admin.php I'd put this function in:
if(isset($_POST['send'])){
if($enabled == true){
$enabled == false;
}
else{
$enabled == true;
}
apc_add('enabled',$enabled);
}
Now to 'get' our $enabled var:
$enabled = apc_fetch('enabled');
Then to check the the var within your client page:
if($enabled == true){
echo ' button';
}
Now the only things I haven't fully looked at is the security of the apc_ function and the client usage. I believe it works for all clients of the server but I'm not 100% certain. Here the php manual to give better examples.
This is the method I was thinking of. But again I'm not sure on the security of it but I'm sure you can find something to keep it secure. The video is actually is tutorial for a Youtube API. But he does cover saving a variable to a cache text file which should be of use to you :)
If you have functions.php which defines functions, simply include it in admin.php file and then you can call the function from there and also pass value.
I have a basic form, which i need to put some validation into, I have a span area and I want on pressing of the submit button, for a predefined message to show in that box if a field is empty.
Something like
if ($mytextfield = null) {
//My custom error text to appear in the spcificed #logggingerror field
}
I know i can do this with jquery (document.getElementbyId('#errorlogging').innerHTML = "Text Here"), but how can I do this with PHP?
Bit of a new thing for me with php, any help greatly appreciated :)
Thanks
You could do it it a couple of ways. You can create a $error variable. Make it so that the $error is always created (even if everything checks out OK) but it needs to be empty if there is no error, or else the value must be the error.
Do it like this:
<?php
if(isset($_POST['submit'])){
if(empty($_POST['somevar'])){
$error = "Somevar was empty!";
}
}
?>
<h2>FORM</h2>
<form method="post">
<input type="text" name="somevar" />
<?php
if(isset($error) && !empty($error)){
?>
<span class="error"><?= $error; ?></span>
<?php
}
?>
</form>
If you want change it dynamically in client-side, there is no way but ajax. PHP works at server-side and you have to use post/get requests.
Form fields sent to php in a $_REQUEST, $_GET or $_POST variables...
For validate the field param you may write like this:
if(strlen($_REQUEST['username']) < 6){
echo 'false';
}
else{
echo 'true';
}
You can't do anything client-side with PHP. You need Javascript for that. If you really need PHP (for instance to do a check to the database or something), you can use Javascript to do an Ajax call, and put the return value inside a div on the page.
To practice PHP and MySQL development, I am attempting to create the user registration system for an online chess game.
What are the best practices for:
How I should handle the (likely) possibility that when a user tries to register, the username he has chosen is already in use, particularly when it comes to function return values? Should I make a separate SELECT query before the INSERT query?
How to handle varying page titles?($gPageTitle = '...'; require_once 'bgsheader.php'; is rather ugly)
(An excerpt of the code I have written so far is in the history.)
Do a separate SELECT to check whether the username is already in use before attempting to INSERT.
More importantly, I would suggest something like the following structure for the script you're writing. It has a strong separation of presentation logic (e.g. HTML) from your other processing (e.g. validation, database, business logic.) This is one important aspect of the model-view-controller paradigm and is generally considered a best-practice.
<?php
// The default state of the form is incomplete with no errors.
$title = "Registration";
$form_completed = false;
$errors = array();
// If the user is submitting the form ..
if ($_POST) {
// Validate the input.
// This includes checking if the username is taken.
$errors = validate_registration_form($_POST);
// If there are no errors.
if (!count($errors)) {
// Add the user.
add_user($_POST['username'], $_POST['password']);
// The user has completed.
$form_completed = true;
// Optionally you could redirect to another page here.
} else {
// Update the page title.
$title = "Registration, again!"
}
}
?>
<html>
<head>
<title>Great Site: <?= $title ?></title>
<body>
<?php if ($form_complete): ?>
<p>Thanks for registering!</p>
<?php else: ?>
<?php if (count($errors)): ?>
<ul>
<?php foreach ($errors as $error): ?>
<li><?= $error ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<form method="post">
Username: <input type="text" name="username">
Password: <input type="password" name="password">
<input type="submit">
</form>
<?php endif; ?>
</body>
</html>
Well, one thing you can do instead of repeating code down near the bottom is this:
if( $result === true ) {
$gPageTitle = 'Registration successful';
$response = <p>You have successfully registered as ' . htmlspecialchars( $username ) . ' on this site.</p>';
} elseif( $result == 'exists' ) {
$gPageTitle = 'Username already taken';
$response = '<p>Someone is already using the username you have chosen. Please try using another one instead.</p>';
} else {
trigger_error('This should never happen');
}
require_once 'bgsheader.php';
echo $response;
require_once 'bgsfooter.php';
Also, you can return false rather than the string 'exists' in the function, not that it makes much difference.
Checking the error number isn't bad, I'm sure that's why it's an included feature. If you really wanted to do something different, you could check if there already is a user by that name by selecting the username. If no result exists, then insert the user, otherwise, give the error.
One thing I like to do with error handling on forms is save all the error strings into an array like $error['username'], $error['email'], etc., and then have it run through the error checking on each input individually to set all the error strings, and then have a function that does something like this:
function error($field)
{
global $error;
if(isset($error[$field]))
{
echo $error[$field];
}
}
and then call that after each field in the form to give error reporting on the form. Of course, the form page must submit to itself, but you could have all the error checking logic in a separate file and do an include if $_POST['whatever'] is set. If your form is formatted in a table or whatever, you could even do something like echo '<tr><td class="error">' . $error[$field] . '</td></tr>, and automatically insert another row directly below the field to hold the error if there is one.
Also, always remember to filter your inputs, even if it should be filtered automatically. Never pass post info directly into a DB without checking it out. I'd also suggest using the specific superglobal variable for the action, like $_POST rather than $_REQUEST, because $_REQUEST contains $_GET, $_POST, and $_COOKIE variables, and someone could feasibly do something strange like submit to the page with ?username=whatever after the page, and then you have both $_POST['username'] and $_GET['username'], and I'm not sure how $_REQUEST would handle that. Probably would make there be a $_REQUEST['username'][0] and $_REQUEST['username'][1].
Also, a bit about the page titles. Don't know if you have it set up like this but you can do something like this in your header:
$pageTitle = "My Website";
if(isset($gPageTitle))
{
$pageTitle .= "- $gPageTitle";
}
echo "<title>$pageTitle</title>";
Which would make the page load normally with "My Website" as the title, and append "- Username already exists" or whatever for "My Website - Username already exists" as the title when $gPageTitle is set.
I think the answer from Mr. Neigyl would require a separate trip to the database, which is not a good idea because it would only add performance overhead to yuor app.
I am not a PHP guru, but I know my way around it, although I don't recall the === operator. == I remember.
You could pass the function call directly into the IF statement.
if (addUser($username, $passwd));
I don't see anything wrong with using the $gPageTitle variable, but you will probably have to declare it "global" first and then use namespaces so you can actually access it within the "header.php" because "header.php" will not know how to address this page's variables.
Although I personally don't like messing with namespaces and I would rather call a function from the "header.php" and pass the page title into it
display_title($pgTitle);
or
display_title("Registration Successfull");
or
$header->display_title("Registration Successfull")
if you like OO style better
Let me know if that helps. :)
You should get into forms and allow your page to redirect to another page where you have there the 'insert username to database'.
Suppose the username entered is in a post variable such as $_POST['username'].
Have your database check where that username exist:
$res = mysql_query("SELECT * FROM table WHERE username='$_POST['username']'") or die(mysql_error());
if(mysql_num_rows($res) > 0) {
echo "Username exists.";
// more code to handle username exist
} else {
// ok here.
}
What is basically done is we check if your table already contains an existing username. mysql_num_rows($res) will return 0 if no username exist.
I am having problems figuring out how to retain users data when the validation fails. I am somewhat new to PHP so I might be making some huge mistakes in my logic.
Currently if the validation fails all the fields are wiped clean and $_Post data is also gone.
Here is some code assuming the user enters an invalid email I want the Name field to be retained. This code is not working.
<?php
if($_POST['doSubmit'] == 'Submit') {
$usr_name = $data['Name'];
$usr_email = $data['Email'];
if (isEmail($usr_email)==FALSE){
$err = "Email is invalid.");
header("Location: index.php?msg=$err");
exit();
}
//do whatever with data
}
if (isset($_GET['msg'])) {
$msg = mysql_real_escape_string($_GET['msg']);
echo "<div class=\"msg\">$msg</div><hr />";
}
if (isset ($_POST['Name'])){
$reusername = $_POST['Name'];}
else{$reusername = "NOTHING";}//to test
?>
<form action="index.php" method="post" >
<input name="UserName" type="text" size="30" value="<?echo $reusername;?>">
<input name="Email" type="text" size="30">
<input name="doSubmit" type="submit" value="submit">
</form>
}
You can use AJAX to submit your form data to your PHP script and have it return JSON data that specifies whether the validation was successful or not. That way, your fields won't be wiped clean.
Another way is to send back the recorded parameters to the posting page, and in the posting page, populate the fields using PHP.
However, I think the first solution is better.
UPDATE
The edit makes your code clearer and so I noticed something. Your input field is called UserName in the HTML, but you are referring to Name in PHP. That's probably why it's not working. Is your field always being filled with the value NOTHING? Make sure the name of the input field and the subscript you are using in $_POST are the same.
Also, there's no need to redirect to another page (using header) if you have an error. Maintain an $errors array or variable to print error messages in the same page. But like I mentioned before, it's probably better to use the JSON approach since then you can separate your view layer (the html) from the PHP (controller layer). So you'd put your HTML in one file, and your PHP in another file.
EDIT:
Vivin had commented that my assumption regarding the header was incorrect and he was right in that. Further more it looks like what the OP is doing is essentially what i layed out below albeit in a less structured fashion. Further Vivin - caught what is likely the actual problem here - the html name and the array key $_POST do not match.
Its wiped clean because you are using header to redirect to another page. Typicaly you would have a single page that validates the data and if ok does something with it and returns a success view of some sort, or that returns an error view directly showing the form again. By using header youre actually redirecting the browser to another page (ie. starting up an entirely new request).
For example:
// myform.php
if(strtolower($_SERVER['REQUEST_METHOD']) == 'get')
{
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
elseif(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
{
$form = santize($_POST); // clean up the input... htmlentities, date format filters, etc..
if($data = is_valid($form))
{
process_data($data); // this would insert it in the db, or email it, etc..
}
else
{
$errors = get_errors(); // this would get our error messages associated with each form field indexed by the same key as $form
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
}
so this assumes that your form.inc.php always has the output of error messages coded into it - it just doesnt display them. So in this file you might see something like:
<fieldset>
<label for="item_1">
<?php echo isset($error['item_1']) ? $error['item_1'] : null; ?>
Item 1: <input id="item_1" value="<?php echo $form['item_1'] ?>" />
</label>
</fieldset>
Could do something similar to if failed then value=$_POST['value']
But vivin's answer is best. I don't know much about AJAX and wouldn't be able to manage that.
Ok, firstly header("Location: index.php?msg=$err"); is not really required. It's best practice not to redirect like this on error, but display errors on the same page. Also, redirecting like this means you lose all of the post data in the form so you can never print it back into the inputs.
What you need to do is this:
<input name="Email" type="text" size="30" value="<?php print (!$err && $usr_email ? htmlentities($usr_email, ENT_QUOTES) : '') ?>">
Here I'm checking whether any errors exist, then whether the $usr_email variable is set. If both these conditions are matched the post data is printed in the value attribute of the field.
The reason I'm using the function htmlentities() is because otherwise a user can inject malicious code into the page.
You appear to be processing the post on the same page as your form. This is an OK way to do things and it means you're nearly there. All you have to do is redirect if your validation is successful but not if it fails. Like this
<?php
if( isset( $_POST['number'] ) ) {
$number = $_POST['number'];
// validate
if( $number < 10 ) {
// process it and then;
header('Location: success_page.php');
} else {
$err = 'Your number is too big';
}
} else {
$number = '';
$err = '';
}
?>
<form method="POST">
Enter a number less than 10<br/>
<?php echo $err ?><br/>
<input name="number" value="<?php echo $number ?>"><br/>
<input type="submit">
</form>