php file reading displaying unwanted content - php

I am working on some code and i have scraped together the following some from stackoverflow and some from my old code. Any way, I am trying to just have the file parsed and processed without actually displaying its content untell a later stage.
There is the PHP:
$c = 0;
if($fp = fopen($newname,"r"))
{
while (($line = fgets($fp)) !== false)
{
//CHECK STRING TO SEE IF IT CONTAINS AN EMAIL
$checkResult = $this->checkCSVContentForEmail($line,$c);//$content
if(!empty($checkResult))
{
if($checkResult == TRUE && is_bool($checkResult) == true)
{
$this->contactsAddedCounter += 1;
}
elseif(is_string($checkResult))
{
$errLine .= '
<p> CheckResult: '.$checkResult.' Line number: '.$c.' does not have an email</p>';
array_push($this->LogError_contactsUpload, $errLine);
}
}
else
{
$errLine = "<p>Line number: ".$c." contain's an empty string</p><br>\n";
array_push($this->LogError_contactsUpload, $errLine);
}
$c++;
}
}
fclose($fp);
I have spend the whole day yesterday coding through all the involved code - functions and all but nothing should be doing any displaying but i still get the follwing displayed,
The unwanted output:
Array ( [0] => " [1] => [2] => [3] => [4] => Normal"" [5] => ""False"" [6] => [7] => [8] => ""Normal""";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; )
of-course this is displayed repeatedly for each line read.
Any help on what may be causing this?
The rest of the code involved in processing:
//Check line for Email Method
public function checkCSVContentForEmail($csvLine, $lineNum)
{
if(!empty($csvLine))
{
$partedCSV = explode(',',$csvLine);
if(!empty($partedCSV[57]))
{
$csvEmail = $partedCSV[57];
if(!empty($csvEmail))
{
if($Result = $this->checkEmail($csvEmail, $lineNum))
{
//convert csv line into sql statement
$csv2sqlInsertMultiLine = '(';
$csvTosql = '';
foreach($partedCSV as $csvContent)
{
$str = strip_tags($csvContent);
$letters = array('"', "'");
$Quotes = array('', ' ');
$strN = str_replace($letters, $Quotes, $str);
$letters = array('(', ")");
$Quotes = array('', '');
$c2s_str = str_replace($letters, $Quotes, $strN);
$csvTosql[] .= $c2s_str;
}
//(4,5,6);
$theSQL = implode(',',$csvTosql);
$csv2sqlInsertMultiLine .= $theSQL;
$csv2sqlInsertMultiLine .= '),';
array_push($this->csv2sqlInsertMultiLine, $csv2sqlInsertMultiLine);
return $Result;
}
}
}
else
{
$show = 'No Entry for Email address field - WILL NOT BE ADDED TO DATABASE! '.print_r($partedCSV);
return $show;
}
}
else
{
$show = 'This line is empty';
return $show;
}
}
//Validate Email Method
public function checkEmail($email, $row)
{
if(!empty($email))
{
$str = strip_tags($email);
$letters = array('"', "'");
$Quotes = array('', ' ');
$em = str_replace($letters, $Quotes, $str);
if(!empty($em) or $em !=' ')
{
$check = preg_match('/^\S+#[\w\d.-]{2,}\.[\w]{2,6}$/iU', $em) ? TRUE : FALSE;
if($check == TRUE)
{
$this->contactEmail[$row] = $em;//array_push();
return TRUE;
}
}
else
{
$msg = 'There is no email passed in: '.$em.' <br>Our check resulted in: '.$check;
return $msg;
}
}
else
{
$msg = 'There is no email passed in: '.$email.' <br>Our check resulted in: '.$check;
return $msg;
}
}
The JQuery
// Upload Contacts
function uploadContacts()
{
var obj = '#upImprtFile';
var file_data = $k('#ContactsImprt').prop('files')[0];
var form_data = new FormData();
form_data.append("action", "uploadContacts");
form_data.append("upImprtFile", "submit");
form_data.append("ContactsImprt", file_data);
$k.ajax({
url: 'inc/runUtilities.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data)
{
$k('#doUpload').html(data).fadeIn('slow');
}
});
}

See the following lines inside checkCSVContentForEmail method.
else
{
$show = 'No Entry for Email address field - WILL NOT BE ADDED TO DATABASE! '.print_r($partedCSV);
return $show;
}
Use of print_r must be causing the output.

Related

fsockopen(): unable to connect when using ajax

I am required to get domain information so I wrote this function
$servers = array(
"biz" => "whois.neulevel.biz",
"com" => "whois.internic.net",
function whois($domainName, $ext)
{
$server = trim($this->servers[$ext]);
$output = "";
try {
if ($conn = fsockopen($server, 43)) {
fputs($conn, strtolower($domainName) . '.' . $ext . "\r\n");
while (!feof($conn)) {
$output .= fgets($conn, 128);
}
fclose($conn);
if (stristr($output, "No match") ||
stristr($output, "No Data") ||
stristr($output, "No entries") ||
stristr($output, "No entries") ||
stristr($output, "NOT FOUND")) {
$this->durum[$ext]["durum"] = "bos";
} else {
$this->durum[$ext]["durum"] = "dolu";
// $this->durum[$ext]["son"] =substr($output)
}
$bas = strpos($output, "Expiry Date:");
$t = substr($output, $bas, 23);
$tarih = str_replace("Expiry Date:", "", $t);
$this->durum[$ext]["son"] = $tarih;
} else {
}
} catch (exception $e) {
echo $e->getMessage();
}
this function works fine without using ajax The problem is if I use ajax I realized that Its not working second time without waiting 10 or 15 seconds.
this my ajax code
$.ajax({
type: "POST",
url: "islem.php",
beforeSend:function(){
$('#table').html("")
$('.load').show()
},
data: {
extension:myCheckboxes,domainName:domainName },
success:function (e) {
$('#table').html(e)
}
Am I missin out something Why should I wait to execute second time

ajax request returns an unexpected output with the correct output

This is the output I get from ajax request to php pdo:
[{"sys_id":"1","task":"qwe","task_date":"11\/30\/2017 8:49 PM","task_person":"qwe","task_status":"0"},{"sys_id":"2","task":"asd","task_date":"11\/30\/2017 9:54 PM","task_person":"asd","task_status":"0"}]null
As shown there is an excess null value which I cant figure out where it is coming from my code is:
function selecttask(action) {
$.ajax({
type: 'POST',
url: '../include/demo.php',
dataType: "json",
data: {
action: action
},
success: function(data) {
}
}).done(function(data) {
});
}
selecttask("selectall");
My demo.php is:
<?php
include_once("crud.php");
//include_once("../config/config.php");
//$con = new connect_pdo();
$crud = new Crud();
$action = $_POST['action'];
$data = $_POST['data'];
switch (strtolower($action)):
case("selectall"):
$table = "list_tbl";
$selectall = $crud->selectall($table);
echo json_encode($selectall, JSON_UNESCAPED_UNICODE);
break;
case("add"):
$table = "list_tbl";
$insert = $crud->insert($table,$data);
echo json_encode($insert, JSON_UNESCAPED_UNICODE);
break;
endswitch;
?>
Then crud is:
<?php
include_once("../config/config.php");
class Crud extends connect_pdo {
public $_con;
function __construct() {
parent::__construct();
$this->_con = $this->dbh();
}
public function selectall($table_name) {
$queryselectall = "Select * from {$table_name}";
$selectall = $this->_con->prepare($queryselectall);
if ($selectall->execute()) {
if ($selectall->rowCount() > 0) {
$result = $selectall->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result, JSON_UNESCAPED_UNICODE);
}else{
echo array('error'=> TRUE, 'message'=> 'No result found.');
}
}
}
public function insert($table_name, $res) {
parse_str($res, $data);
$limit = count($data);
$ctr = 0;
$columns = "";
$values = "";
foreach ($data as $key => $value) {
$ctr++;
$columns.= "{$key}";
$values .= ":{$key}";
if ($ctr < $limit) {
$columns.= ",";
$values .= ",";
}
}
$query = "INSERT INTO {$table_name} ({$columns})VALUES({$values})";
try {
$create = $this->_con->prepare($query);
foreach ($data as $key => $value) {
$keys = ":{$key}";
$create->bindValue($keys, $value, PDO::PARAM_STR);
}
if ($create->execute()) {
$lastinserted_id = $this->_con->lastInsertId();
echo array('error' => FALSE, 'message' => 'Data added successfully.', 'lastinserted_id' => $lastinserted_id, 'query' => $query);
} else {
echo array('error' => TRUE, 'message' => 'Execution failed, please contact system support!');
}
} catch (Exception $ex) {
echo array('error' => TRUE, 'message' => $ex);
}
}
}
?>
From the above code I cant determine where the null is coming from.
Did I miss something that is why null is coming as result of ajax request
Probably a better architecture for your Crud class to handle DB interactions by running the queries and returning the results as an array (or throwing an exception if anything exceptional happens). Then your demo.php script can just get the array from the Crud class method and handle the output (json encoding, response output).

Ajax response from Zend frameword

Recently, I've been trying to create an online CRM using jquery/php/xml-rpc and I've had an issue that I just can't seem to find the solution to.
I currently have an ajax request sending an element id to a php document that when opened on its own (as a direct url to the document) returns a response from the API server (either a Boolean or some error like 'wrong data').
However this doesn't come out to my page at all and I am not sure the data I am sending is even getting through to the php document.
This is my jquery code:
$('#SomeElement').on('click', function(){
var id = $('#ELEMENTID').attr('value');
$.ajax ({
type:'POST',
url: 'PHPfile.php',
dataType: 'json',
data: {id:id},
success: function(data) {
if(data.indexOf('YES') === -1){
$('.alert-success').show();
$('.alert-success').html(data);
/*setTimeout(function() {
$('.alert-success').fadeOut('slow');
location.reload();
}, 2000);*/
} else {
$('.alert-danger').show();
$('.alert-danger').html(data);
/*setTimeout(function() {
$('.alert-danger').fadeOut('slow');
location.reload();
}, 2000);*/
}
}
});
});
And this is my PHP code:
require 'init_autoloader.php';
Zend\Mvc\Application::init(require 'config/application.config.php')->run();
$q = mysqli_query($conn, "SELECT * FROM some db WHERE somekey = '$_POST[id]'");
$main = mysqli_fetch_assoc($q);
if($main['someentry'] !== '0') {
echo 'This is FALSE';
} else {
$r = mysqli_query($conn, "SELECT * FROM side_db WHERE side_id = '$_POST[id]'");
$p = mysqli_query($conn, "SELECT * FROM ext_db WHERE ext_id = '$_POST[id]'");
$m = mysqli_query($conn, "SELECT * FROM img_db WHERE img_id = '$_POST[id]'");
$side = mysqli_fetch_assoc($r);
$ext = mysqli_fetch_assoc($p);
if((int)$ext['gt'] === '0' || (int)$ext['gt'] === '1') {
$g = 'yes';
} else {
$g = 'no';
}
foreach($ext as $key => $value) {
if($key === 'somestring') {
continue;
}else if($value === '0' || $value === '1') {
$ext[$key] = 'no';
} else if($value === '2'){
$ext[$key] = 'yes';
}
}
foreach($main as $k => $v) {
if($v === '0' || $v === '1') {
$main[$k] = 'no';
} else if($v === '2'){
$main[$k] = 'yes';
}
}
require 'init_autoloader.php';
Zend\Mvc\Application::init(require 'config/application.config.php')->run();
$appkey = 'appkey';
$someid = id;
$something = 'something';
$else = 'else';
$divarray = Array
(
'HEAL' = Array(
[0] = "WARLOCK",
[1] = "PRIEST",
[2] = "ROGUE",
[3] = "WARRIOR",
[4] = "MAGE"
),
"someENTRY" = 'YES'
);
$oxClient = new \Zend\XmlRpc\Client('http://link-to-server.php');
$somenewrequest = $oxClient->call('class.OfAPI',array($appkey,$someid,$something,$else,$divarray));
$res = $oxClient->getLastResponse();
echo $res;
$client = new \Zend\XmlRpc\Client('http://link-to-server.php');
if($m !== FALSE) {
$j = 1;
while($img = mysqli_fetch_assoc($m)) {
$pather = str_replace('../',"",$img['img_path']);
$url = str_replace('www.', "", $_SERVER['HTTP_HOST']);
$imagedata = file_get_contents('OUR/FILE/PATH/OF/SERVER'.$url.'/'.$pather);
$base64 = base64_encode($imagedata);
$SOMEID = $res;
$image = $base64;
$client->call('CLASS.IMAGESOMETHING',array($appkey,$usr,$psw,$res,$image));
$j++;
}
}
$fin = mysqli_query($conn, "UPDATE our_db SET avalue = '1' WHERE somefield = '$_POST[id]'");
echo 'You succeeded in doing w/e';
}
Excluding all the small errors I might have done due to having to rewrite half of the code to protect sensitive information, I want to know what I can change so that I can see the responses pop up on the page where the ajax is run.
I tried JSON.encode on the $res but that didn't seem to solve anything. Is there something I am missing or something I can do differently to get the responses I need or even see if the ajax variable is getting through to the php document.
Either way I would be happy to know what I am doing wrong so I can improve and not have to run into the problem in the future.
Thanks in advance!
In your $.(ajax) please put id in quotes to make sure it is interpreted as field name:
data: {'id':id},
Use developer-tools of google chrome to inspect your POST-request going to the server. Here a very good intro:
https://blog.versionone.com/spy-on-browser-http-requests/

php Notice: array to string conversion

hi all im new ish to php and new to stack overflow but do have some knowledge in php what im trying to do is get one value from my returned array call from an api function is
$character->getSlot('head');
using print_r gives me:
Array (
[icon] => http://url to image location
[name] => Wizard's Petasos
[slot] => head )
if i echo $character->getSlot('head', 'name); gives me C:\xampp\htdocs\test\index.php on line 19 and just returns the word Array
here is the section of index.php
<?php
include('api.php');
// Call API
$API = new LodestoneAPI();
// Search for: Demonic Pagan on Sargatanas
$character = $API->get(array(
"name" => "Darka Munday",
"server" => "Ragnarok"
));
// Basic character data
echo "Character ID: " . $character->getID();
$ID = $character->getID();
$API->parseProfile($ID);
$Character = $API->getCharacterByID($ID);
echo $character->getSlot('head', 'name');
and the section of the api just in case
// GEAR
public function setGear($Array)
{
$this->Gear['slots'] = count($Array);
$GearArray = NULL;
// Loop through gear equipped
$Main = NULL;
foreach($Array as $A)
{
// Temp array
$Temp = array();
// Loop through data
$i = 0;
foreach($A as $Line)
{
// Item Icon
if (stripos($Line, 'socket_64') !== false) { $Data = trim(explode('"', $A[$i + 1])[1]); $Temp['icon'] = $Data; }
if (stripos($Line, 'item_name') !== false) { $Data = trim(str_ireplace(array('>', '"'), NULL, strip_tags(html_entity_decode($A[$i + 2])))); $Temp['name'] = htmlspecialchars_decode(trim($Data), ENT_QUOTES); }
if (stripos($Line, 'item_name') !== false) {
$Data = htmlspecialchars_decode(trim(html_entity_decode($A[$i + 3])), ENT_QUOTES);
if (
strpos($Data, " Arm") !== false ||
strpos($Data, " Grimoire") !== false ||
strpos($Data, " Tool") !== false
)
{ $Main = $Data; $Data = 'Main'; }
$Temp['slot'] = strtolower($Data);
}
// Increment
$i++;
}
// Slot manipulation
$Slot = $Temp['slot'];
if (isset($GearArray[$Slot])) { $Slot = $Slot . 2; }
// Append array
$GearArray['numbers'][] = $Temp;
$GearArray['slots'][$Slot] = $Temp;
}
// Set Gear
$this->Gear['equipped'] = $GearArray;
// Set Active Class
$classjob = str_ireplace('Two-Handed ', NULL, explode("'", $Main)[0]);
$this->Stats['active']['class'] = $classjob;
if (isset($this->Gear['soul crystal'])) { $this->Stats['active']['job'] = str_ireplace("Soul of the ", NULL, $this->Gear['soul crystal']['name']); }
}
public function getGear() { return $this->Gear; }
public function getEquipped($Type) { return $this->Gear['equipped'][$Type]; }
public function getSlot($Slot) { return $this->Gear['equipped']['slots'][$Slot]; }
the solution to this is probably really simple and im being really dumb but any help would be great :) thanks in advance
public function getSlot($Slot) {
return $this->Gear['equipped']['slots'][$Slot];
}
getSlot method have only one argument. You are passing another argument but getSlot method returns array.
You can do like this :
public function getSlot($Slot, $param = null) {
if(empty($param)) {
return $this->Gear['equipped']['slots'][$Slot];
} else {
if(isset($this->Gear['equipped']['slots'][$Slot][$param] )) {
return $this->Gear['equipped']['slots'][$Slot][$param];
} else {
return null;
}
}
}
OR
echo $character->getSlot('head')['name'] // If version is >= 5.4.*
If version < 5.4.*
$slot = $character->getSlot('head');
echo $slot['name'];

exif_imagetype() [function.exif-imagetype]:

hi all when Using exif_imagetype() [function.exif-imagetype]: function for checking images if the user hits the submit button without uploading anything the exif function returns an error in the webpage itself. my question is how to get rid of this error. am pasting the error below
Warning: exif_imagetype() [function.exif-imagetype]: Filename cannot be empty in /mounted- storage/home98a/sub009/sc61374-HGPS/sitakalyanam.com/newsita/php4upload.class.php on line 88
<?php
/*
- PHP4 Image upload script
*/
class imageupload
{
//pblic variables
var $path = '';
var $errorStr = '';
var $imgurl = '';
//private variables
var $_errors = array();
var $_params = array();
var $_lang = array();
var $_maxsize = 1048576;
var $_im_status = false;
//public methods
function imageupload ()
{
//require 'photouploadconfig.php';
if($_GET['Choice']=="1")
{
require 'Photouploddir1.php';
}
elseif ($_GET['Choice']=="2")
{
require 'Photouploddir2.php';
}
elseif ($_GET['Choice']=="3")
{
require 'Photouploddir3.php';
}
elseif ($_GET['horoschoice']=="1")
{
require 'horosuploaddir.php';
}
elseif ($_GET['videoChoice']=="5")
{
require 'videouploaddir.php';
}
$this->_types = $types;
$this->_lang = $lang;
$this->_upload_dir = $upload_dir;
$this->_maxsize = $maxsize;
$this->path = $PHP_SELF;
if (is_array($_FILES['__upload']))
{
$this->_params = $_FILES['__upload'];
if (function_exists('exif_imagetype'))
$this->_doSafeUpload();
else
$this->_doUpload();
if (count($this->_errors) > 0)
$this->_errorMsg();
}
}
function allowTypes ()
{
$str = '';
if (count($this->_types) > 0) {
$str = 'Allowed types: (';
$str .= implode(', ', $this->_types);
$str .= ')';
}
return $str;
}
// private methods
function _doSafeUpload ()
{
preg_match('/\.([a-zA-Z]+?)$/', $this->_params['name'], $matches);
if (exif_imagetype($this->_params['tmp_name']) && in_a rray(strtolower($matches[1]), $this->_types))
{
if ($this->_params['size'] > $this->_maxsize)
$this->_errors[] = $this->_lang['E_SIZE'];
else
$this->_im_status = true;
if ($this->_im_status == true)
{
$ext = substr($this->_params['name'], -4);
$this->new_name = md5(time()).$ext;
move_uploaded_file($this->_params['tmp_name'], $this->_up load_dir.$this->new_name);
$this->imgurl =$this->new_name;
//$this->imgurl = .$this->new_name;
}
}
else
$this->_errors[] = $this->_lang['E_TYPE'];
}
function _doUpload ()
{
preg_match('/\.([a-zA-Z]+?)$/', $this->_params['name'], $matches);
if(in_array(strtolower($matches[1]), $this->_types))
{
if ($this->_params['size'] > $this->_maxsize)
$this->_errors[] = $this->_lang['E_SIZE'];
else
$this->_im_status = true;
if ($this->_im_status == true)
{
$ext = substr($this->_params['name'], -3);
$this->new_name = md5(time()).$ext;
move_uploaded_file($this->_params['tmp_name'], $this- >_upload_dir.$this->new_name);
$this->imgurl = ''.$this->new_name;
//$this->imgurl = ''.$this->_upload_dir.''.$this->new_name;
//$this->imgurl = ''.$this->new_name;
//$this->imgurl = $this->_upload_dir.'/'.$this->new_name;
}
}
else
$this->_errors[] = $this->_lang['E_TYPE'];
}
function _errorMsg()
{
$this->errorStr = implode('<br />', $this->_errors);
}
}
?>
You are getting that message because you are never checking if the user uploaded a file or not, you're just assuming they are. When the user does not upload a file then $_FILES will be an empty array.
That means that $this->_params['tmp_name'] won't exist. You need to check if a file was uploaded, not just assume one was.
Just simply check the size of $_FILES.
if(count($_FILES) === 0){
echo "no file uploaded";
}
Change your code to this one and then try
if (isset($_FILES['__upload']))
{
$this->_params = $_FILES['__upload'];
if (function_exists('exif_imagetype'))
$this->_doSafeUpload();
else
$this->_doUpload();
if (count($this->_errors) > 0)
$this->_errorMsg();
}

Categories