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.
Related
I am new to prestashop and module development. I was practicing a module which allows users to submit comment on a product. But there is an issue with form submission. I think.
Below is the code I tried.(Only methods of interest)
BulkyEdit.php
public function install()
{
if (!parent::install() )
return false;
//Registering the hook.
$this->registerHook('displayProductTabContent');
return true;
}
public function hookDisplayProductTabContent($params)
{
//Using hook displayProductTabContent.
$this->processCommentPublish();
return $this->display(__FILE__,'displayProductTabContent.tpl');
}
private function processCommentPublish()
{
$stat = Tools::isSubmit('comment_submit_form');
if($stat)
{
$stat = "submit success";
}
else $stat = "failure";
Configuration::updateValue('BULKYEDIT_TESTVAL',$stat);
}
displayProductTabContent.tpl
<form action="" method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="text" placeholder="Tell us your name" name="name"/>
</div>
<div class="form-group">
<label for="comment">Your comment</label>
<input type="text" placeholder="Tell us your name" name="comment"/>
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="comment_submit_form" value="Publish" />
</div>
</form>
$stat logs failure.
Edit : BULKYEDIT_TESTVAL logs Forms post failure
if(isset($_POST['comment_submit_form']))
{
Configuration::updateValue('BULKYEDIT_TESTVAL',$_POST);
}
else{
Configuration::updateValue('BULKYEDIT_TESTVAL','Forms post failure');
}
Any help is highly appreciated.
No Issues with the code.Everything works fine. Actually the code I wrote for the first time was different and I was using a wrong name in Tools::isSubmit('submit').But after I made changes prestashop kept using the cached files so I could not able to get the desired results according to my latest edits.
I then disabled cache and enabled Developer Mode following the instructions here.
http://blog.belvg.com/enabling-error-output-in-prestashop.html
And everything was working like a charm. So, When developing. enable Developer mode on so you can see results of your latest edits.
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;
}
}
}
Before You read the code, I have tried separating each part into their own php files and just using requires to fetch the code, but using requires or having all the code in the same file I seem to be getting the same errors regardless. I think it may have something to do with the the version of PHP I'm using.
I seem to be getting an error with submit on line 3 of the BACKEND part. Being an undefined property.
The second is an undefined error on the USER FEEDBACK section.
I've used this template before and has worked successfully.
I'm running PHP 5.4.12 and Apache 2.4.4 using WAMP on my Windows 8.1 Pro PC.
Any help would be appreciated
/** BACKEND **/
<?php
if($_POST['submit'])
{
$fName=$_POST['fName'];
$topic=$_POST['topic'];
$email=$_POST['email'];
$message=$_POST['message'];
function verify_email($email)
{
if(!preg_match('/^[_A-z0-9-]+((\.|\+)[_A-z0-9-]+)*#[A-z0-9-]+(\.[A-z0-9-]+)*(\.[A-z]{2,4})$/',$email))
{
return false;
}
else
{
return $email;
}
}
function verify_email_dns($email)
{
list($name, $domain) = split('#',$email);
if(!checkdnsrr($domain,'MX'))
{
return false;
}
else
{
return $email;
}
}
if(verify_email($email))
{
if(verify_email_dns($email))
{
if ($fName=='')
{
header('location:./contact.php?error=missing');
}
elseif ($email=='')
{
header('location:./contact.php?error=missing');
}
elseif ($message=='')
{
header('location:./contact.php?error=missing');
}
else
{
foreach ($myvars as $var)
{
if (isset($_POST[$var]))
{
$var=$_POST[$var];
}
}
$subject = "Email Submission for review";
$add.="test.email#gmail.com";
$msg.="First Name: \t$fName\n";
$msg.="Email: \t$email\n";
$msg.="Topic: \t$topic\n";
$msg.="Message: \t$message\n";
$mailheaders="From: $email\n";
$mailheaders.="Reply-To: $email\n";
mail("$add", "$subject", $msg, $mailheaders);
header('location:./contact.php?error=none');
}//end else
}//end inner-if
else
{
header('location:./contact.php?error=mx');
}
}// end outter-if
else
{
header('location:./contact.php?error=format');
}
}// end starting if
/** VIEW for form **/
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contactForm">
<label for="fName" class="first-name">Name:</label>
<input type="text" name="fName" value="" id="fName">
<br><br>
<label for="email" class="email-name">Email:</label>
<input type="text" name="email" value="" id="email">
<br><br>
<label for="topic" class="subject-name">Subject:</label>
<input type="text" name="topic" value="" id="topicsubject">
<br><br>
<label for="message" class="message-name">Message:</label>
<textarea name="message" rows="5" cols="60" id="message"></textarea>
<br><br>
<input type="submit" name="submit" id="submit-btn" class="submit-btn" value="Email Me">
</form>
/** USER FEEDBACK if error occurs **/
<?php
$error=$_GET['error'];
switch ($error)
{
case "mx":
echo "<br><span class='red'>Your email address you entered is invalid. Please try again.</span><br>";
break;
case "format":
echo "<br><span class='red'>Your email address is not in the correct format, it should look like name#domain.com. Please try again.</span><br>";
break;
case "missing":
echo "<br><span class='red'>You seem to be missing a required field, please try again.</span><br>";
break;
case "none":
echo "<br>Your email was sent. I will get back to you as soon as I can. Thank you for your interest.<br>";
break;
default:
echo "<br><br>";
}
?>
You are assuming that there are POST and GET variables when you are visiting the page. So its possible that $_POST['submit'] only exists when you actually submit the form otherwise you will get an error when first visiting that page.
try this condition instead:
if(isset($_POST['submit']) ) {
// now its safe to do something
}
You should never assume that any $_POST or $_GET variable is available when visiting the page.
Also off topic:
In your HTML you are using an 'action' attribute with the same url as the page you are visiting on this line here:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contactForm">
Basically if you just leave out the action attribute all together it will have the same effect and its also semantic to do so. This is a better way of doing it and it has the same effect:
<form method="post" name="contactForm">
You can check this previous Stack Overflow question for a better explanation on that matter:
Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")
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>
I have a simple form for a mailing list that I found at http://www.notonebit.com/projects/mailing-list/
The problem is when I click submit all I want it to do is display a message under the current form saying "Thanks for subscribing" without any redirect. Instead, it directs me to a completely new page.
<form method="POST" action="mlml/process.php">
<input type="text" name="address" id="email" maxlength="30" size="23">
<input type="submit" value="" id="submit"name="submit" >
</form>
You will need AJAX to post the data to your server. The best solution is to implement the regular posting, so that will at least work. Then, you can hook into that using Javascript. That way, posting will work (with a refresh) when someone doesn't have Javascript.
If found a good article on posting forms with AJAX using JQuery .
In addition, you can choose to post the data to the same url. The JQuery library will add the HTTP_X_REQUESTED_WITH header, of which you can check the value in your server side script. That will allow you to post to the same url but return a different value (entire page, or just a specific response, depending on being an AJAX request or not).
So you can actually get the url from your form and won't need to code it in your Javascript too. That allows you to write a more maintanable script, and may even lead to a generic form handling method that you can reuse for all forms you want to post using Ajax.
Quite simple with jQuery:
<form id="mail_subscribe">
<input type="text" name="address" id="email" maxlength="30" size="23">
<input type="hidden" name="action" value="subscribe" />
<input type="submit" value="" id="submit"name="submit" >
</form>
<p style="display: none;" id="notification">Thank You!</p>
<script>
$('#mail_subscribe').submit(function() {
var post_data = $('#mail_subscribe').serialize();
$.post('mlml/process.php', post_data, function(data) {
$('#notification').show();
});
});
</script>
and in your process.php:
<?php
if(isset($_POST['action'])) {
switch($_POST['action']) {
case 'subscribe' :
$email_address = $_POST['address'];
//do some db stuff...
//if you echo out something, it will be available in the data-argument of the
//ajax-post-callback-function and can be displayed on the html-site
break;
}
}
?>
It redirects to a different page because of your action attribute.
Try:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<input type="text" name="address" id="email" maxlength="30" size="23" />
<input type="submit" value="" id="submit" name="submit" />
</form>
<?php if (isset($_POST['submit'])) : ?>
<p>Thank you for subscribing!</p>
<?php endif; ?>
The page will show your "Thank You" message after the user clicks your submit button.
Also, since I don't know the name of the page your code is on, I inserted a superglobal variable that will insert the the filename of the currently executing script, relative to the document root. So, this page will submit to itself.
You have to use AJAX. But that requires JavaScript to be active at the users Brwoser.
In my opinion it's the only way to do without redirect.
to send a form request without redirecting is impossible in php but there is a way you can work around it.
<form method="post" action="http://yoururl.com/recv.php" target="_self">
<input type="text" name="somedata" id="somedata" />
<input type="submit" name="submit" value="Submit!" />
</form>
then for the php page its sending to have it do something but DO NOT echo back a result, instead simply redirect using
header( 'Location: http://yourotherurl.com/formpage' );
if you want it to send back a success message simply do
$success = "true";
header( 'Location: http://yourotherurl.com/formpage?success='.$success);
and on the formpage add
$success = $_GET['success'];
if($success == "true"){ echo 'Your success message'; } else { echo
'Your failure message';
Return and print the contents of another page on the current page.
index.php
<html>
<body>
<p>index.php</p>
<form name="form1" method="post" action="">
Name: <input type="text" name="search">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$_POST['search'];
include 'test.php';
}
?>
</body>
</html>
test.php
<?php
echo 'test.php <br/>';
echo 'data posted is: ' . $_POST['search'];
?>
Result:
Just an idea that might work for you assuming you have no control over the page you are posting to:
Create your own "proxy php target" for action and then reply with the message you want. The data that was posted to your php file can then be forwarded with http_post_data (Perform POST request with pre-encoded data). You might need to parse it a bit.
ENGLISH Version
It seems that no one has solved this problem without javascript or ajax
You can also do the following.
Save a php file with the functions and then send them to the index of your page
Example
INDEX.PHP
<div>
<?php include 'tools/edit.php';?>
<form method="post">
<input type="submit" name="disable" value="Disable" />
<input type="submit" name="enable" value="Enable" />
</form>
</div>
Tools.php (It can be any name, note that it is kept in a folder lame tools)
<?php
if(isset($_POST['enable'])) {
echo "Enable";
} else {
}
if(isset($_POST['disable'])) {
echo "Disable";
} else {
}
?>
Use
form onsubmit="takeActions();return false;"
function takeAction(){
var value1 = document.getElementById('name').innerHTML;
// make an AJAX call and send all the values to it
// Once , you are done with AJAX, time to say Thanks :)
document.getElementById('reqDiv').innerHTML = "Thank You for subscribing";
}