Get ID from ROW and include in a linkable result - PHP MYSQL - php

I have this code for a search engine. I need to make linkable the results, only in the column name, but when I add the code ALL the colums turns as a link.
Here is how the results looks like now: http://postimg.org/image/59y36mih7/
I need to construct the link for the column name in this way:
http://www.mysite.com/id, (coma included)
Can you help me how to make the query to get the info from id column and make only the results from name column clickable? I´m quite lost.
<?php
$MySQLPassword = "*****";
$HostName = "***";
$UserName = "***";
$Database = "****";
mysql_connect($HostName,$UserName,$MySQLPassword)
or die("ERROR: Could not connect to database!");
mysql_select_db($Database) or die("cannot select db");
$default_sort = 'ID';
$allowed_order = array ('name','description');
if (!isset ($_GET['order']) ||
!in_array ($_GET['order'], $allowed_order)) {
$order = $default_sort;
} else {
$order = $_GET['order'];
}
if (isset($_GET['keyword'])) {
if(!$_GET['keyword']) {
die('<p>Please enter a search term.</p>');
}
/////////////////////////HERE IS THE BEGINING OF CODE WHERE I THINK SHOULD BE THE PROBLEM ////////////////////////////
$tables = 'reports';
$return_fields = 'name organizer_id no_pages publication_date price';
$check_fields = 'name description';
$query_text = $_GET['keyword'];
$clean_query_text =cleanQuery($query_text);
$newquery=bq_simple ($return_fields, $tables, $check_fields, $clean_query_text);
$newquery = $newquery . " ORDER BY $order;";
$result = mysql_query($newquery) or die(mysql_error());
$numrows = mysql_num_rows($result);
if ($numrows == 0) {
echo "<H4>No data to display!</H4>";
exit;
}
echo "<p>Your search '$query_text' returned ".$numrows. " results.</p>\n";
echo "<p>Click on the headings to sort.</p>\n";
$row = mysql_fetch_assoc ($result);
echo "<TABLE border=1>\n";
echo "<TR>\n";
foreach ($row as $heading=>$column) {
echo "<TD><b>";
if (in_array ($heading, $allowed_order)) {
echo "$heading";
} else {
echo $heading;
}
echo "</b></TD>\n";
}
echo "</TR>\n";
/* reset the $result set back to the first row and
* display the data */
mysql_data_seek ($result, 0);
while ($row = mysql_fetch_assoc ($result)) {
echo "<TR>\n";
foreach ($row as $column) {
echo "<TD><a href='http://mysite.com/(here should be the ID)'>$column</TD>\n";
}
echo "</TR>\n";
}
echo "</TABLE>\n";
}
////////////////////////FINISH OF THE CODE WITH PROBLEM ////////////////////////////
/* * * * * * * * * * * * * * F U N C T I O N S * * * * * * * * * * * */
function cleanQuery($string)
{
$string = trim($string);
$string = strip_tags($string); // remove any html/javascript.
if(get_magic_quotes_gpc()) // prevents duplicate backslashes
{
$string = stripslashes($string);
}
if (phpversion() >= '4.3.0')
{
$string = mysql_real_escape_string($string);
}
else
{
$string = mysql_escape_string($string);
}
return $string;
}
function bq_handle_shorthand($text) {
$text = preg_replace("/ \+/", " and ", $text);
$text = preg_replace("/ -/", " not ", $text);
return $text;
}
function bq_explode_respect_quotes($line) {
$quote_level = 0; #keep track if we are in or out of quote-space
$buffer = "";
for ($a = 0; $a < strlen($line); $a++) {
if ($line[$a] == "\"") {
$quote_level++;
if ($quote_level == 2) { $quote_level = 0; }
}
else {
if ($line[$a] == " " and $quote_level == 0) {
$buffer = $buffer . "~~~~"; #Hackish magic key
}
else {
$buffer = $buffer . $line[$a];
}
}
}
$buffer = str_replace("\\", "", $buffer);
$array = explode("~~~~", $buffer);
return $array;
}
function bq_make_subquery($fields, $word, $mode) {
if ($mode == "not") {
$back = " LIKE '%$word%'))";
}
else {
$back = " LIKE '%$word%')";
}
if ($mode == "not") {
$front = "(NOT (";
$glue = " LIKE '%$word%' AND ";
}
else {
$front = "(";
$glue = " LIKE '%$word%' AND ";
}
$text = str_replace(" ", $glue, $fields);
$text = $front . $text . $back;
return $text;
}
function bq_make_query($fields, $text) {
$text = strtolower($text);
$text = bq_handle_shorthand($text);
$wordarray = bq_explode_respect_quotes($text);
$buffer = "";
$output = "";
for ($i = 0; $i<count($wordarray); $i++) {
$word = $wordarray[$i];
if ($word == "and" or $word == "not" and $i > 0) {
if ($word == "not") {
$i++;
if ($i == 1) { #invalid sql syntax to prefix the first check with and/or/not
$buffer = bq_make_subquery($fields, $wordarray[$i], "not");
}
else {
$buffer = " AND " . bq_make_subquery($fields, $wordarray[$i], "not");
}
}
else {
if ($word == "and") {
$i++;
if ($i == 1) {
$buffer = bq_make_subquery($fields, $wordarray[$i], "");
}
else {
$buffer = " AND " . bq_make_subquery($fields, $wordarray[$i], "");
}
}
else {
if ($word == "and") {
$i++;
if ($i == 1) {
$buffer = bq_make_subquery($fields, $wordarray[$i], "");
}
else {
$buffer = " AND " . bq_make_subquery($fields, $wordarray[$i], "");
}
}
}
}
}
else {
if ($i == 0) { # 0 instead of 1 here because there was no conditional word to skip and no $i++;
$buffer = bq_make_subquery($fields, $wordarray[$i], "");
}
else {
$buffer = " AND " . bq_make_subquery($fields, $wordarray[$i], "");
}
}
$output = $output . $buffer;
}
return $output;
}
function bq_simple ($return_fields, $tables, $check_fields, $query_text) {
$return_fields = str_replace(" ", ", ", $return_fields);
$tables = str_replace(" ", ", ", $tables);
$query = "SELECT $return_fields FROM $tables WHERE ";
$query = $query . bq_make_query($check_fields, $query_text);
#
# Uncomment to debug
#
return $query;
}
?>

I'm not going to dig through your code completely, but you should delete your ID column and whatever variable is being used for ID(such as $id) should be formatted like this where your name column is printed.
"<?PHP echo $name ?>"

Related

Write single element of array to fwrite file

I'm trying to return an array from MyArray function and use [0] to write2file and use [1] to populate pushover(myArray($jason)). I have tried fwrite($myfile, echo $txt[0]); but this fails and only writes the word 'Array' to the file instead of contents of array. I've looked at print_r and implode but no luck.
write2file(myArray($json));
compare2files('old_version.txt', 'new_version.txt');
if (compare2files('old_version.txt', 'new_version.txt') == 'false') {
pushover(implode("\n",myArray($json)[1]));
rename("new_version.txt", "old_version.txt");
}
function write2file($txt) {
$myfile = fopen("new_version.txt", "w") or die("Unable to open file!");
fwrite($myfile, implode("\n",$txt[0]));
fclose($myfile);
}
function compare2files($file1, $file2) {
$file3 = file_get_contents($file1);
$file4 = file_get_contents($file2);
if (strcmp($file3, $file4) !== 0) {
return 'false';
}
}
function myArray($arry) {
$selected = array(5,6,7,10,12,15,17,18,22,24);
foreach($arry as $key => $value) {
if (in_array($key, $selected) || empty($selected)) {
$result .= $value['name']. chr(10);
$xTime .= $value['name']. chr(10);
$length = count($value["color"]);
for ($i = 0; $i < $length; $i++) {
if($value['time'][$i] != "") {
if(preg_match('/#ff0000/', $value['color'][$i])) {
$value['color'][$i] = 'RED';
}
if(preg_match('/#ffff00/', $value['color'][$i])) {
$value['color'][$i] = 'YELLOW';
}
if(preg_match('/#006600/', $value['color'][$i])) {
$value['color'][$i] = 'GREEN (Mini Disaster)';
}
if(preg_match('/#9933cc/', $value['color'][$i])) {
$value['color'][$i] = 'PURPLE (Trauma ByPass)';
}
if(preg_match('/#ff6600/', $value['color'][$i])) {
$value['color'][$i] = 'ORANGE (ReRoute)';
}
$xTime .= ' ' . $value["color"][$i] . ' - ' . $value["time"][$i] . chr(10);
$xColor .= ' ' . $value["color"][$i] . chr(10);
$results[0] = $xTime;
$results[1] = $xColor;
}
}
}
}
return $results;
}

How say to this joomla module to take me to my SEF url article?

This module takes the articles from categories in joomla and displays them like a blog (short of). the problem is when i click on the title it gives a &view=item&layout=edit&sliderid=1&id=2. non friendly, and the link opens the article in my home page. how to make it produce the correct SEF link like suppose to do? I use joomla 3 and mod_rewrite is enabled
Here is the code:
defined('_JEXEC') or die('Restricted access');
require_once(JPATH_SITE.DS.'components'.DS.'com_content'.DS.'helpers'.DS.'route.php');
class PBHSourceJcontent {
public $arg;
public function loadFromDB($itemId = -1) {
$myQuery = 'SELECT
i.*
FROM #__content as i
WHERE 1=1
AND i.state = 1';
if ($itemId < 0 && !empty($this->arg['categories'])) {
$myQuery .= ' AND i.catid IN (' .implode(',',$this->arg['categories']). ')';
}
if ($this->arg['ordering'] == 'random' && !empty($this->arg['loaded_items'])) {
$myQuery .= ' AND i.id NOT IN ('.implode(',',$this->arg['loaded_items']).')';
}
if ($itemId < 0 && !empty($this->arg['ordering'])) {
switch ($this->arg['ordering']) {
case 'title_asc':
$myQuery .= ' ORDER BY i.title ASC';
break;
case 'title_desc':
$myQuery .= ' ORDER BY i.title DESC';
break;
case 'date_asc':
$myQuery .= ' ORDER BY i.publish_up ASC';
break;
case 'hits_desc':
$myQuery .= ' ORDER BY i.hits DESC';
break;
case 'hits_asc':
$myQuery .= ' ORDER BY i.hits ASC';
break;
case 'article_order':
$myQuery .= ' ORDER BY i.ordering ASC';
break;
case 'random':
$myQuery .= ' ORDER BY RAND()';
break;
default:
$myQuery .= ' ORDER BY i.publish_up DESC';
break;
}
}
if ($itemId < 0 && !empty($this->arg['items_number'])) {
$myQuery .= ' LIMIT ' . $this->arg['items_number'];
}
if ($itemId < 0 && !empty($this->arg['items_offset']) && $this->arg['items_offset'] > 0 && $this->arg['ordering'] != 'random') {
$myQuery .= ' OFFSET ' . $this->arg['items_offset'];
}
if ($itemId < 0) {
return DMHData::loadObjectList($myQuery);
} else {
$myQuery .= ' AND i.id = ' . $itemId;
return DMHData::loadObject($myQuery);
}
}
public function getItemId($item) {
return $item->id;
}
public function getItemUrl($item) {
if ($this->arg['previewpopup'] == 'enabled') {
$myLink = 'href="#" onclick="DMPinboard.getPreview('.$item->id.');return false;"';
} else {
$link = 'index.php?option=com_content&view=article&id='.$item->id;
$link = ContentHelperRoute::getArticleRoute($item->id, $item->catid);
$myLink = 'href="'.urldecode($link).'"';
}
return $myLink;
}
public function getItemTitle($item) {
if ($this->arg['show_title'] == 'yes') {
return $item->title;
} else {
return '';
}
}
public function getItemImage($item) {
if ($this->arg['show_image'] == 'fromtext') {
$myImage = '';
$output = preg_match( '/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $item->introtext, $matches);
if ($output > 0) {
$myImage = $matches[1];
}
return $myImage;
} else if($this->arg['show_image'] == 'introimg') {
$images = json_decode($item->images);
return $images->image_intro;
} else if ($this->arg['show_image'] == 'fullimg') {
$images = json_decode($item->images);
return $images->image_fulltext;
} else {
return '';
}
}
public function getItemIntro($item) {
if ($this->arg['show_intro'] == 'yes') {
$outText = str_replace(array("\t","\n","\r","\r\n"),'',strip_tags($item->introtext));
if (!empty($this->arg['introlength']) && $this->arg['introlength'] > 0) {
$outText = PBHHtml::shorter($outText, $this->arg['introlength']);
}
return $outText;
} else {
return '';
}
}
public function getPreviewImage($item) {
if ($this->arg['show_popup_images'] == 'fromtext') {
$myImage = '';
$output = preg_match('/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $item->introtext, $matches);
if ($output > 0) {
$myImage = $matches[1];
}
return $myImage;
} else if ($this->arg['show_popup_images'] == 'fullimg') {
$images = json_decode($item->images);
return $images->image_fulltext;
} else {
return '';
}
}
public function getPreviewTitle($item) {
if ($this->arg['show_popup_title'] == 'linked') {
$link = 'index.php?option=com_content&view=article&id='.$item->id;
$link = ContentHelperRoute::getArticleRoute($item->id, $item->catid);
return ''.$item->title.'';
} else if ($this->arg['show_popup_title'] == 'yes') {
return $item->title;
} else {
return '';
}
}
public function getPreviewContent($item) {
if ($this->arg['show_popup_intro'] == 'withoutimg') {
$outText = preg_replace('/<img[^>]+\>/i', '', $item->introtext);
} else if($this->arg['show_popup_intro'] == 'yes') {
$outText = preg_replace_callback('/(src=["\'])([^"\']+)(["\'])/','PBHHtml::checkImgSrc',$item->introtext);
} else {
$outText = '';
}
if (!empty($this->arg['previewlength']) && $this->arg['previewlength'] > 0) {
$outText = PBHHtml::truncate_teaser($outText,$this->arg['previewlength']);
}
return $outText;
}
public function getPreviewReadmore($item) {
if ($this->arg['show_popup_articlelink'] == 'yes') {
$link = 'index.php?option=com_content&view=article&id='.$item->id;
$link = ContentHelperRoute::getArticleRoute($item->id, $item->catid);
return ''.JText::_('COM_DMPINBOARD_FRONTEND_READMORE').'';
} else {
return '';
}
}
public function getShareInfo($item) {
$share = array();
//---
$link = 'index.php?option=com_content&view=article&id='.$item->id;
$link = ContentHelperRoute::getArticleRoute($item->id, $item->catid);
$share['url'] = urldecode(JUri::base().$link);
//---
$share['title'] = $item->title;
return $share;
}
}
?>
I am assuming you mean to output a SEF url in the second part of the getItemUrl($item) function.
Simply
$link = JRoute::_('index.php?option=com_content&view=article&id='.$item->id);
will do. However in your question, above your code, you show &view=item&layout=edit&sliderid=1&id=2 which is not the url in the code below, and will not take you to the article view.

How increase the performance of this code in php?

How increase the performance of this code in php?
or any alternative method to find out the comment if the string starts with # then call at()
or if string starts with "#" then call hash()
here the sample comment is "#hash #at #####tag";
/
/this is the comment with mention,tag
function getCommentWithLinks($comment="#name #tag ###nam1 test", $pid, $img='', $savedid='', $source='', $post_facebook='', $fbCmntInfo='') {
//assign to facebook facebookComment bcz it is used to post into the fb wall
$this->facebookComment = $comment;
//split the comment based on the space
$comment = explode(" ", $comment);
//get the lenght of the splitted array
$cmnt_length = count($comment);
$store_cmnt = $tagid = '';
$this->img = $img;
$this->saveid = $savedid;//this is uspid in product saved table primary key
//$this->params = "&product=".base_url()."product/".$this->saveid;
$this->params['product'] = base_url()."product/".$this->saveid;
//$this->params['tags']='';
foreach($comment as $word) {
//check it is tag or not
//the first character must be a # and remaining all alphanumeric if any # or # is exist then it is comment
//find the length of the tag #mention
$len = strlen($word);
$cmt = $c = $tag_name = '';
$j = 0;
$istag = false;
for($i=0; $i<$len; $i++) {
$j = $i-1;
//check if the starting letter is # or not
if($word[$i] == '#') {
//insert tagname
if($istag) {
//insert $tag_name
$this->save_tag($tag_name, $pid);
$istag = false;
$tag_name = '';
}
//check for comment
if($i >= 1 && $word[$j]=='#') {
$this->store_cmnt .= $word[$i];
}else{
//append to the store_coment if the i is 1 or -1 or $word[j]!=#
$this->store_cmnt .= $word[$i];//23,#
}
}else if($word[$i]=='#') {
//insert tagname
if($istag) {
//insert $tag_name
$this->save_mention($tag_name, $pid, $fbCmntInfo);
$istag = false;
$tag_name = '';
}
//check for comment
if($i >= 1 && $word[$j]=='#') {
$this->store_cmnt .= $word[$i];
}else{
$this->store_cmnt .= $word[$i];//23,#
}
}else if( $this->alphas($word[$i]) && $i!=0){
if($tag_name=='') {
//check the length of the string
$strln=strlen($this->store_cmnt);//4
if($strln != 0) {
$c = substr($this->store_cmnt, $strln-1, $strln);//#
if($c=='#' || $c=='#') {
$this->store_cmnt = substr($this->store_cmnt, 0, $strln-1);//23,
$tag_name = $c;
}
}
//$tag_name='';
}
//check that previous is # or # other wise it is
if($c=='#' || $c=='#') {
$tag_name .= $word[$i];
$istag = true;
//check if lenis == i then add anchor tag her
if($i == $len-1) {
$istag =false;
//check if it is # or #
if($c=='#')
$this->save_tag($tag_name,$pid);
else
$this->save_mention($tag_name,$pid,$fbCmntInfo);
//$this->store_cmnt .= '<a >'. $tag_name.'</a>';
}
}else{
$this->store_cmnt .= $word[$i];
}
}else{
if($istag) {
//insert $tag_name
$this->save_tag($tag_name,$pid);
$istag = false;
$tag_name = '';
}
$this->store_cmnt .= $word[$i];
}
}
$this->store_cmnt .=" ";
}
}
Try This it may be help full
function getResultStr($data, $param1, $param2){
return $param1 != $param2?(''.$data.''):$data;
}
function parseWord($word, $symbols){
$result = $word;
$status = FALSE;
foreach($symbols as $symbol){
if(($pos = strpos($word, $symbol)) !== FALSE){
$status = TRUE;
break;
}
}
if($status){
$temp = $symFlag = '';
$result = '';
foreach(str_split($word) as $char){
//Checking whether chars are symbols(#,#)
if(in_array($char, $symbols)){
if($symFlag != ''){
$result .= getResultStr($temp, $symFlag, $temp);
}
$symFlag = $temp = $char;
} else if(ctype_alnum($char) or $char == '_'){
//accepts[0-9][A-Z][a-z] and unserscore (_)
//Checking whether Symbol already started
if($symFlag != ''){
$temp .= $char;
} else {
//Just appending the char to $result
$result .= $char;
}
} else {
//accepts all special symbols excepts #,# and _
if($symFlag != ''){
$result .= getResultStr($temp, $symFlag, $temp);
$temp = $symFlag = '';
}
$result .= $char;
}
}
$result .= getResultStr($temp, $symFlag, '');
}
return $result;
}
function parseComment($comment){
$str = '';
$symbols = array('#', '#');
foreach(explode(' ', $comment) as $word){
$result = parseWord($word, $symbols);
$str .= $result.' ';
}
return $str;
}
$str = "#Richard, #McClintock, a Latin professor at $%#Hampden_Sydney #College-in #Virginia, looked up one of the ######more obscure Latin words, #######%%#%##consectetur, from a Lorem Ipsum passage, and #going#through the cites of the word in classical literature";
echo "<br />Before Parsing : <br />".$str;
echo "<br /><br />After Parsing : <br />".parseComment($str);
use strpos or preg_match or strstr
Please refer string functions in php. You can do it in a line or two with that in built functions.
If it not matches better to write a regex.

Hacker Backdoor script? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I found this script attached to a modified index page. This looks like some kind of backdoor. and who is this SAPE ?
<?php
class SAPE_base {
var $_version = '1.0.8';
var $_verbose = false;
var $_charset = '';
var $_sape_charset = '';
var $_server_list = array('dispenser-01.sape.ru', 'dispenser-02.sape.ru');
var $_cache_lifetime = 3600;
var $_cache_reloadtime = 600;
var $_error = '';
var $_host = '';
var $_request_uri = '';
var $_multi_site = false;
var $_fetch_remote_type = '';
var $_socket_timeout = 6;
var $_force_show_code = false;
var $_is_our_bot = false;
var $_debug = false;
var $_ignore_case = false;
var $_db_file = '';
var $_use_server_array = false;
var $_force_update_db = false;
function SAPE_base($options = null) {
$host = '';
if (is_array($options)) {
if (isset($options['host'])) {
$host = $options['host'];
}
}
elseif (strlen($options)) {
$host = $options;
$options = array();
}
else {
$options = array();
}
if (isset($options['use_server_array']) && $options['use_server_array'] == true) {
$this->_use_server_array = true;
}
if (strlen($host)) {
$this->_host = $host;
}
else {
$this->_host = $_SERVER['HTTP_HOST'];
}
$this->_host = preg_replace('/^http:\/\//', '', $this->_host);
$this->_host = preg_replace('/^www\./', '', $this->_host);
if (isset($options['request_uri']) && strlen($options['request_uri'])) {
$this->_request_uri = $options['request_uri'];
}
elseif ($this->_use_server_array === false) {
$this->_request_uri = getenv('REQUEST_URI');
}
if (strlen($this->_request_uri) == 0) {
$this->_request_uri = $_SERVER['REQUEST_URI'];
}
if (isset($options['multi_site']) && $options['multi_site'] == true) {
$this->_multi_site = true;
}
if (isset($options['debug']) && $options['debug'] == true) {
$this->_debug = true;
}
if (isset($_COOKIE['sape_cookie']) && ($_COOKIE['sape_cookie'] == _SAPE_USER)) {
$this->_is_our_bot = true;
if (isset($_COOKIE['sape_debug']) && ($_COOKIE['sape_debug'] == 1)) {
$this->_debug = true;
$this->_options = $options;
$this->_server_request_uri = $this->_request_uri = $_SERVER['REQUEST_URI'];
$this->_getenv_request_uri = getenv('REQUEST_URI');
$this->_SAPE_USER = _SAPE_USER;
}
if (isset($_COOKIE['sape_updatedb']) && ($_COOKIE['sape_updatedb'] == 1)) {
$this->_force_update_db = true;
}
}
else {
$this->_is_our_bot = false;
}
if (isset($options['verbose']) && $options['verbose'] == true || $this->_debug) {
$this->_verbose = true;
}
if (isset($options['charset']) && strlen($options['charset'])) {
$this->_charset = $options['charset'];
}
else {
$this->_charset = 'windows-1251';
}
if (isset($options['fetch_remote_type']) && strlen($options['fetch_remote_type'])) {
$this->_fetch_remote_type = $options['fetch_remote_type'];
}
if (isset($options['socket_timeout']) && is_numeric($options['socket_timeout']) && $options['socket_timeout'] > 0) {
$this->_socket_timeout = $options['socket_timeout'];
}
if (isset($options['force_show_code']) && $options['force_show_code'] == true) {
$this->_force_show_code = true;
}
if (!defined('_SAPE_USER')) {
return $this->raise_error('Не задана константа _SAPE_USER');
}
if (isset($options['ignore_case']) && $options['ignore_case'] == true) {
$this->_ignore_case = true;
$this->_request_uri = strtolower($this->_request_uri);
}
}
function fetch_remote_file($host, $path) {
$user_agent = $this->_user_agent . ' ' . $this->_version;
#ini_set('allow_url_fopen', 1);
#ini_set('default_socket_timeout', $this->_socket_timeout);
#ini_set('user_agent', $user_agent);
if (
$this->_fetch_remote_type == 'file_get_contents'
||
(
$this->_fetch_remote_type == ''
&&
function_exists('file_get_contents')
&&
ini_get('allow_url_fopen') == 1
)
) {
$this->_fetch_remote_type = 'file_get_contents';
if ($data = #file_get_contents('http://' . $host . $path)) {
return $data;
}
}
elseif (
$this->_fetch_remote_type == 'curl'
||
(
$this->_fetch_remote_type == ''
&&
function_exists('curl_init')
)
) {
$this->_fetch_remote_type = 'curl';
if ($ch = #curl_init()) {
#curl_setopt($ch, CURLOPT_URL, 'http://' . $host . $path);
#curl_setopt($ch, CURLOPT_HEADER, false);
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
#curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->_socket_timeout);
#curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
if ($data = #curl_exec($ch)) {
return $data;
}
#curl_close($ch);
}
}
else {
$this->_fetch_remote_type = 'socket';
$buff = '';
$fp = #fsockopen($host, 80, $errno, $errstr, $this->_socket_timeout);
if ($fp) {
#fputs($fp, "GET {$path} HTTP/1.0\r\nHost: {$host}\r\n");
#fputs($fp, "User-Agent: {$user_agent}\r\n\r\n");
while (!#feof($fp)) {
$buff .= #fgets($fp, 128);
}
#fclose($fp);
$page = explode("\r\n\r\n", $buff);
return $page[1];
}
}
return $this->raise_error('Не могу подключиться к серверу: ' . $host . $path . ', type: ' . $this->_fetch_remote_type);
}
function _read($filename) {
$fp = #fopen($filename, 'rb');
#flock($fp, LOCK_SH);
if ($fp) {
clearstatcache();
$length = #filesize($filename);
$mqr = #get_magic_quotes_runtime();
#set_magic_quotes_runtime(0);
if ($length) {
$data = #fread($fp, $length);
}
else {
$data = '';
}
#set_magic_quotes_runtime($mqr);
#flock($fp, LOCK_UN);
#fclose($fp);
return $data;
}
return $this->raise_error('Не могу считать данные из файла: ' . $filename);
}
function _write($filename, $data) {
$fp = #fopen($filename, 'ab');
if ($fp) {
if (flock($fp, LOCK_EX | LOCK_NB)) {
$length = strlen($data);
ftruncate($fp, 0);
#fwrite($fp, $data, $length);
#flock($fp, LOCK_UN);
#fclose($fp);
if (md5($this->_read($filename)) != md5($data)) {
#unlink($filename);
return $this->raise_error('Нарушена целостность данных при записи в файл: ' . $filename);
}
}
else {
return false;
}
return true;
}
return $this->raise_error('Не могу записать данные в файл: ' . $filename);
}
function raise_error($e) {
$this->_error = '<p style="color: red; font-weight: bold;">SAPE ERROR: ' . $e . '</p>';
if ($this->_verbose == true) {
print $this->_error;
}
return false;
}
function load_data() {
$this->_db_file = $this->_get_db_file();
if (!is_file($this->_db_file)) {
if (#touch($this->_db_file)) {
#chmod($this->_db_file, 0666);
}
else {
return $this->raise_error('Нет файла ' . $this->_db_file . '. Создать не удалось. Выставите права 777 на папку.');
}
}
if (!is_writable($this->_db_file)) {
return $this->raise_error('Нет доступа на запись к файлу: ' . $this->_db_file . '! Выставите права 777 на папку.');
}
#clearstatcache();
$data = $this->_read($this->_db_file);
if (
$this->_force_update_db
|| (
!$this->_is_our_bot
&&
(
filemtime($this->_db_file) < (time() - $this->_cache_lifetime)
||
filesize($this->_db_file) == 0
||
#unserialize($data) == false
)
)
) {
#touch($this->_db_file, (time() - $this->_cache_lifetime + $this->_cache_reloadtime));
$path = $this->_get_dispenser_path();
if (strlen($this->_charset)) {
$path .= '&charset=' . $this->_charset;
}
foreach ($this->_server_list as $i => $server) {
if ($data = $this->fetch_remote_file($server, $path)) {
if (substr($data, 0, 12) == 'FATAL ERROR:') {
$this->raise_error($data);
}
else {
$hash = #unserialize($data);
if ($hash != false) {
$hash['__sape_charset__'] = $this->_charset;
$hash['__last_update__'] = time();
$hash['__multi_site__'] = $this->_multi_site;
$hash['__fetch_remote_type__'] = $this->_fetch_remote_type;
$hash['__ignore_case__'] = $this->_ignore_case;
$hash['__php_version__'] = phpversion();
$hash['__server_software__'] = $_SERVER['SERVER_SOFTWARE'];
$data_new = #serialize($hash);
if ($data_new) {
$data = $data_new;
}
$this->_write($this->_db_file, $data);
break;
}
}
}
}
}
if (strlen(session_id())) {
$session = session_name() . '=' . session_id();
$this->_request_uri = str_replace(array('?' . $session, '&' . $session), '', $this->_request_uri);
}
$this->set_data(#unserialize($data));
}
}
class SAPE_client extends SAPE_base {
var $_links_delimiter = '';
var $_links = array();
var $_links_page = array();
var $_user_agent = 'SAPE_Client PHP';
function SAPE_client($options = null) {
parent::SAPE_base($options);
$this->load_data();
}
function return_links($n = null, $offset = 0) {
if (is_array($this->_links_page)) {
$total_page_links = count($this->_links_page);
if (!is_numeric($n) || $n > $total_page_links) {
$n = $total_page_links;
}
$links = array();
for ($i = 1; $i <= $n; $i++) {
if ($offset > 0 && $i <= $offset) {
array_shift($this->_links_page);
}
else {
$links[] = array_shift($this->_links_page);
}
}
$html = join($this->_links_delimiter, $links);
if (
strlen($this->_charset) > 0
&&
strlen($this->_sape_charset) > 0
&&
$this->_sape_charset != $this->_charset
&&
function_exists('iconv')
) {
$new_html = #iconv($this->_sape_charset, $this->_charset, $html);
if ($new_html) {
$html = $new_html;
}
}
if ($this->_is_our_bot) {
$html = '<sape_noindex>' . $html . '</sape_noindex>';
}
}
else {
$html = $this->_links_page;
}
if ($this->_debug) {
$html .= print_r($this, true);
}
return $html;
}
function _get_db_file() {
if ($this->_multi_site) {
return dirname(__FILE__) . '/' . $this->_host . '.links.db';
}
else {
return dirname(__FILE__) . '/links.db';
}
}
function _get_dispenser_path() {
return '/code.php?user=' . _SAPE_USER . '&host=' . $this->_host;
}
function set_data($data) {
if ($this->_ignore_case) {
$this->_links = array_change_key_case($data);
}
else {
$this->_links = $data;
}
if (isset($this->_links['__sape_delimiter__'])) {
$this->_links_delimiter = $this->_links['__sape_delimiter__'];
}
if (isset($this->_links['__sape_charset__'])) {
$this->_sape_charset = $this->_links['__sape_charset__'];
}
else {
$this->_sape_charset = '';
}
if (#array_key_exists($this->_request_uri, $this->_links) && is_array($this->_links[$this->_request_uri])) {
$this->_links_page = $this->_links[$this->_request_uri];
}
else {
if (isset($this->_links['__sape_new_url__']) && strlen($this->_links['__sape_new_url__'])) {
if ($this->_is_our_bot || $this->_force_show_code) {
$this->_links_page = $this->_links['__sape_new_url__'];
}
}
}
}
}
class SAPE_context extends SAPE_base {
var $_words = array();
var $_words_page = array();
var $_user_agent = 'SAPE_Context PHP';
var $_filter_tags = array('a', 'textarea', 'select', 'script', 'style', 'label', 'noscript', 'noindex', 'button');
function SAPE_context($options = null) {
parent::SAPE_base($options);
$this->load_data();
}
function replace_in_text_segment($text) {
$debug = '';
if ($this->_debug) {
$debug .= "<!-- argument for replace_in_text_segment: \r\n" . base64_encode($text) . "\r\n -->";
}
if (count($this->_words_page) > 0) {
$source_sentence = array();
if ($this->_debug) {
$debug .= '<!-- sentences for replace: ';
}
foreach ($this->_words_page as $n => $sentence) {
//Заменяем все сущности на символы
$special_chars = array(
'&' => '&',
'"' => '"',
''' => '\'',
'<' => '<',
'>' => '>'
);
$sentence = strip_tags($sentence);
foreach ($special_chars as $from => $to) {
str_replace($from, $to, $sentence);
}
$sentence = htmlspecialchars($sentence);
$sentence = preg_quote($sentence, '/');
$replace_array = array();
if (preg_match_all('/(&[#a-zA-Z0-9]{2,6};)/isU', $sentence, $out)) {
for ($i = 0; $i < count($out[1]); $i++) {
$unspec = $special_chars[$out[1][$i]];
$real = $out[1][$i];
$replace_array[$unspec] = $real;
}
}
foreach ($replace_array as $unspec => $real) {
$sentence = str_replace($real, '((' . $real . ')|(' . $unspec . '))', $sentence);
}
$source_sentences[$n] = str_replace(' ', '((\s)|( ))+', $sentence);
if ($this->_debug) {
$debug .= $source_sentences[$n] . "\r\n\r\n";
}
}
if ($this->_debug) {
$debug .= '-->';
}
$first_part = true;
if (count($source_sentences) > 0) {
$content = '';
$open_tags = array();
$close_tag = '';
$part = strtok(' ' . $text, '<');
while ($part !== false) {
if (preg_match('/(?si)^(\/?[a-z0-9]+)/', $part, $matches)) {
$tag_name = strtolower($matches[1]);
if (substr($tag_name, 0, 1) == '/') {
$close_tag = substr($tag_name, 1);
if ($this->_debug) {
$debug .= '<!-- close_tag: ' . $close_tag . ' -->';
}
}
else {
$close_tag = '';
if ($this->_debug) {
$debug .= '<!-- open_tag: ' . $tag_name . ' -->';
}
}
$cnt_tags = count($open_tags);
if (($cnt_tags > 0) && ($open_tags[$cnt_tags - 1] == $close_tag)) {
array_pop($open_tags);
if ($this->_debug) {
$debug .= '<!-- ' . $tag_name . ' - deleted from open_tags -->';
}
if ($cnt_tags - 1 == 0) {
if ($this->_debug) {
$debug .= '<!-- start replacement -->';
}
}
}
if (count($open_tags) == 0) {
if (!in_array($tag_name, $this->_filter_tags)) {
$split_parts = explode('>', $part, 2);
if (count($split_parts) == 2) {
foreach ($source_sentences as $n => $sentence) {
if (preg_match('/' . $sentence . '/', $split_parts[1]) == 1) {
$split_parts[1] = preg_replace('/' . $sentence . '/', str_replace('$', '\$', $this->_words_page[$n]), $split_parts[1], 1);
if ($this->_debug) {
$debug .= '<!-- ' . $sentence . ' --- ' . $this->_words_page[$n] . ' replaced -->';
}
unset($source_sentences[$n]);
unset($this->_words_page[$n]);
}
}
$part = $split_parts[0] . '>' . $split_parts[1];
unset($split_parts);
}
}
else {
$open_tags[] = $tag_name;
if ($this->_debug) {
$debug .= '<!-- ' . $tag_name . ' - added to open_tags, stop replacement -->';
}
}
}
}
else {
foreach ($source_sentences as $n => $sentence) {
if (preg_match('/' . $sentence . '/', $part) == 1) {
$part = preg_replace('/' . $sentence . '/', str_replace('$', '\$', $this->_words_page[$n]), $part, 1);
if ($this->_debug) {
$debug .= '<!-- ' . $sentence . ' --- ' . $this->_words_page[$n] . ' replaced -->';
}
unset($source_sentences[$n]);
unset($this->_words_page[$n]);
}
}
}
if ($this->_debug) {
$content .= $debug;
$debug = '';
}
if ($first_part) {
$content .= $part;
$first_part = false;
}
else {
$content .= $debug . '<' . $part;
}
unset($part);
$part = strtok('<');
}
$text = ltrim($content);
unset($content);
}
}
else {
if ($this->_debug) {
$debug .= '<!-- No word`s for page -->';
}
}
if ($this->_debug) {
$debug .= '<!-- END: work of replace_in_text_segment() -->';
}
if ($this->_is_our_bot || $this->_force_show_code || $this->_debug) {
$text = '<sape_index>' . $text . '</sape_index>';
if (isset($this->_words['__sape_new_url__']) && strlen($this->_words['__sape_new_url__'])) {
$text .= $this->_words['__sape_new_url__'];
}
}
if ($this->_debug) {
if (count($this->_words_page) > 0) {
$text .= '<!-- Not replaced: ' . "\r\n";
foreach ($this->_words_page as $n => $value) {
$text .= $value . "\r\n\r\n";
}
$text .= '-->';
}
$text .= $debug;
}
return $text;
}
function replace_in_page(&$buffer) {
if (count($this->_words_page) > 0) {
$split_content = preg_split('/(?smi)(<\/?sape_index>)/', $buffer, -1);
$cnt_parts = count($split_content);
if ($cnt_parts > 1) {
//Если есть хоть одна пара sape_index, то начинаем работу
if ($cnt_parts >= 3) {
for ($i = 1; $i < $cnt_parts; $i = $i + 2) {
$split_content[$i] = $this->replace_in_text_segment($split_content[$i]);
}
}
$buffer = implode('', $split_content);
if ($this->_debug) {
$buffer .= '<!-- Split by Sape_index cnt_parts=' . $cnt_parts . '-->';
}
}
else {
$split_content = preg_split('/(?smi)(<\/?body[^>]*>)/', $buffer, -1, PREG_SPLIT_DELIM_CAPTURE);
if (count($split_content) == 5) {
$split_content[0] = $split_content[0] . $split_content[1];
$split_content[1] = $this->replace_in_text_segment($split_content[2]);
$split_content[2] = $split_content[3] . $split_content[4];
unset($split_content[3]);
unset($split_content[4]);
$buffer = $split_content[0] . $split_content[1] . $split_content[2];
if ($this->_debug) {
$buffer .= '<!-- Split by BODY -->';
}
}
else {
if ($this->_debug) {
$buffer .= '<!-- Can`t split by BODY -->';
}
}
}
}
else {
if (!$this->_is_our_bot && !$this->_force_show_code && !$this->_debug) {
$buffer = preg_replace('/(?smi)(<\/?sape_index>)/', '', $buffer);
}
else {
if (isset($this->_words['__sape_new_url__']) && strlen($this->_words['__sape_new_url__'])) {
$buffer .= $this->_words['__sape_new_url__'];
}
}
if ($this->_debug) {
$buffer .= '<!-- No word`s for page -->';
}
}
return $buffer;
}
function _get_db_file() {
if ($this->_multi_site) {
return dirname(__FILE__) . '/' . $this->_host . '.words.db';
}
else {
return dirname(__FILE__) . '/words.db';
}
}
function _get_dispenser_path() {
return '/code_context.php?user=' . _SAPE_USER . '&host=' . $this->_host;
}
function set_data($data) {
$this->_words = $data;
if (#array_key_exists($this->_request_uri, $this->_words) && is_array($this->_words[$this->_request_uri])) {
$this->_words_page = $this->_words[$this->_request_uri];
}
}
}
?>
Sape is apparently link exchange service used by a Russian-speaking botnet owner.
This backdoor appears to use the sape API to download XML and use bots to create a "context" that probably clicks links to generate illicit revenue.
From a bad Google transition of sape.ru:
Sape system increases revenue and reduces the consumption of
webmasters optimizers. Venues are beginning to sell the place, not
only from the main pages, but also internal. How many pages on the
site? Let each revenue. Optimizers are buying cheap internal pages and
save on moving projects.
My Russian isn't very good, but sape.ru looks like some kind of link exchange service. And in answer to your question "Who is SAPE":
[david#archtower ~]$ whois sape.ru
% By submitting a query to RIPN's Whois Service
% you agree to abide by the following terms of use:
% http://www.ripn.net/about/servpol.html#3.2 (in Russian)
% http://www.ripn.net/about/en/servpol.html#3.2 (in English).
domain: SAPE.RU
nserver: ns1.q0.ru.
nserver: ns2.q0.ru.
nserver: ns3.q0.ru.
state: REGISTERED, DELEGATED, VERIFIED
org: LTD Sape
registrar: R01-REG-RIPN
admin-contact: https://partner.r01.ru/contact_admin.khtml
created: 2006.06.20
paid-till: 2013.06.20
free-date: 2013.07.21
source: TCI
Last updated on 2012.06.19 19:28:42 MSK
[david#archtower ~]$
Looks like it's something to automatically visit ads referral links at first glance.

Can't debug random error

I have a web-based custom ticket sales I made for a friend and whenever I tried it (on any browser) it worked perfectly fine. However when it went live yesterday some people tried to book tickets and they would receive their email stating they had their seats booked (everything was ok) but the system would only record some of those seats.
Let's say that if they booked A1 - A10 they got an email saying they booked those but the system would only book A1 - A5 (or A6 or so, it seems random).
Also, this wouldn't happen with EVERY person it just happens randomly (at least I haven't found a proper reason for it to happen yet).
The code is here when I book the tickets:
$cantTotal=0;
$boletosF1 = $_POST['funcion1Hidden'];
if($boletosF1!=""){
$lugares = explode(" ", $boletosF1);
$cant = count($lugares);
$cantTotal += $cant;
$f1 = "";
$sqlAP = "SELECT * FROM apartados";
if ($resultAP = mysql_query($sqlAP)) {
while ($rowAP = mysql_fetch_array($resultApP)) {
$f = $rowAP['funcion'];
$lugar = $rowAP['lugar'];
$count++;
if ($f == "F1") {
$f1.= ( $lugar . " ");
}
}
}
$sqlPag2 = "SELECT * FROM pagados";
if ($resultPag2 = mysql_query($sqlPag2)) {
while ($rowPag2 = mysql_fetch_array($resultPag2)) {
$f = $rowPag2['funcion'];
$lugar = $rowPag2['lugar'];
$count++;
if ($f == "F1") {
$f1.= ( $lugar . " ");
}
}
}
$func = explode(" ", $f1);
$cantUtilizados = count($func);
$repetidos = 0;
for ($int = 0; $int < $cant; $int++) {
for ($r = 0; $r < $cantUtilizados; $r++) {
if ($func[$r] == $lugares[$int]) {
$repetidos++;
}
}
}
if ($repetidos > 0) {
redirect("apartadoBoletos.php?error=1");
}
}
$boletosF2 = $_POST['funcion2Hidden'];
if($boletosF2!=""){
$lugares2 = explode(" ", $boletosF2);
$cant2 = count($lugares2);
$cantTotal+=$cant2;
$f2 = "";
$sqlAP = "SELECT * FROM apartados";
if ($resultAP = mysql_query($sqlAP)) {
while ($rowAP = mysql_fetch_array($resultApP)) {
$f = $rowAP['funcion'];
$lugar = $rowAP['lugar'];
$count++;
if ($f == "F2") {
$f2.= ( $lugar . " ");
}
}
}
$sqlPag2 = "SELECT * FROM pagados";
if ($resultPag2 = mysql_query($sqlPag2)) {
while ($rowPag2 = mysql_fetch_array($resultPag2)) {
$f = $rowPag2['funcion'];
$lugar = $rowPag2['lugar'];
$count++;
if ($f == "F2") {
$f2.= ( $lugar . " ");
}
}
}
$func2 = explode(" ", $f2);
$cantUtilizados = count($func2);
for ($int = 0; $int < $cant2; $int++) {
for ($r = 0; $r < $cantUtilizados; $r++) {
if ($func2[$r] == $lugares2[$int]) {
$repetidos++;
}
}
}
if ($repetidos > 0) {
redirect("apartadoBoletos.php?error=1");
}
}
function redirect($url) {
echo "<script language=\"JavaScript\"> window.location='$url'; </script>";
}
$totalAPagar=120*$cantTotal;
and when I save them to the Database and send the email:
$boletosF1 = $_POST['boletosF1'];
$boletosF2 = $_POST['boletosF2'];
$nombre = $_POST['name'];
$correo = $_POST['mail'];
$cant1=0;
$cant2=0;
if($boletosF1!=""){
$lugares1 = explode(" ", $boletosF1);
echo $lugares1;
$cant1 = count($lugares1);
echo $cant1;
$f1 = "";
$sqlAP = "SELECT * FROM apartados";
if ($resultAP = mysql_query($sqlAP)) {
while ($rowAP = mysql_fetch_array($resultApP)) {
$f = $rowAP['funcion'];
$lugar = $rowAP['lugar'];
$count++;
if ($f == "F1") {
$f1.= ( $lugar . " ");
}
}
}
$sqlPag2 = "SELECT * FROM pagados";
if ($resultPag2 = mysql_query($sqlPag2)) {
while ($rowPag2 = mysql_fetch_array($resultPag2)) {
$f = $rowPag2['funcion'];
$lugar = $rowPag2['lugar'];
$count++;
if ($f == "F1") {
$f1.= ( $lugar . " ");
}
}
}
$func1 = explode(" ", $f1);
$cantUtilizados1 = count($func1);
$repetidos = 0;
for ($int = 0; $int < $cant1; $int++) {
for ($r = 0; $r < $cantUtilizados1; $r++) {
if ($func1[$r] == $lugares1[$int]) {
$repetidos++;
}
}
}
if ($repetidos > 0) {
redirect("apartadoBoletos.php?error=1");
}
}
if($boletosF2!=""){
$lugares2 = explode(" ", $boletosF2);
echo $lugares2;
$cant2 = count($lugares2);
echo $cant2;
$f2 = "";
$sqlAP = "SELECT * FROM apartados";
if ($resultAP = mysql_query($sqlAP)) {
while ($rowAP = mysql_fetch_array($resultApP)) {
$f = $rowAP['funcion'];
$lugar = $rowAP['lugar'];
$count++;
if ($f == "F2") {
$f2.= ( $lugar . " ");
}
}
}
$sqlPag2 = "SELECT * FROM pagados";
if ($resultPag2 = mysql_query($sqlPag2)) {
while ($rowPag2 = mysql_fetch_array($resultPag2)) {
$f = $rowPag2['funcion'];
$lugar = $rowPag2['lugar'];
$count++;
if ($f == "F2") {
$f2.= ( $lugar . " ");
}
}
}
$func2 = explode(" ", $f2);
$cantUtilizados2 = count($func2);
$repetidos = 0;
for ($int = 0; $int < $cant2; $int++) {
for ($r = 0; $r < $cantUtilizados2; $r++) {
if ($func2[$r] == $lugares2[$int]) {
$repetidos++;
}
}
}
if ($repetidos > 0) {
redirect("apartadoBoletos.php?error=1");
}
}
$rand = rand(0, 500);
$clave = sha1($rand . date("shd"));
$clave = substr($clave, 5, 5);
//insertar nuevo cliente
//mysql_query('BEGIN');
$sql = "INSERT INTO cliente(`idCliente`,`fecha`,`Nombre`,`correo`)VALUES('$clave',NOW(),'$nombre','$correo')";
$result = mysql_query($sql);
//crear arrays para guardar lugares
//insertar apartado F1
for ($i = 0; $i < $cant1; $i++) {
$sqlF1 = "INSERT INTO apartados(`lugar`,`idCliente`,`funcion`)VALUES('$lugares1[$i]','$clave','F1')";
$resultF1 = mysql_query($sqlF1);
}
for ($i = 0; $i < $cant2; $i++) {
$sqlF1 = "INSERT INTO apartados(`lugar`,`idCliente`,`funcion`)VALUES('$lugares2[$i]','$clave','F2')";
$resultF1 = mysql_query($sqlF1);
}
if (mysql_error ()) {
//echo mysql_error ();
// mysql_query('ROLLBACK');
redirect("apartadoBoletos.php?error=2");
} else {
$totalAPagar=($cant1+$cant2)*120;
// mysql_query('COMMIT');
$to = $correo;
$dia=date("d-m-Y");
//echo $dia;
//User info
$subject = "Boletos"; //The default subject. Will appear by default in all messages.
//The message to be received in the inbox
$msg .= "Estimad# $nombre: \n\n";
$msg .= "Clave: $clave " . "\r\n\n"; //the message itself
$msg .= "Boletos 28 de Junio: $boletosF1 " . "\r\n";
$msg .= "Boletos 27 de Junio: $boletosF2 " . "\r\n\n";
$msg .= "Total a pagar: $ $totalAPagar.00 " . "\r\n\n";
//$header .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$header .= "From: no-reply#booking.com" . "\r\n";
$header .= "Reply-To: no-reply#booking.com" . "\r\n";
$header .= "Return-Path: $email" . "\r\n";
mail($to, $subject, $msg, $header);
}
function redirect($url) {
echo "<script language=\"JavaScript\"> window.location='$url'; </script>";
}
So far I can't find the error and I've got to since this should have started working yesterday but everything had to be stopped =/ I really need help here please.
Also, something that might help, I think the error could be related to the amount of users at a given time however since it just happens to some of the persons that use this I really can't say that's the reason.
If you aren't sure where the error is occurring, you could add extensive logging for a while to see if you can figure it out.
For example, when the user clicks save, or buy tickets, or whatever, you could write to the log file the data that the user has input on the form.
Then, you could log again when you send the purchase information to the database. Record the SQL or stored procedure name and parameter values.
This kind of extensive logging tends to hurt performance, but when you are in a desperate situation, sometimes it's worthwhile.
As soon as you have an idea of the problem, or think you have logged enough data to analyze, you can turn the logging back off.
This is really a comment, but it's too code centric to fit in one.
Consider rewriting your code so it actually uses SQL.
This code
$f1 = "";
$sqlAP = "SELECT * FROM apartados";
if ($resultAP = mysql_query($sqlAP)) {
while ($rowAP = mysql_fetch_array($resultApP)) {
$f = $rowAP['funcion'];
$lugar = $rowAP['lugar'];
$count++;
if ($f == "F1") {
$f1.= ( $lugar . " ");
}
}
}
Looks silly, you're not using SQL at all.
Rewrite it into this:
$sqlAP = "SELECT group_concat(lugar SEPARATOR ' ') as lugar
, count(*) as count1
FROM apartados WHERE funcion = 'F1'";
if ($resultAP = mysql_query($sqlAP)) {
$rowAP = mysql_fetch_array($result_AP);
$count = $rowAP['count1'];
$lugar = $rowAP['lugar'];
}
Much faster and much cleaner.

Categories