Where is the class instance created in this php Example? - php

I'm quite new to PHP but used to some other programming languages (e.g JAVA,Python). Recently I had a closer look to the Login-Script panique/php-login-advanced (https://github.com/panique/php-login-advanced) which I find is a really good way to learn some useful PHP-structures.
Unfortunately there is one thing, i don't understand and which gives me quite a headache: all starts from "index.php" whih includes "login_manager.php" (used, among others, to create a new Login-instance from "classes/Login.php").
// create a login object. when this object is created, it will do all login/logout stuff automatically
// so this single line handles the entire login process.
$login = new Login();
If you aren't logged in, you can register yourself, which leads you to "views/register.php". In this file there is a POST-form, calling the same file again:
<?php include('_header.php'); ?>
<!-- show registration form, but only if we didn't submit already -->
<?php if (!$registration->registration_successful && !$registration->verification_successful) { ?>
<form method="post" action="register.php" name="registerform">
<label for="user_name"><?php echo WORDING_REGISTRATION_USERNAME; ?></label>
<input id="user_name" type="text" pattern="[a-zA-Z0-9]{2,64}" name="user_name" required />
<label for="user_email"><?php echo WORDING_REGISTRATION_EMAIL; ?></label>
<input id="user_email" type="email" name="user_email" required />
<label for="user_password_new"><?php echo WORDING_REGISTRATION_PASSWORD; ?></label>
<input id="user_password_new" type="password" name="user_password_new" pattern=".{6,}" required autocomplete="off" />
<label for="user_password_repeat"><?php echo WORDING_REGISTRATION_PASSWORD_REPEAT; ?></label>
<input id="user_password_repeat" type="password" name="user_password_repeat" pattern=".{6,}" required autocomplete="off" />
<img src="tools/showCaptcha.php" alt="captcha" />
<label><?php echo WORDING_REGISTRATION_CAPTCHA; ?></label>
<input type="text" name="captcha" required />
<input type="submit" name="register" value="<?php echo WORDING_REGISTER; ?>" />
</form>
<?php } ?>
<?php echo WORDING_BACK_TO_LOGIN; ?>
<?php include('_footer.php'); ?>
Now I don't understand where this $registration instance comes from?! Of course it should be an instance of "classes/Registration.php" which explains the further processing using the constructor of the class:
public function __construct()
{
session_start();
// if we have such a POST request, call the registerNewUser() method
if (isset($_POST["register"])) {
$this->registerNewUser($_POST['user_name'], $_POST['user_email'], $_POST['user_password_new'], $_POST['user_password_repeat'], $_POST["captcha"]);
// if we have such a GET request, call the verifyNewUser() method
} else if (isset($_GET["id"]) && isset($_GET["verification_code"])) {
$this->verifyNewUser($_GET["id"], $_GET["verification_code"]);
}
}
But where is the connection here? I searched the complete project with all files and I could not find something like "new Registration()" and even the $registration variable is never set (to my knowledge). So as the script works without problems, there needs to be some trick i don't know.
I also thought it could be set in the "_header.php" but in this file there is only some error-output:
// show potential errors / feedback (from registration object)
if (isset($registration)) {
if ($registration->errors) {
foreach ($registration->errors as $error) {
echo $error;
}
}
if ($registration->messages) {
foreach ($registration->messages as $message) {
echo $message;
}
}
}

Related

How to login properly using HTML and php?

So, I'm creating a simple file share site that takes in only a user name to login.
But even when I have the correct user name, the program thinks it's wrong below is my code:
<form method ="POST">
<p>
<label for="user">User ID: </label><input type="text" name="userID" id="user" />
</p>
<p>
<input type="submit" name = "LogIn" value="Log In" />
<input type ="reset"/>
</p>
</form>
PHP part
<?php
$users = file('users.txt');
if (isset($_POST['LogIn'])) {
echo $_POST['userID'].'<br>';
foreach ($users as $user) {
if ($_POST['userID']==$user){
header("Location: FileShareLogInRedirect.php");
exit;
}
}
echo "Wrong ID".'<br>';
?>
What I might be doing wrong? It seems like it should work.
The submit button value does NOT get sent along with the POST.
You should not use the submit button to try to pass form values.
<form method ="POST">
<p>
<label for="user">User ID: </label><input type="text" name="userID" id="user" />
</p>
<p>
<input type="submit" value="Log In" />
<input type ="reset"/>
</p>
</form>
PHP part
<?php
$users = file('users.txt');
if (isset($_POST['userID'])) {
echo $_POST['userID'].'<br>';
foreach ($users as $user) {
if ($_POST['userID']==$user){
header("Location: FileShareLogInRedirect.php");
exit;
}
}
echo "Wrong ID".'<br>';
?>
you haven't warped
echo "Wrong ID".'<br>';
in an else statement.
Example:
<?php
$users = file('users.txt');
if (isset($_POST['LogIn'])) {
echo $_POST['userID'].'<br>';
foreach ($users as $user) {
if ($_POST['userID']==$user){
header("Location: FileShareLogInRedirect.php");
exit;
}
}
else{
echo "Wrong ID".'<br>';
}
?>
Without the else statement your echo statement will execute every time regardless of weather the login is correct or not.
Function file() can't process row by row. For processing on any raw like this case, we use function in_array(). Function in_array() we can use only if we have explicit function array(). Because of that, we needs variable $users to be equal array(). Afther that with help of function fopen() and loop While, load array(), and afther that use function in_array().
Here is code:
<form method ="POST">
<p>
<label for="user">User ID: </label><input type="text" name="userID" id="user" />
</p>
<p>
<input type="submit" name = "LogIn" value="Log In" />
<input type ="reset"/>
</p>
</form>
<?php
$users=array();
$fpn=fopen('users.txt', 'r');
while (!feof($fpn))
{
$user=fgets($fpn);
$user=trim($user);
$users[]=$user;
}
if (in_array($_POST['userID'], $users)) {
header("Location: FileShareLogInRedirect.php");
exit;
}
echo "Wrong ID".'<br>';
?>

How do you correctly pass post variables from the view to the controller in CodeIgniter?

I haven't used CodeIgniter in nearly a year and I seem to have forgotten a lot of the fundamentals.
I am trying to retrieve the post variables from a form and pass them into a model which inserts them into mysql.
The controller function my form submits to looks like this:
public function validation() {
$this->load->helper("form");
$this->load->model("contact_form");
$data = array(
"name" => $this->input->post("name"),
... etc. etc. ....
);
if ($this->contact_form->new_form($data)) {
$this->load->view("header");
$this->load->view("submitted");
} else echo "Sorry, there was a problem adding the form to the database.";
}
The form in the view is structured like so:
<? echo form_open("form/validation");?>
<div id="one" style="display: block;">
<h1>A Heading</h1>
<p>Some Text</p>
<p class="bold">Name: <input type="text" name="name" class="single" value="<?php echo set_value('name'); ?>"></p>
<p class="bold">Email: <input type="text" name="email" class="single" value="<?php echo set_value('email'); ?>"></p>
<p class="bold">And then some radio buttons</p>
<p> yes <input type="radio" name="registered" value="yes"> no <input type="radio" name="registered" value="no"></p>
<p class="bold">And a textarea...</p>
<textarea name="description" class="fill" value="<?php echo set_value('description'); ?>"></textarea>
next
</div>
<div id="two" style="display:none;">
<h1>Another Heading...</h1>
<p class="bold">And some more textareas</p>
<textarea name="audience" class="fill"></textarea>
... There are four divs in total with further textarea fields ...
<p class="bold"><input type="submit" name="submit" value="submit" class="center"></p>
back
</div>
<? echo form_close();?>
And finally my model is very simple:
class contact_form extends CI_Model {
public function new_form($data) {
$query = $this->db->insert("contact", $data);
if ($query) {
return true;
} else return false;
}
}
The form processes without any errors, but the data just appears as 0's in MySQL. If at any point I attempt to output the value of $_POST it returns BOOL (false), or with $this->input->post('something'); it returns NULL.
You will notice that no actual validation takes place. Initially I was using $this->form_validation->run() and getting the same results. I thought perhaps I was having trouble with the validation so I stripped it out and now I'm fairly certain my problem is that I'm not passing the $_POST variables correctly.
Can anyone explain why I am failing so hard?
I have now resolved this problem.
For some reason <? echo form_open("form/validation");?> was implementing GET and not POST. Replacing that line with <form method="post" accept-charset="utf-8" action="form/validation"/> resolved the issue.
According to the CodeIgniter documentation, by default, form_open should use POST - I have no idea why in my case it decided to use GET.

error if "else" begins with a new php block

Just curious to know why the code below gives "unexpected T_ELSE" syntax error:
<?php if (isset($_SESSION["user_id"])) { ?>
<h2>Welcome, <?php echo $_SESSION["user_id"]; ?></h2>
<?php } ?>
<?php else { ?>
<form action="" method="post">
<label for="user">User ID</label>
<input type="text" id="user" />
<label for="password">Password</label>
<input type="password" id="password" />
<input type="submit" value="Login" />
</form>
<?php } ?>
While I keep the } else { on same line, it works fine. I mean the code below just works fine:
<?php if (isset($_SESSION["user_id"])) { ?>
<h2>Welcome, <?php echo $_SESSION["user_id"]; ?></h2>
<?php } else { ?>
<form action="" method="post">
<label for="user">User ID</label>
<input type="text" id="user" />
<label for="password">Password</label>
<input type="password" id="password" />
<input type="submit" value="Login" />
</form>
<?php } ?>
thinking a bit about this, I've come to the realization that this has to be the intended behavior.
consider the following (syntactical wrong ) example:
<?php if ($condition == true) { ?>
<div id="first">Yey</div>
<?php } ?>
<span id="second?">where am I?</span>
<?php else { ?>
<div id="first">Ney</div>
<?php } ?>
the span element would be in an undefined state
It seems to me, that you can't start a new code block with an else statement without a preceding if.
You could…
A) write your code in one block, e.g.
<?php }
else { ?>
B) or use the alternative syntax, if you are working with multiple code-blocks:
<?php if (isset($_SESSION["user_id"])): ?>
/* … */
<?php else: ?>
/* … */
<?php endif; ?>
There's nothing weird per se, it's because you're in a separate code block, that's the simplest way to put it. Nothing is open at the time of you "Leaving PHP", so when you go back into it there is no context.
Consider your code like this (of course consider it as pseudo-code just to emphasise the point):
if (isset($_SESSION["user_id"])) {
// ....
}; else {
// ....
}
Breaking in/out of PHP can be tricky at times, and managing it like you want to in your first example doesn't really make very much sense.
You might want to consider using this, which would put your transition to the else block on a single line anyway:
<?php if (isset($_SESSION["user_id"])): ?>
<h2>Welcome, <?php echo $_SESSION["user_id"]; ?></h2>
<?php else: ?>
<form action="" method="post">
<label for="user">User ID</label>
<input type="text" id="user" />
<label for="password">Password</label>
<input type="password" id="password" />
<input type="submit" value="Login" />
</form>
<?php endif ?>
At the end of the day whilst PHP is pretty flexible I wouldn't expect it to allow you to do what you're wanting. That would allow for an else block to be added miles away which may not be the intention at all.
<?php } ?>
^^
When PHP parses a file, it looks for opening and closing tags, which are which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser.
When the PHP parser comes to this line it executes the if block only. After that PHP parser tried to parse the next block of code(else part) but here it start with else { and because of that else is separated from if and produces error.

PHP error display

I am new with php, but I have already made a registration script that works fine. But the problem is every time I press the submit button to check my error, I'm going to a new page.
My question is how I make that error comes on the same page?
The code I am useing for the html form.
I want the error display in the error div box that I made Any idea ?
<div id="RegistrationFormLayout">
<h1>Registration Page</h1>
<div id="ErrorMessage"></div>
<form action="script/registration.php" method="post">
<label for="Username">Username</label>
<input type="text" name="Regi_username">
<label for="FirstName">FirstName</label>
<input type="text" name="Regi_Firstname">
<label for="LastName">LastName</label>
<input type="text" name="Regi_Lastname">
<label for="EamilAddress">Regi_EmailAddres</label>
<input type="text" name="Regi_EmailAddres">
<label for="Password">Password</label>
<input type="password" name="Regi_password">
<button type="submit" value="Submit" class="Login_button">Login</button>
</form>
</div>
If I understand correctly, you want form validation errors there. This is a very common pattern, and the simple solution is to always set a form's action attribute to the same page that displays the form. This allows you to do the form processing before trying to display the form (if there are $_POST values). If the validation is successful, send a redirect header to the "next step" page (with header()).
The basic pattern looks like this (in very very simplified PHP)
<?php
if(count($_POST)) {
$errors = array();
$username = trim($_POST['Regi_username']);
if(empty($username)) {
$errors[] = 'username is required';
}
if(count($errors) == 0) {
header('Location: success.php');
die();
}
}
<ul class="errors">
<?php foreach($errors as $error) { ?>
<li><?php echo $error;?></li>
<?php } ?>
</ul>

Magento server side form validation

is there any server side form validation in magento? i have created a from and using magentos form validation but its not gonna work if someone disable the javascipt and enters something that can be harmful. if there is no built in class for that. could someone please point me in a direction how to implement a server side form validation as a backup. here is my my code for the form
<div style="border:0px solid red; margin:0px auto;">
<?php $_product = $this->getProduct(); ?>
<form id="test" action="<?php echo Mage::getUrl('pricenotify/pricenotify/db') ?>" method="post">
<label for="price">Price *</label>
<input type="text" id="price" name="price" value="" class="required-entry validate-number"/><br />
<label for="email">Email Address *</label>
<input type="text" id="email" name="email" value="" class="required-entry validate-email"/>
<input type="hidden" id="id" name="id" value="<?php echo $_product->getId() ?>" />
<input type="hidden" id="propri" name="propri" value="<?php echo $_product->getPrice() ?>" />
<input type="submit" name="submit" value="<?php echo $this->__('Submit') ?>" onclick="if(customForm.validator && customForm.validator.validate()) this.form.request(); return false;" />
</form>
<script type="text/javascript">
//< ![CDATA[
var customForm = new VarienForm('test',false);
//]]>
</script>
If you want to keep it simple, you could do the validation in your controller
try {
$postObject = new Varien_Object();
$postObject->setData($post);
$error = false;
if (!Zend_Validate::is($postObject->getPrice(), 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is($postObject->getEmail(), 'EmailAddress')) {
$error = true;
}
if ($error) {
throw new Exception();
}
//save to db
return;
} catch (Exception $e) {
Mage::getSingleton('customer/session')->addError(Mage::helper('pricenotify')->__('Unable to submit your request. Please, try again later'));
$this->_redirect('/');
return;
}
Zend_Validate : http://files.zend.com/help/Zend-Framework/zend.validate.html
Yes, Magento has server-side validation for some forms. However, the module that added the form is responsible for validating it - so if you're dealing with third-party code like a plugin, it might not be there.
Conventionally, the validation code lives with the Model part of a module. For example, in Magento's built-in review functionality, when a review form is submitted, its data is validated by the validate() function in the /app/code/core/Mage/Review/Model/Review.php file. I'd start by looking at that code, and the code in existing Mage/Core modules for examples.
In the situation that you give, the conventional place for the validation logic would be /app/code/local/YourCompany/PriceNotify/Model/Pricenotify.php
Magento uses prototype to validate forms. To implement this validation, just add "required-entry" to your input tag.

Categories