PHP domain availability script exec() function alternative - php

I want to install a php whois domain availability check script on my website which I found somewhere.
It has a whois_class.php file where it allows my to switch between "win" & "linux" mode.
When I switch on "win" mode it works fine in my localhost as I am using Windows OS.
But when I upload it to the server it stops working as my server is Linux Server.
So I have to switch it to "linux" mode and re-upload whois_class.php. This was expected to work fine but for linux mode the developer of the script has used exec() function which my host has disabled for security purposes.
So, the only option I guess is if I change my server platform from Linux to Windows. But, that will be a mess.
I was looking for a way how I can use this script to run smoothly on my linux server just as it runs on my localhost in Windows OS. Any change or modification to the script to make it run will be appreciated.
whois_class.php :
<?php
class Whois_domain {
var $possible_tlds;
var $whois_server;
var $free_string;
var $whois_param;
var $domain;
var $tld;
var $compl_domain;
var $full_info;
var $msg;
var $info;
var $os_system = "win"; // switch between "linux" and "win"
function Whois_domain() {
$this->info = "";
$this->msg = "";
}
function process() {
if ($this->create_domain()) {
if ($this->full_info == "yes") {
$this->get_domain_info();
} else {
if ($this->check_only() == 1) {
$this->msg = "<p style='font-size: 16px'>The domain name: <font color='#000'>".$this->compl_domain."</font> is <font color='#2ec62e'>available</font>.</p>";
return true;
} elseif ($this->check_only() == 0) {
$this->msg = "<p style='font-size: 16px'>The domain name: <font color='#000'>".$this->compl_domain."</font> is <font color='red'>registered</font>.</p>";
return false;
} else {
$this->msg = "<p style='font-size: 16px'>There was something wrong, try it again.</p>";
}
}
} else {
$this->msg = "<p style='font-size: 16px'>Only letters, numbers and hyphens (-) are valid!</p>";
}
}
function check_entry() {
if (preg_match("/^([a-z0-9]+(\-?[a-z0-9]*)){2,63}$/i", $this->domain)) {
return true;
} else {
return false;
}
}
function create_tld_select() {
$menu = "<select id=\"tld\" name=\"tld\" style=\"margin-left:0; width: 100px; margin-top: 20px; border-radius: 5px\">\n";
foreach ($this->possible_tlds as $val) {
$menu .= " <option value=\"".$val."\"";
$menu .= (isset($_POST['tld']) && $_POST['tld'] == $val) ? " selected=\"selected\">" : ">";
$menu .= $val."</option>\n";
}
$menu .= "</select>\n";
return $menu;
}
function create_domain() {
if ($this->check_entry()) {
$this->domain = strtolower($this->domain);
$this->compl_domain = $this->domain.".".$this->tld;
return true;
} else {
return false;
}
}
function check_only() {
$data = $this->get_whois_data();
if (is_array($data)) {
$found = 0;
foreach ($data as $val) {
if (preg_match('/'.$this->free_string.'/', $val)) {
$found = 1;
}
}
return $found;
} else {
$this->msg = "<p style='font-size: 16px'>Error, please try it again.</p>";
}
}
function get_domain_info() {
if ($this->create_domain()) {
$data = ($this->tld == "nl") ? $this->get_whois_data(true) : $this->get_whois_data();
//print_r($data);
if (is_array($data)) {
foreach ($data as $val) {
if (eregi($this->free_string, $val)) {
$this->msg = "<p style='font-size: 16px'>The domain name: <font color='#000'>".$this->compl_domain."</font> is <font color='#2ec62e'>available</font>.</p>";
$this->info = "";
break;
}
$this->info .= $val;
}
} else {
$this->msg = "<p style='font-size: 16px'>Error, please try it again.</p>";
}
} else {
$this->msg = "<p style='font-size: 16px'>Only letters, numbers and hyphens (-) are valid!</p>";
}
}
function get_whois_data($empty_param = false) {
// the parameter is new since version 1.20 and is used for .nl (dutch) domains only
if ($empty_param) {
$this->whois_param = "";
}
if ($this->tld == "de") $this->os_system = "win"; // this tld must be queried with fsock otherwise it will not work
if ($this->os_system == "win") {
$connection = #fsockopen($this->whois_server, 43);
if (!$connection) {
unset($connection);
$this->msg = "<p style='font-size: 16px'>Can't connect to the server!</p>";
return;
} else {
sleep(2);
fputs($connection, $this->whois_param.$this->compl_domain."\r\n");
while (!feof($connection)) {
$buffer[] = fgets($connection, 4096);
}
fclose($connection);
}
} else {
$string = "whois -h ".$this->whois_server." \"".$this->whois_param.$this->compl_domain."\"";
$string = str_replace (";", "", $string).";";
exec($string, $buffer);
}
if (isset($buffer)) {
//print_r($buffer);
return $buffer;
} else {
$this->msg = "<p style='font-size: 16px'>Can't retrieve data from the server!</p>";
}
}
}
?>
The problem is here
if ($this->os_system == "win") {
$connection = #fsockopen($this->whois_server, 43);
if (!$connection) {
unset($connection);
$this->msg = "<p style='font-size: 16px'>Can't connect to the server!</p>";
return;
} else {
sleep(2);
fputs($connection, $this->whois_param.$this->compl_domain."\r\n");
while (!feof($connection)) {
$buffer[] = fgets($connection, 4096);
}
fclose($connection);
}
} else {
$string = "whois -h ".$this->whois_server." \"".$this->whois_param.$this->compl_domain."\"";
$string = str_replace (";", "", $string).";";
exec($string, $buffer);
}
Disabled functions by my host
system,exec,shell_exec,passthru,popen,proc_open,pcntl_exec,highlight_file,show_source,symlink,link,posix_getpwuid,posix_getpwnam,posix_getgrgid,posix_getgrnam,posix_kill,posix_mkfifo,posix_getrlimit

There are plenty of functions related to program execution. However you should check which other functions are disabled on your setup:
var_dump(ini_get("disable_functions"));

Related

PHP ldap_get_entries returns null but only on one system not on another

I'm trying to connect to Active directory and validate my user which works and the I retrieve a certain field which returns and employeecode that stored in AD for our payroll/ESS application, this code has been working on multiple different clients but suddenly at one client the code runs through until it get to the ldap_get_entries, the ldap_search ran successfully but nothing is getting returned in get_entries
If checked some similar problems where people changed sAMAccount to uid or email in the filter but that hasn't helped me solve this, does anyone maybe have an idea whatI missed that would make this code fail on one system but work fine on others
the magic happens in the second function (RetrieveADEntry), the first(Authenticate) is just to show my connection
public function authenticate()
{
error_reporting(0);
//10.0.4.22
$this->ldapConnection = ldap_connect($this->mHost, $this->mPort);
if(isset($this->ldapConnection))
{
if(trim($this->mUsername) === "")
{
$this->mErrorCode = ERR_USERNAME_REQUIRED;
$this->mConnected = false;
return false;
}
else if(trim($this->mPassword) === "")
{
$this->mErrorCode = ERR_PASSWORD_REQUIRED;
$this->mConnected = false;
return false;
}
echo "pre bind";
ldap_set_option($this->ldapConnection, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
if ($this->mGroup == null)
{
$ldaprdn = $this->mPrdn . "\\" . $this->mUsername;
}
else
{
$ldaprdn = 'cn='.$this->mGroup.$this->mPrdn . "\\" . $this->mUsername;
}
$mConnected = ldap_bind($this->ldapConnection, $ldaprdn, $this->mPassword);
if ($mConnected)
{
$this->retrieveADEntry();
echo "Binded";
if ($this->mErrorCode == UNAUTHORIZED)
{
$this->mErrorCode = UNAUTHORIZED;
$this->mConnected = false;
}
else if ($this->mErrorCode == ERR_LOGIN_FAILED)
{
$this->mErrorCode = ERR_LOGIN_FAILED;
$this->mConnected = false;
}
else
{
$this->mErrorCode = SUCCESSFUL;
$this->mConnected = true;
if ($data->{"rlogcompanycode"} != ''){
$this->setCompanyCode(trim((string)$data->{"rlogcompanycode"}));
}
}
}
else
{
echo "Not binded";
$this->mErrorCode = ERR_LOGIN_FAILED;
$this->mConnected = false;
}
return $this->mConnected;
}
else{
$this->mErrorCode = ERR_CONNECTION_FAILED;
$this->mConnected = false;
return false;
}
error_reporting(E_ALL);
}
private function retrieveADEntry()
{
//$ldap_base_dn = 'DC='.$this->mDC.',DC='.$this->mDomain;
$ldap_base_dn = "OU=group,DC=domain,DC=co,DC=za";
$filter = "";
$attr = array(
$this->mField,
"sAMAccountName",
);
$filter .="(sAMAccountName=$this->mUsername)";
$search_results = ldap_search($this->ldapConnection,$ldap_base_dn, $filter);
//For each account returned by the search
if (FALSE !== $search_results ){
$entries = ldap_get_entries($this->ldapConnection, $search_results);
$values = ldap_get_values($this->ldapConnection,$search_results, $attr);
$access = 0;
//For each account returned by the search
echo "succesfull query";
echo $entries['count'];
echo $this->mUsername;
var_dump($values);
for ($x=0; $x<$entries['count']; $x++)
{
echo "in loop";
var_dump($entries);
if (strpos( $entries[$x]['memberof'][0], $this->mGroup)) //Check if member is part of specified group
{
echo "GroupCheck1";
$access = 1;
$group = $this->mGroup;
}
if ($this->mGroup == null)
{
echo "GroupCheck2";
$access = 1;
}
echo "PostGroupChecks";
echo $access;
if ($access != 0)
{
echo "access";
echo $this->mField;
echo $entries[$x]['sAMAccountName'][0];
if (!empty($entries[$x][$this->mField][0]))
{
$this->setEmpkey($entries[$x][$this->mField][0]);
echo $entries[$x][$this->mField][0];
}
echo "return succesfull";
$this->mConnected = true;
$this->mErrorCode = SUCCESSFUL;
}
else
{
echo "No Access";
$this->mConnected = false;
$this->mErrorCode = UNAUTHORIZED;
} //END for loop
}
//END FALSE !== $result
ldap_unbind($ldap_connection); // Clean up after ourselves.
}
else
{
$this->mConnected = false;
$this->mErrorCode = ERR_LOGIN_FAILED;
}
return $this->ldapEntry;
}
PS. I also wrote a C# script for our desktop app which works perfectly fine on this system just like on all the rest and doesn't give this issue

php whois stopped working on another server

I am using this whois class, it works fine on one server but it does not work properly on another server with the same PHP version 5.4, on first server it returns domain name status correctly, but on the other one it returns just one status: "domain name is not available" while the domain name is actually available.
<?
class Whois_domain {
var $possible_tlds;
var $whois_server;
var $free_string;
var $whois_param;
var $domain;
var $tld;
var $compl_domain;
var $full_info;
var $msg;
var $info;
var $os_system = "linux"; // switch between "linux" and "win"
function Whois_domain() {
$this->info = "";
$this->msg = "";
}
function process() {
if ($this->create_domain()) {
if ($this->full_info == "yes") {
$this->get_domain_info();
} else {
if ($this->check_only() == 1) {
$this->msg = "The domain name: <b>".$this->compl_domain."</b> is free.";
return true;
} elseif ($this->check_only() == 0) {
$this->msg = "The domain name: <b>".$this->compl_domain."</b> is not available";
return false;
} else {
$this->msg = "There was something wrong, try it again.";
}
}
} else {
$this->msg = "Only letters, numbers and hyphens (-) are valid!";
}
}
function check_entry() {
if (preg_match("/^([a-z0-9]+(\-?[a-z0-9]*)){2,63}$/i", $this->domain)) {
return true;
} else {
return false;
}
}
function create_tld_select() {
$menu = "<select name=\"tld\" style=\"margin-left:0;\">\n";
foreach ($this->possible_tlds as $val) {
$menu .= " <option value=\"".$val."\"";
$menu .= (isset($_POST['tld']) && $_POST['tld'] == $val) ? " selected=\"selected\">" : ">";
$menu .= $val."</option>\n";
}
$menu .= "</select>\n";
return $menu;
}
function create_domain() {
if ($this->check_entry()) {
$this->domain = strtolower($this->domain);
$this->compl_domain = $this->domain.".".$this->tld;
return true;
} else {
return false;
}
}
function check_only() {
$data = $this->get_whois_data();
if (is_array($data)) {
$found = 0;
foreach ($data as $val) {
if (eregi($this->free_string, $val)) {
$found = 1;
}
}
return $found;
} else {
$this->msg = "Error, please try it again.";
}
}
function get_domain_info() {
if ($this->create_domain()) {
$data = ($this->tld == "nl") ? $this->get_whois_data(true) : $this->get_whois_data();
if (is_array($data)) {
foreach ($data as $val) {
if (eregi($this->free_string, $val)) {
$this->msg = "The domain name: <b>".$this->compl_domain."</b> is free.";
$this->info = "";
break;
}
$this->info .= $val;
}
} else {
$this->msg = "Error, please try it again.";
}
} else {
$this->msg = "Only letters, numbers and hyphens (-) are valid!";
}
}
function get_whois_data($empty_param = false) {
// the parameter is new since version 1.20 and is used for .nl (dutch) domains only
if ($empty_param) {
$this->whois_param = "";
}
if ($this->tld == "de") $this->os_system = "win"; // this tld must be queried with fsock otherwise it will not work
if ($this->os_system == "win") {
$connection = #fsockopen($this->whois_server, 43);
if (!$connection) {
unset($connection);
$this->msg = "Can't connect to the server!";
return;
} else {
sleep(2);
fputs($connection, $this->whois_param.$this->compl_domain."\r\n");
while (!feof($connection)) {
$buffer[] = fgets($connection, 4096);
}
fclose($connection);
}
} else {
$string = "whois -h ".$this->whois_server." \"".$this->whois_param.$this->compl_domain."\"";
$string = str_replace (";", "", $string).";";
exec($string, $buffer);
}
if (isset($buffer)) {
//print_r($buffer);
return $buffer;
} else {
$this->msg = "Can't retrieve data from the server!";
}
}
}
?>
I changed files permissions and php versions on the other server, but still the same.
This has been solved, it was fsockopen restrictions on the server, it is fine now.

PHPMailer multiple attachments with one input button

I'm trying to make a contact form that is capable of multiple image attachments.
I got the contact form from here and everything's working fine. I really want to add the ability to attach more than one image within a single input element.
At the top of the contact form is this php:
<?PHP
require_once("./include/fgcontactform.php");
$formproc = new FGContactForm();
$formproc->AddRecipient('****#****.com');
$formproc->SetFormRandomKey('************');
$formproc->AddFileUploadField('photo','jpg,jpeg,gif,png,bmp',4000);
if(isset($_POST['submitted']))
{
if($formproc->ProcessForm())
{
$formproc->RedirectToURL("thank-you.php");
}
}
?>
This is the html for the form (I've cut it down so its only the upload portion of the form):
<html>
<head>
<script type='text/javascript' src='scripts/gen_validatorv31.js'></script>
<script type='text/javascript' src='scripts/fg_captcha_validator.js'></script>
</head>
<body>
<form id='contactus' action='<?php echo $formproc->GetSelfScript(); ?>' method='post' enctype="multipart/form-data" accept-charset='UTF-8'>
<h4><label for='photo' >Please upload your images:</label><br/>
<input type="file" name='photo' id='photo' multiple="multiple"/><br/>
<span style="color:#999999;font-size:12px;">(To select more than 1 image hold the "CTRL" key as you click. If you're on Mac hold the "cmd" key.)</span><br/></h4>
<span id='contactus_photo_errorloc' class='error'></span>
</form>
<script type='text/javascript'>
// <![CDATA[
var frmvalidator = new Validator("contactus");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email address");
frmvalidator.addValidation("email","email","Please provide a valid email address");
frmvalidator.addValidation("message","maxlen=2048","The message is too long!(more than 2KB!)");
frmvalidator.addValidation("photo","file_extn=jpg;jpeg;gif;png;bmp","Upload images only. Supported file types are: jpg,gif,png,bmp");
// ]]>
</script>
</body>
</html>
I have managed to get multiple image uploads working by adding the following to the top of the initial PHP and adding new input elements within the html with the relevant names:
$formproc->AddFileUploadField('photo2','jpg,jpeg,gif,png,bmp',4000);
$formproc->AddFileUploadField('photo3','jpg,jpeg,gif,png,bmp',4000);
$formproc->AddFileUploadField('photo4','jpg,jpeg,gif,png,bmp',4000);
$formproc->AddFileUploadField('photo5','jpg,jpeg,gif,png,bmp',4000);
Although this works I'd much prefer to have only one input button and allow people to attach multiple images with it (with a max of around 10, but that's an issue for another time).
I believe this is the php that composes the email if that helps:
<?PHP
require_once("class.phpmailer.php");
class FG_CaptchaHandler
{
function Validate() { return false;}
function GetError(){ return '';}
}
class FGContactForm
{
var $receipients;
var $errors;
var $error_message;
var $name;
var $email;
var $message;
var $from_address;
var $form_random_key;
var $conditional_field;
var $arr_conditional_receipients;
var $fileupload_fields;
var $captcha_handler;
var $mailer;
function FGContactForm()
{
$this->receipients = array();
$this->errors = array();
$this->form_random_key = 'HTgsjhartag';
$this->conditional_field='';
$this->arr_conditional_receipients=array();
$this->fileupload_fields=array();
$this->mailer = new PHPMailer();
$this->mailer->CharSet = 'utf-8';
}
function EnableCaptcha($captcha_handler)
{
$this->captcha_handler = $captcha_handler;
session_start();
}
function AddRecipient($email,$name="")
{
$this->mailer->AddAddress($email,$name);
}
function SetFromAddress($from)
{
$this->from_address = $from;
}
function SetFormRandomKey($key)
{
$this->form_random_key = $key;
}
function GetSpamTrapInputName()
{
return 'sp'.md5('KHGdnbvsgst'.$this->GetKey());
}
function SafeDisplay($value_name)
{
if(empty($_POST[$value_name]))
{
return'';
}
return htmlentities($_POST[$value_name]);
}
function GetFormIDInputName()
{
$rand = md5('TygshRt'.$this->GetKey());
$rand = substr($rand,0,20);
return 'id'.$rand;
}
function GetFormIDInputValue()
{
return md5('jhgahTsajhg'.$this->GetKey());
}
function SetConditionalField($field)
{
$this->conditional_field = $field;
}
function AddConditionalReceipent($value,$email)
{
$this->arr_conditional_receipients[$value] = $email;
}
function AddFileUploadField($file_field_name,$accepted_types,$max_size)
{
$this->fileupload_fields[] =
array("name"=>$file_field_name,
"file_types"=>$accepted_types,
"maxsize"=>$max_size);
}
function ProcessForm()
{
if(!isset($_POST['submitted']))
{
return false;
}
if(!$this->Validate())
{
$this->error_message = implode('<br/>',$this->errors);
return false;
}
$this->CollectData();
$ret = $this->SendFormSubmission();
return $ret;
}
function RedirectToURL($url)
{
header("Location: $url");
exit;
}
function GetErrorMessage()
{
return $this->error_message;
}
function GetSelfScript()
{
return htmlentities($_SERVER['PHP_SELF']);
}
function GetName()
{
return $this->name;
}
function GetEmail()
{
return $this->email;
}
function GetMessage()
{
return htmlentities($this->message,ENT_QUOTES,"UTF-8");
}
function SendFormSubmission()
{
$this->CollectConditionalReceipients();
$this->mailer->CharSet = 'utf-8';
$this->mailer->Subject = "Customer installation competition submition from $this->name";
$this->mailer->From = $this->GetFromAddress();
$this->mailer->FromName = $this->name;
$this->mailer->AddReplyTo($this->email);
$message = $this->ComposeFormtoEmail();
$textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$message)));
$this->mailer->AltBody = #html_entity_decode($textMsg,ENT_QUOTES,"UTF-8");
$this->mailer->MsgHTML($message);
$this->AttachFiles();
if(!$this->mailer->Send())
{
$this->add_error("Failed sending email!");
return false;
}
return true;
}
function CollectConditionalReceipients()
{
if(count($this->arr_conditional_receipients)>0 &&
!empty($this->conditional_field) &&
!empty($_POST[$this->conditional_field]))
{
foreach($this->arr_conditional_receipients as $condn => $rec)
{
if(strcasecmp($condn,$_POST[$this->conditional_field])==0 &&
!empty($rec))
{
$this->AddRecipient($rec);
}
}
}
}
function IsInternalVariable($varname)
{
$arr_interanl_vars = array('scaptcha',
'submitted',
$this->GetSpamTrapInputName(),
$this->GetFormIDInputName()
);
if(in_array($varname,$arr_interanl_vars))
{
return true;
}
return false;
}
function FormSubmissionToMail()
{
$ret_str='';
foreach($_POST as $key=>$value)
{
if(!$this->IsInternalVariable($key))
{
$value = htmlentities($value,ENT_QUOTES,"UTF-8");
$value = nl2br($value);
$key = ucfirst($key);
$ret_str .= "<div class='label'>$key :</div><div class='value'>$value </div>\n";
}
}
foreach($this->fileupload_fields as $upload_field)
{
$field_name = $upload_field["name"];
if(!$this->IsFileUploaded($field_name))
{
continue;
}
$filename = basename($_FILES[$field_name]['name']);
$ret_str .= "<div class='label'>File upload '$field_name' :</div><div class='value'>$filename </div>\n";
}
return $ret_str;
}
function ExtraInfoToMail()
{
$ret_str='';
$ip = $_SERVER['REMOTE_ADDR'];
$ret_str = "<div class='label'>IP address of the submitter:</div><div class='value'>$ip</div>\n";
return $ret_str;
}
function GetMailStyle()
{
$retstr = "\n<style>".
"body,.label,.value { font-family:Arial,Verdana; } ".
".label {font-weight:bold; margin-top:5px; font-size:1em; color:#333;} ".
".value {margin-bottom:15px;font-size:0.8em;padding-left:5px;} ".
"</style>\n";
return $retstr;
}
function GetHTMLHeaderPart()
{
$retstr = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">'."\n".
'<html><head><title></title>'.
'<meta http-equiv=Content-Type content="text/html; charset=utf-8">';
$retstr .= $this->GetMailStyle();
$retstr .= '</head><body>';
return $retstr;
}
function GetHTMLFooterPart()
{
$retstr ='</body></html>';
return $retstr ;
}
function ComposeFormtoEmail()
{
$header = $this->GetHTMLHeaderPart();
$formsubmission = $this->FormSubmissionToMail();
$extra_info = $this->ExtraInfoToMail();
$footer = $this->GetHTMLFooterPart();
$message = $header."Submission details:<p>$formsubmission</p><hr/>$extra_info".$footer;
return $message;
}
function AttachFiles()
{
foreach($this->fileupload_fields as $upld_field)
{
$field_name = $upld_field["name"];
if(!$this->IsFileUploaded($field_name))
{
continue;
}
$filename =basename($_FILES[$field_name]['name']);
$this->mailer->AddAttachment($_FILES[$field_name]["tmp_name"],$filename);
}
}
function GetFromAddress()
{
if(!empty($this->from_address))
{
return $this->from_address;
}
$host = $_SERVER['SERVER_NAME'];
$from ="nobody#$host";
return $from;
}
function Validate()
{
$ret = true;
if(empty($_POST[$this->GetFormIDInputName()]) ||
$_POST[$this->GetFormIDInputName()] != $this->GetFormIDInputValue() )
{
$this->add_error("Automated submission prevention: case 1 failed");
$ret = false;
}
if(!empty($_POST[$this->GetSpamTrapInputName()]) )
{
$this->add_error("Automated submission prevention: case 2 failed");
$ret = false;
}
if(empty($_POST['name']))
{
$this->add_error("Please provide your name");
$ret = false;
}
else
if(strlen($_POST['name'])>50)
{
$this->add_error("Name is too big!");
$ret = false;
}
if(empty($_POST['email']))
{
$this->add_error("Please provide your email address");
$ret = false;
}
else
if(strlen($_POST['email'])>50)
{
$this->add_error("Email address is too big!");
$ret = false;
}
else
if(!$this->validate_email($_POST['email']))
{
$this->add_error("Please provide a valid email address");
$ret = false;
}
if(strlen($_POST['message'])>2048)
{
$this->add_error("Message is too big!");
$ret = false;
}
if(isset($this->captcha_handler))
{
if(!$this->captcha_handler->Validate())
{
$this->add_error($this->captcha_handler->GetError());
$ret = false;
}
}
if(!empty($this->fileupload_fields))
{
if(!$this->ValidateFileUploads())
{
$ret = false;
}
}
return $ret;
}
function ValidateFileType($field_name,$valid_filetypes)
{
$ret=true;
$info = pathinfo($_FILES[$field_name]['name']);
$extn = $info['extension'];
$extn = strtolower($extn);
$arr_valid_filetypes= explode(',',$valid_filetypes);
if(!in_array($extn,$arr_valid_filetypes))
{
$this->add_error("Valid file types are: $valid_filetypes");
$ret=false;
}
return $ret;
}
function ValidateFileSize($field_name,$max_size)
{
$size_of_uploaded_file =
$_FILES[$field_name]["size"]/2048;//size in KBs
if($size_of_uploaded_file > $max_size)
{
$this->add_error("The file is too big. File size should be less than $max_size KB");
return false;
}
return true;
}
function IsFileUploaded($field_name)
{
if(empty($_FILES[$field_name]['name']))
{
return false;
}
if(!is_uploaded_file($_FILES[$field_name]['tmp_name']))
{
return false;
}
return true;
}
function ValidateFileUploads()
{
$ret=true;
foreach($this->fileupload_fields as $upld_field)
{
$field_name = $upld_field["name"];
$valid_filetypes = $upld_field["file_types"];
if(!$this->IsFileUploaded($field_name))
{
continue;
}
if($_FILES[$field_name]["error"] != 0)
{
$this->add_error("Error in file upload; Error code:".$_FILES[$field_name]["error"]);
$ret=false;
}
if(!empty($valid_filetypes) &&
!$this->ValidateFileType($field_name,$valid_filetypes))
{
$ret=false;
}
if(!empty($upld_field["maxsize"]) &&
$upld_field["maxsize"]>0)
{
if(!$this->ValidateFileSize($field_name,$upld_field["maxsize"]))
{
$ret=false;
}
}
}
return $ret;
}
function StripSlashes($str)
{
if(get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return $str;
}
function Sanitize($str,$remove_nl=true)
{
$str = $this->StripSlashes($str);
if($remove_nl)
{
$injections = array('/(\n+)/i',
'/(\r+)/i',
'/(\t+)/i',
'/(%0A+)/i',
'/(%0D+)/i',
'/(%08+)/i',
'/(%09+)/i'
);
$str = preg_replace($injections,'',$str);
}
return $str;
}
function CollectData()
{
$this->name = $this->Sanitize($_POST['name']);
$this->email = $this->Sanitize($_POST['email']);
$this->message = $this->StripSlashes($_POST['message']);
}
function add_error($error)
{
array_push($this->errors,$error);
}
function validate_email($email)
{
return eregi("^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $email);
}
function GetKey()
{
return $this->form_random_key.$_SERVER['SERVER_NAME'].$_SERVER['REMOTE_ADDR'];
}
}
?>
What I do for multiple file/pictures upload is to use an IFRAME for a hidden form, with a file input that would get triggered once you press a button that you can include in your original form. The form is submitted in the iframe (therefore doesn't reload your page) and uploads the files, you can get files' details and add them with javascript to your form (ex. pic1.jpg uploaded, pic2.png uploaded...) I have a code sample, but I'll have to look for it a bit, so try and come up with the code yourself following this strategy.

PHP mail Form redirect URL doesn't work. Webpage is here. (Tried other "SOF" answers)

first of all, I have to say this.I used "Wix" for my website but since it doesn't have function to [img] tag with percentage width.So now I have started making my own website, and that's about 1month ago, when I only knew how to [img src], without any other html knowledge. I forced myself to make this myself so I can make my website exactly as what I want, and now it seems almost done as I uploaded on my hosting server.
The problem is, in my 'order page', after filling out the form, and press 'submit button', it doesn't show the page I attended to show. Just turns out to the first part of order page.
the code I tried is
if(isset($_POST['submitted']))
{
if($formproc->ProcessForm())
{
$formproc->RedirectToURL("http://ljhbunkercom.ipage.com/index/thank-you.php");
}
when fully filled form gets submitted with the submit button, it really sends every information to my mailbox, but thank-you.php doesn't show up.
I tried
if(isset($_POST['submitted']))
{
if($formproc->ProcessForm())
{
$formproc->header("Location: http://ljhbunkercom.ipage.com/index/thank-you.php");
}
( the change is , redirect url -> header location.)
and also, not showing the thank-you page.
I modified free open email form source into my own order page, by combining another open source.
-->http://www.sanwebe.com/2014/04/ajax-contact-form-attachment-jquery-php
this is the source I used, but this works so fine. when filled out all the input text box and pressed the submit button, it shows the thank-you.php.
I think I did something wrong, when I modified it.
I remember I changed this,
htmlentities-> htmlspecialchars
but I don't think this really does that effect.
please help .
My web orderpage is this .
http://ljhbunkercom.ipage.com/index/order.php
(! please do not hack my webpage. )
****What is the problem, and how can I make it show the thank-you.php page when required information have been submitted??****
============== The form class==========
class FG_CaptchaHandler
{
function Validate() { return false;}
function GetError(){ return '';}
}
/*
FGContactForm is a general purpose contact form class
It supports Captcha, HTML Emails, sending emails
conditionally, File atachments and more.
*/
class FGContactForm
{
var $receipients;
var $errors;
var $error_message;
var $name;
var $email;
var $message;
var $from_address;
var $form_random_key;
var $conditional_field;
var $arr_conditional_receipients;
var $fileupload_fields;
var $captcha_handler;
var $mailer;
function FGContactForm()
{
$this->receipients = array();
$this->errors = array();
$this->form_random_key = 'xxxxxxx';
$this->conditional_field='';
$this->arr_conditional_receipients=array();
$this->fileupload_fields=array();
$this->mailer = new PHPMailer();
$this->mailer->CharSet = 'utf-8';
}
function EnableCaptcha($captcha_handler)
{
$this->captcha_handler = $captcha_handler;
session_start();
}
function AddRecipient($email,$name="")
{
$this->mailer->AddAddress($email,$name);
}
function SetFromAddress($from)
{
$this->from_address = $from;
}
function SetFormRandomKey($key)
{
$this->form_random_key = $key;
}
function GetSpamTrapInputName()
{
return 'sp'.md5('xxxxxxxxx'.$this->GetKey());
}
function SafeDisplay($value_name)
{
if(empty($_POST[$value_name]))
{
return'';
}
return htmlspecialchars($_POST[$value_name]);
}
function GetFormIDInputName()
{
$rand = md5('xxxxxxx'.$this->GetKey());
$rand = substr($rand,0,20);
return 'id'.$rand;
}
function GetFormIDInputValue()
{
return md5('xxxxxxx'.$this->GetKey());
}
function SetConditionalField($field)
{
$this->conditional_field = $field;
}
function AddConditionalReceipent($value,$email)
{
$this->arr_conditional_receipients[$value] = $email;
}
function AddFileUploadField($file_field_name,$accepted_types,$max_size)
{
$this->fileupload_fields[] =
array("name"=>$file_field_name,
"file_types"=>$accepted_types,
"maxsize"=>$max_size);
}
function ProcessForm()
{
if(!isset($_POST['submitted']))
{
return false;
}
if(!$this->Validate())
{
$this->error_message = implode('<br/>',$this->errors);
return false;
}
$this->CollectData();
$ret = $this->SendFormSubmission();
return $ret;
}
function RedirectToURL($url)
{
header("Location: $url");
exit;
}
function GetErrorMessage()
{
return $this->error_message;
}
function GetSelfScript()
{
return htmlspecialchars($_SERVER['PHP_SELF']);
}
function GetName()
{
return $this->name;
}
function GetEmail()
{
return $this->email;
}
function GetMessage()
{
return htmlspecialchars($this->message,ENT_QUOTES,"UTF-8");
}
/*-------- Private (Internal) Functions -------- */
function SendFormSubmission()
{
$this->CollectConditionalReceipients();
$this->mailer->CharSet = 'utf-8';
$this->mailer->Subject = "Contact form submission from $this->name";
$this->mailer->From = $this->GetFromAddress();
$this->mailer->FromName = $this->name;
$this->mailer->AddReplyTo($this->email);
$message = $this->ComposeFormtoEmail();
$textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$message)));
$this->mailer->AltBody = #html_entity_decode($textMsg,ENT_QUOTES,"UTF-8");
$this->mailer->MsgHTML($message);
$this->AttachFiles();
if(!$this->mailer->Send())
{
$this->add_error("알수없는 이유로 메일보내기가 실패하였습니다. LJHBUNKER#LJHBUNKER.COM 으로 연락주시길 바랍니다!");
return false;
}
return true;
}
function CollectConditionalReceipients()
{
if(count($this->arr_conditional_receipients)>0 &&
!empty($this->conditional_field) &&
!empty($_POST[$this->conditional_field]))
{
foreach($this->arr_conditional_receipients as $condn => $rec)
{
if(strcasecmp($condn,$_POST[$this->conditional_field])==0 &&
!empty($rec))
{
$this->AddRecipient($rec);
}
}
}
}
/*
Internal variables, that you donot want to appear in the email
Add those variables in this array.
*/
function IsInternalVariable($varname)
{
$arr_interanl_vars = array('scaptcha',
'submitted',
$this->GetSpamTrapInputName(),
$this->GetFormIDInputName()
);
if(in_array($varname,$arr_interanl_vars))
{
return true;
}
return false;
}
function FormSubmissionToMail()
{
$ret_str='';
foreach($_POST as $key=>$value)
{
if(!$this->IsInternalVariable($key))
{
$value = htmlspecialchars($value,ENT_QUOTES,"UTF-8");
$value = nl2br($value);
$key = ucfirst($key);
$ret_str .= "<div class='label'>$key :</div><div class='value'>$value </div>\n";
}
}
foreach($this->fileupload_fields as $upload_field)
{
$field_name = $upload_field["name"];
if(!$this->IsFileUploaded($field_name))
{
continue;
}
$filename = basename($_FILES[$field_name]['name']);
$ret_str .= "<div class='label'>File upload '$field_name' :</div><div class='value'>$filename </div>\n";
}
return $ret_str;
}
function ExtraInfoToMail()
{
$ret_str='';
$ip = $_SERVER['REMOTE_ADDR'];
$ret_str = "<div class='label'>IP address of the submitter:</div><div class='value'>$ip</div>\n";
return $ret_str;
}
function GetMailStyle()
{
$retstr = "\n<style>".
"body,.label,.value { font-family:Arial,Verdana; } ".
".label {font-weight:bold; margin-top:5px; font-size:1em; color:#333;} ".
".value {margin-bottom:15px;font-size:0.8em;padding-left:5px;} ".
"</style>\n";
return $retstr;
}
function GetHTMLHeaderPart()
{
$retstr = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">'."\n".
'<html><head><title></title>'.
'<meta http-equiv=Content-Type content="text/html; charset=utf-8">';
$retstr .= $this->GetMailStyle();
$retstr .= '</head><body>';
return $retstr;
}
function GetHTMLFooterPart()
{
$retstr ='</body></html>';
return $retstr ;
}
function ComposeFormtoEmail()
{
$header = $this->GetHTMLHeaderPart();
$formsubmission = $this->FormSubmissionToMail();
$extra_info = $this->ExtraInfoToMail();
$footer = $this->GetHTMLFooterPart();
$message = $header."Submission from 'contact us' form:<p>$formsubmission</p><hr/>$extra_info".$footer;
return $message;
}
function AttachFiles()
{
foreach($this->fileupload_fields as $upld_field)
{
$field_name = $upld_field["name"];
if(!$this->IsFileUploaded($field_name))
{
continue;
}
$filename =basename($_FILES[$field_name]['name']);
$this->mailer->AddAttachment($_FILES[$field_name]["tmp_name"],$filename);
}
}
function GetFromAddress()
{
if(!empty($this->from_address))
{
return $this->from_address;
}
$host = $_SERVER['SERVER_NAME'];
$from ="nobody#$host";
return $from;
}
function Validate()
{
$ret = true;
//security validations
if(empty($_POST[$this->GetFormIDInputName()]) ||
$_POST[$this->GetFormIDInputName()] != $this->GetFormIDInputValue() )
{
//The proper error is not given intentionally
$this->add_error("Automated submission prevention: case 1 failed");
$ret = false;
}
//This is a hidden input field. Humans won't fill this field.
if(!empty($_POST[$this->GetSpamTrapInputName()]) )
{
//The proper error is not given intentionally
$this->add_error("Automated submission prevention: case 2 failed");
$ret = false;
}
//name validations
if(empty($_POST['name']))
{
$this->add_error(" 이름을 기재하여주세요! ");
$ret = false;
}
else
if(strlen($_POST['name'])>50)
{
$this->add_error(" 이름을 정확히 기재하여 주세요! ");
$ret = false;
}
//email validations
if(empty($_POST['email']))
{
$this->add_error(" E-mail 주소가 입력되지 않았습니다! ");
$ret = false;
}
else
if(strlen($_POST['email'])>50)
{
$this->add_error(" 올바른 E-mail 주소를 “정확히” 입력하여주세요! ");
$ret = false;
}
else
if(!$this->validate_email($_POST['email']))
{
$this->add_error(" 올바른 E-mail 주소를 “정확히” 입력하여주세요! ");
$ret = false;
}
//check validations
if(empty($_POST['message0']))
{
$this->add_error(" 용도를 기입하여 주세요! ");
$ret = false;
}
//message validaions
if(strlen($_POST['message2'])>2048)
{
$this->add_error(" 추가 코멘트가 너무 깁니다! 500자 이내의 분량만 수용이 가능합니다. ");
$ret = false;
}
//file validations
if($_FILES['photo']['size'] == 0 )
{
$this->add_error(" 스케치가 첨부되지 않았습니다! ");
$ret = false;
}
//check validations
if(empty($_POST['check']))
{
$this->add_error(" 커스텀 일러스트 Type을 선택하여주세요! ");
$ret = false;
}
//captcha validaions
if(isset($this->captcha_handler))
{
if(!$this->captcha_handler->Validate())
{
$this->add_error($this->captcha_handler->GetError());
$ret = false;
}
}
//file upload validations
if(!empty($this->fileupload_fields))
{
if(!$this->ValidateFileUploads())
{
$ret = false;
}
}
return $ret;
}
function ValidateFileType($field_name,$valid_filetypes)
{
$ret=true;
$info = pathinfo($_FILES[$field_name]['name']);
$extn = $info['extension'];
$extn = strtolower($extn);
$arr_valid_filetypes= explode(',',$valid_filetypes);
if(!in_array($extn,$arr_valid_filetypes))
{
$this->add_error("Valid file types are: $valid_filetypes");
$ret=false;
}
return $ret;
}
function ValidateFileSize($field_name,$max_size)
{
$size_of_uploaded_file =
$_FILES[$field_name]["size"]/4096;//size in KBs
if($size_of_uploaded_file > $max_size)
{
$this->add_error("스케치파일의 용량이 너무 큽니다! (4메가 초과) ");
return false;
}
return true;
}
function IsFileUploaded($field_name)
{
if(empty($_FILES[$field_name]['name']))
{
return false;
}
if(!is_uploaded_file($_FILES[$field_name]['tmp_name']))
{
return false;
}
return true;
}
function ValidateFileUploads()
{
$ret=true;
foreach($this->fileupload_fields as $upld_field)
{
$field_name = $upld_field["name"];
$valid_filetypes = $upld_field["file_types"];
if(!$this->IsFileUploaded($field_name))
{
continue;
}
if($_FILES[$field_name]["error"] != 0)
{
$this->add_error("Error in file upload; Error code:".$_FILES[$field_name]["error"]);
$ret=false;
}
if(!empty($valid_filetypes) &&
!$this->ValidateFileType($field_name,$valid_filetypes))
{
$ret=false;
}
if(!empty($upld_field["maxsize"]) &&
$upld_field["maxsize"]>0)
{
if(!$this->ValidateFileSize($field_name,$upld_field["maxsize"]))
{
$ret=false;
}
}
}
return $ret;
}
function StripSlashes($str)
{
if(get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return $str;
}
/*
Sanitize() function removes any potential threat from the
data submitted. Prevents email injections or any other hacker attempts.
if $remove_nl is true, newline chracters are removed from the input.
*/
function Sanitize($str,$remove_nl=true)
{
$str = $this->StripSlashes($str);
if($remove_nl)
{
$injections = array('/(\n+)/i',
'/(\r+)/i',
'/(\t+)/i',
'/(%0A+)/i',
'/(%0D+)/i',
'/(%08+)/i',
'/(%09+)/i'
);
$str = preg_replace($injections,'',$str);
}
return $str;
}
/*Collects clean data from the $_POST array and keeps in internal variables.*/
function CollectData()
{
$this->name = $this->Sanitize($_POST['name']);
$this->email = $this->Sanitize($_POST['email']);
$this->check = $this->Sanitize($_POST['check']);
/*newline is OK in the message.*/
$this->message0 = $this->StripSlashes($_POST['message0']);
$this->message2 = $this->StripSlashes($_POST['message2']);
}
function add_error($error)
{
array_push($this->errors,$error);
}
function validate_email($email)
{
return eregi("^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $email);
}
function GetKey()
{
return $this->form_random_key.$_SERVER['SERVER_NAME'].$_SERVER['REMOTE_ADDR'];
}
}
(Please Please let me know if I just wrote something that should be kept unshown on public..)

Am I using the PHP.js strpbrk function properly?

I have the following JS function:
function validatePass()
{
var oldPass = document.getElementById("oldpass").value;
var newPass1 = document.getElementById("newpass1").value;
var newPass2 = document.getElementById("newpass2").value;
if(strpbrk(newPass1,"abcdefghijklmnopqrstuvwxyz") != false)
{
document.getElementById("ContainsAtLeastOneLowercaseLetter").innerHTML = "<span id=\"green\">Met</span>";
}
else
{
document.getElementById("ContainsAtLeastOneLowercaseLetter").innerHTML = "<span id=\"red\">Not Met</span>";
}
if(strpbrk(newPass1,"ABCDEFGHIJKLMNOPQRSTUVWXYZ") != false)
{
document.getElementById("ContainsAtLeastOneUppercaseLetter").innerHTML = "<span id=\"green\">Met</span>";
}
else
{
document.getElementById("ContainsAtLeastOneUppercaseLetter").innerHTML = "<span id=\"red\">Not Met</span>";
}
if(strpbrk(newPass1,"1234567890") != false)
{
document.getElementById("ContainsAtLeastOneNumber").innerHTML = "<span id=\"green\">Met</span>";
}
else
{
document.getElementById("ContainsAtLeastOneNumber").innerHTML = "<span id=\"red\">Not Met</span>";
}
}
That code makes a call to the PHP.js function strpbrk to determine if newPass1 contains acceptable data. In PHP, strpbrk searches to see if the haystack contains any of the chars in the char_list. However, in this JS implementation, it searches for all of the chars. How can I make it behave the way I want to?
TIA.
I would suggest using regex instead of strpbrk.
function validatePass()
{
var oldPass = document.getElementById("oldpass").value;
var newPass1 = document.getElementById("newpass1").value;
var newPass2 = document.getElementById("newpass2").value;
if(/[a-z]/.test(newpass1))
{
document.getElementById("ContainsAtLeastOneLowercaseLetter").innerHTML = "<span id=\"green\">Met</span>";
}
else
{
document.getElementById("ContainsAtLeastOneLowercaseLetter").innerHTML = "<span id=\"red\">Not Met</span>";
}
if(/[A-Z]/.test(newpass1))
{
document.getElementById("ContainsAtLeastOneUppercaseLetter").innerHTML = "<span id=\"green\">Met</span>";
}
else
{
document.getElementById("ContainsAtLeastOneUppercaseLetter").innerHTML = "<span id=\"red\">Not Met</span>";
}
if(/[0-9]/.test(newpass1))
{
document.getElementById("ContainsAtLeastOneNumber").innerHTML = "<span id=\"green\">Met</span>";
}
else
{
document.getElementById("ContainsAtLeastOneNumber").innerHTML = "<span id=\"red\">Not Met</span>";
}
}

Categories