PHP Notice : undefined offset : 3 in my array [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
*/
// File called with:
// e_PLUGIN_ABS."log/log.php?referer=' + ref + '&color=' + colord + '&eself=' + eself + '&res=' + res + '\">' );\n";
// referer= ref
// color= colord
// eself= eself
// res= res
// err_direct - optional error flag
// err_referer - referrer if came via error page
define("log_INIT", TRUE);
$colour = strip_tags((isset($_REQUEST['color']) ? $_REQUEST['color'] : ''));
$res = strip_tags((isset($_REQUEST['res']) ? $_REQUEST['res'] : ''));
$self = strip_tags((isset($_REQUEST['eself']) ? $_REQUEST['eself'] : ''));
$ref = addslashes(strip_tags((isset($_REQUEST['referer']) ? $_REQUEST['referer'] : '')));
$date = date("z.Y", time());
$logPfile = "logs/logp_".$date.".php";
// vet resolution and colour depth some more - avoid dud values
if ($res && preg_match("#.*?((\d+)\w+?(\d+))#", $res, $match))
{
$res = $match[2].'x'.$match[3];
}
else
{
$res = '??'; // Can't decode resolution
}
if ($colour && preg_match("#.*?(\d+)#",$colour,$match))
{
$colour = intval($match[1]);
}
else
{
$colour='??';
}
if ($err_code = strip_tags((isset($_REQUEST['err_direct']) ? $_REQUEST['err_direct'] : '')))
{
$ref = addslashes(strip_tags(isset($_REQUEST['err_referer']) ? $_REQUEST['err_referer'] : ''));
$log_string = $err_code.",".$self.",".$ref;
// Uncomment the next two lines to create a separate CSV format log of invalid accesses - error code, entered URL, referrer
// $logname = "logs/errpages.csv";
// $logfp = fopen($logname, 'a+'); fwrite($logfp, $log_string."\n\r"); fclose($logfp);
$err_code .= ':';
}
if(strstr($ref, "admin"))
{
$ref = FALSE;
}
$screenstats = $res."#".$colour;
$agent = $_SERVER['HTTP_USER_AGENT'];
$ip = getip();
$oldref = $ref; // backup for search string being stripped off for referer
if($ref && !strstr($ref, $_SERVER['HTTP_HOST']))
{
if(preg_match("#http://(.*?)($|/)#is", $ref, $match))
{
$ref = $match[0];
}
}
$pageDisallow = "cache|file|eself|admin";
$tagRemove = "(\\\)|(\s)|(\')|(\")|(eself)|( )|(\.php)|(\.html)";
$tagRemove2 = "(\\\)|(\s)|(\')|(\")|(eself)|( )";
preg_match("#/(.*?)(\?|$)#si", $self, $match);
$match[1] = isset($match[1]) ? $match[1] : '';
$pageName = substr($match[1], (strrpos($match[1], "/")+1));
$PN = $pageName;
$pageName = preg_replace("/".$tagRemove."/si", "", $pageName);
if($pageName == "") $pageName = "index";
$pageName = $err_code.$pageName; // Add the error code at the beginning, so its treated uniquely
if(preg_match("/".$pageDisallow."/i", $pageName)) return;
$p_handle = fopen($logPfile, 'r+');
if($p_handle && flock( $p_handle, LOCK_EX ) )
{
$log_file_contents = '';
while (!feof($p_handle))
{ // Assemble a string of data
$log_file_contents.= fgets($p_handle,1000);
}
$log_file_contents = str_replace(array('<'.'?php','?'.'>'),'',$log_file_contents);
if (eval($log_file_contents) === FALSE) echo "error in log file contents<br /><br /><br /><br />";
}
else
{
echo "Couldn't log data<br /><br /><br /><br />";
exit;
}
$flag = FALSE;
if(array_key_exists($pageName, $pageInfo))
{ // Existing page - just increment stats
$pageInfo[$pageName]['ttl'] ++;
}
else
{ // First access of page
$url = preg_replace("/".$tagRemove2."/si", "", $self);
if(preg_match("/".$pageDisallow."/i", $url)) return;
$pageInfo[$pageName] = array('url' => $url, 'ttl' => 1, 'unq' => 1);
$flag = TRUE;
}
if(!strstr($ipAddresses, $ip))
{ /* unique visit */
if(!$flag)
{
$pageInfo[$pageName]['unq'] ++;
}
$siteUnique ++;
$ipAddresses .= $ip."."; // IP address is stored as hex string
require_once("loginfo.php");
}
$siteTotal ++;
$info_data = var_export($pageInfo, true);
//$date_stamp = date("z:Y", time()); // Same as '$date' variable
$data = "<?php
/* e107 website system: Log file: {$date} */
\$ipAddresses = '{$ipAddresses}';
\$siteTotal = '{$siteTotal}';
\$siteUnique = '{$siteUnique}';
\$pageInfo = {$info_data};
?>";
if ($p_handle)
{
ftruncate( $p_handle, 0 );
fseek( $p_handle, 0 );
fwrite($p_handle, $data);
fclose($p_handle);
}
function getip($mode=TRUE)
{
if (getenv('HTTP_X_FORWARDED_FOR'))
{
$ip = $_SERVER['REMOTE_ADDR'];
if (preg_match("#^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})#", getenv('HTTP_X_FORWARDED_FOR'), $ip3))
{
$ip2 = array('#^0\..*#',
'#^127\..*#', // Local loopbacks
'#^192\.168\..*#', // RFC1918 - Private Network
'#^172\.(?:1[6789]|2\d|3[01])\..*#', // RFC1918 - Private network
'#^10\..*#', // RFC1918 - Private Network
'#^169\.254\..*#', // RFC3330 - Link-local, auto-DHCP
'#^2(?:2[456789]|[345][0-9])\..*#' // Single check for Class D and Class E
);
$ip = preg_replace($ip2, $ip, $ip3[1]);
}
}
else
{
$ip = $_SERVER['REMOTE_ADDR'];
}
if ($ip == "")
{
$ip = "x.x.x.x";
}
if($mode)
{
$ipa = explode(".", $ip);
return sprintf('%02x%02x%02x%02x', $ipa[0], $ipa[1], $ipa[2], $ipa[3]);
}
else
{
return $ip;
}
}
?>​
ERROR CODED : PHP Notice : undefined offset : 3 in C:\inetpub\wwwroot\oss_plugins\log\log.php on line 202
Below is the log.php file in wwwroot folder : line 202 is the 3rd line from the
bottom where it states
(return sprintf('%02x%02x%02x%02x', $ipa[0], $ipa[1],
$ipa[2], $ipa[3]);

The length of your array $ipa is 3 then' you don't have $ipa[3].
replace your line 202 with this:
return sprintf('%02x%02x%02x', $ipa[0], $ipa[1], $ipa[2]);
If you want use your line 202:
return sprintf('%02x%02x%02x%02x', $ipa[0], $ipa[1], $ipa[2], $ipa[3]);
You must check that your $ip must be like this
x.x.x.x
the error is because the format is
x.x.x
Check your code.

Related

Returning a variable from a function in php class (return not working only echo works)

I have a PHP class that highlights names mentioned in a text as links.It can search for #character in a given text and check the names that follow that character.
Theproblem is that the return value from class does not get printed out when I echo the method (public function process_text ($text_txt){}) that is responsible for processing the text. But when I change the return language construct to print or echo, then the parsing is successful and the processed string is printed out. I need to return and not print so as to be able to store the return string in a comments table of my CMS.
Kindly see full code below and advise:
class mentions {
public $print_content = '';
private $m_names = array();
private $m_denied_chars = array(
"#",
"#",
"?",
"¿"
);
private $m_link = "http://example.com/"; // + name of the username, link or whatever
/*
* this class can also be used for specific links
* start editing from here
* */
public function add_name ($name) {
array_push($this->m_names, $name);
}
public function process_text ($text_txt) {
$expl_text = explode(" ", $text_txt);
/*
* a character will be ignores which can be specified next this comment
* :)
* */
$sp_sign = "#"; // this is what you can change freely...
for ($i = 0; $i < count($expl_text); ++$i) {
$spec_w = $expl_text[$i];
$print_link = false;
$name_link = "";
if ($spec_w[0] == $sp_sign) { // then can be a mention...
$name = "";
$break_b = false;
for ($x = 1; $x < strlen($spec_w); ++$x) {
if ($spec_w[$x] == '.' || $spec_w[$x] == ",") {
if (in_array($name, $this->m_names)) {
$print_link = true;
$name_link = $name;
break;
}
}
if (in_array($spec_w[$x], $this->m_denied_chars)) {
$break_b = true;
break;
}
$name .= $spec_w[$x];
}
if ($break_b == true) {
$print_link = false;
break;
} else {
if (in_array($name, $this->m_names)) {
$print_link = true;
$name_link = $name;
}
}
}
if ($print_link == true) {
$this->print_content = "".$spec_w."";
if ($i < count($expl_text)) $this->print_content .= " ";
} else {
$this->print_content = $spec_w;
if ($i < count($expl_text)) $this->print_content .= " ";
}
return $this->print_content;
}
}
}
###### create new class object and process raw data ######
$mentions = new mentions;
$raw_data = 'Hello, #Angelina. I am #Bob_Marley.';
$expr = '#(?:^|\W)#([\w-]+)#i';
preg_match_all($expr, $raw_data, $results);
if( !empty($results[1]) ) {
foreach( $results[1] as $user ) {
$mentions->add_name($user);
}
/*
------------------------------------
*/
$commenData = $mentions->process_text($raw_data);
echo $commenData;
}
answer by #Terminus. If you have a return inside of a loop, the loop (and the entire function) will be interrupted and the value being returned will immediately be returned. That's just how it works. Was trying to write that as a good answer but couldn't. Did end up rewriting your class a bit. ideone.com/vaV0d2 note that i left in a test var_dump and that the output provided by ideone doesn't allow link tags to be displayed as html but if you run it from a server, it'll be correct

How do I modify an existing file to add the ability to unlink a specific file from a folder?

Thank you StackOverflow experts for looking at my question.
First, It is possible this question has been asked before but my situation is a bit unique. So, please hear me out.
When our users want to edit an existing record, they would also like to have the ability to delete an existing pdf file if one exists before adding a new one.
To display an existing file, I use this code.
<td class="td_input_form">
<?php
// if the BidIDFile is empty,
if(empty($result["BidIDFile"]))
{
//then show file upload field for Bid File
echo '<input type="file" name="BidIDFile[]" size="50">';
}
else
{
// Bid file already upload, show checkbox to delete it.
echo '<input type="checkbox" name="delete[]" value="'.$result["BidIDFile"].'"> (delete)
'.$result["BidIDFile"].'';
}
</td>
Then to delete this file, I use the following code:
// Connect to SQL Server database
include("connections/Connect.php");
// Connect to SQL Server database
include("connections/Connect.php");
$strsID = isset($_GET["Id"]) ? $_GET["Id"] : null;
if(isset($_POST['delete']))
{
// whilelisted table columns
$fileColumnsInTable = array( 'BidIDFile', 'TabSheet', 'SignInSheet', 'XConnect',
'Addend1', 'Addend2','Addend3','Addend4','Addend5', 'Addend6');
$fileColumns = array();
foreach ($_POST['delete'] as $fileColumn)
{
if(in_array($fileColumn, $fileColumnsInTable))
$fileColumns[] = $fileColumn;
}
// get the file paths for each file to be deleted
$stmts = "SELECT " . implode(', ', $fileColumns) . " FROM bids WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
$files = sqlsrv_fetch_array($querys,SQLSRV_FETCH_ROW);
// loop over the files returned by the query
foreach ($files as $file )
{
//delete file
unlink($file);
}
// now remove the values from the table
$stmts = "UPDATE bids SET " . impload(' = '', ', $fields) . " WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
This works fine. However, the edit file points to an existing file with an INSERT and UPDATE operation in this one file (great thanks to rasclatt) and I am having problem integrating the two together.
Can someone please help with integrating the two files into one?
Thanks in advance for your assistance.
Here is the INSERT and UPDATE file:
<?php
error_reporting(E_ALL);
class ProcessBid
{
public $data;
public $statement;
public $where_vals;
protected $keyname;
protected $conn;
public function __construct($conn = false)
{
$this->conn = $conn;
}
public function SaveData($request = array(),$skip = false,$keyname = 'post')
{
$this->keyname = $keyname;
$this->data[$this->keyname] = $this->FilterRequest($request,$skip);
return $this;
}
public function FilterRequest($request = array(), $skip = false)
{
// See how many post variables are being sent
if(count($request) > 0) {
// Loop through post
foreach($request as $key => $value) {
// Use the skip
if($skip == false || (is_array($skip) && !in_array($key,$skip))) {
// Create insert values
$vals['vals'][] = "'".ms_escape_string($value)."'";
// Create insert columns
$vals['cols'][] = "".str_replace("txt","",$key)."";
// For good measure, create an update string
$vals['update'][] = "".str_replace("txt","",$key)."".' = '."'".ms_escape_string($value)."'";
// For modern day binding, you can use this array
$vals['bind']['cols'][] = "".$key."";
$vals['bind']['cols_bind'][] = ":".$key;
$vals['bind']['vals'][":".$key] = $value;
$vals['bind']['update'][] = "".$key.' = :'.$key;
}
}
}
return (isset($vals))? $vals:false;
}
public function AddFiles($name = 'item')
{
// If the files array has been set
if(isset($_FILES[$name]['name']) && !empty($_FILES[$name]['name'])) {
// Remove empties
$_FILES[$name]['name'] = array_filter($_FILES[$name]['name']);
$_FILES[$name]['type'] = array_filter($_FILES[$name]['type']);
$_FILES[$name]['size'] = array_filter($_FILES[$name]['size']);
$_FILES[$name]['tmp_name'] = array_filter($_FILES[$name]['tmp_name']);
// we need to differentiate our type array names
$use_name = ($name == 'item')? 'Addend':$name;
// To start at Addendum1, create an $a value of 1
$a = 1;
if(!empty($_FILES[$name]['tmp_name'])) {
foreach($_FILES[$name]['name'] as $i => $value ) {
$file_name = ms_escape_string($_FILES[$name]['name'][$i]);
$file_size = $_FILES[$name]['size'][$i];
$file_tmp = $_FILES[$name]['tmp_name'][$i];
$file_type = $_FILES[$name]['type'][$i];
if(move_uploaded_file($_FILES[$name]['tmp_name'][$i], $this->target.$file_name)) {
// Format the key values for addendum
if($name == 'item')
$arr[$use_name.$a] = $file_name;
// Format the key values for others
else
$arr[$use_name] = $file_name;
$sql = $this->FilterRequest($arr);
// Auto increment the $a value
$a++;
}
}
}
}
if(isset($sql) && (isset($i) && $i == (count($_FILES[$name]['tmp_name'])-1)))
$this->data[$name] = $sql;
return $this;
}
public function SaveFolder($target = '../uploads/')
{
$this->target = $target;
// Makes the folder if not already made.
if(!is_dir($this->target))
mkdir($this->target,0755,true);
return $this;
}
public function where($array = array())
{
$this->where_vals = NULL;
if(is_array($array) && !empty($array)) {
foreach($array as $key => $value) {
$this->where_vals[] = $key." = '".ms_escape_string($value)."'";
}
}
return $this;
}
public function UpdateQuery()
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$update[] = implode(",",$arr['update']);
}
}
$vars = (isset($update) && is_array($update))? implode(",",$update):"";
// Check that both columns and values are set
$this->statement = (isset($update) && !empty($update))? "update bids set ".implode(",",$update):false;
if(isset($this->where_vals) && !empty($this->where_vals)) {
$this->statement .= " where ".implode(" and ",$this->where_vals);
}
return $this;
}
public function SelectQuery($select = "*",$table = 'bids')
{
$stmt = (is_array($select) && !empty($select))? implode(",",$select):$select;
$this->statement = "select ".$stmt." from ".$table;
return $this;
}
public function InsertQuery($table = 'bids')
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
$this->statement = "insert into ".$table;
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$insert['cols'][] = implode(",",$arr['cols']);
$insert['vals'][] = implode(",",$arr['vals']);
}
}
$this->statement .= '(';
$this->statement .= (isset($insert['cols']) && is_array($insert['cols']))? implode(",",$insert['cols']):"";
$this->statement .= ") VALUES (";
$this->statement .= (isset($insert['vals']) && is_array($insert['vals']))? implode(",",$insert['vals']):"";
$this->statement .= ")";
return $this;
}
}
include("../Connections/Connect.php");
function render_error($settings = array("title"=>"Failed","body"=>"Sorry, your submission failed. Please go back and fill out all required information."))
{ ?>
<h2><?php echo (isset($settings['title']))? $settings['title']:"Error"; ?></h2>
<p><?php echo (isset($settings['body']))? $settings['body']:"An unknown error occurred."; ?></p>
<?php
}
// this function is used to sanitize code against sql injection attack.
function ms_escape_string($data)
{
if(!isset($data) || empty($data))
return "";
if(is_numeric($data))
return $data;
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
$non_displayables[] = '/[\x00-\x08]/'; // 00-08
$non_displayables[] = '/\x0b/'; // 11
$non_displayables[] = '/\x0c/'; // 12
$non_displayables[] = '/[\x0e-\x1f]/'; // 14-31
foreach($non_displayables as $regex)
$data = preg_replace($regex,'',$data);
$data = str_replace("'","''",$data);
return $data;
}
// New bid save engine is required for both sql statement generations
$BidSet = new ProcessBid($conn);
$strId = null;
if(isset($_POST["Id"]))
{
$strId = $_POST["Id"];
//echo $strId;
}
If ($strId == "") {
//echo "This is an insert statement";
// This will generate an insert query
$insert = $BidSet->SaveData($_POST)
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->InsertQuery()
->statement;
// Check that statement is not empty
if($insert != false) {
sqlsrv_query($conn,$insert);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to Solicitation screen'));
$err = false;
}
//echo '<pre>';
//print_r($insert);
// echo '</pre>';
}
else
{
//echo "This is an update statement";
// This will generate an update query
$update = $BidSet->SaveData($_POST,array("Id"))
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->where(array("Id"=>$_POST["Id"]))
->UpdateQuery()
->statement;
//echo '<pre>';
//print_r($update);
//echo '</pre>';
// Check that statement is not empty
if($update != false) {
sqlsrv_query($conn,$update);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to admin screen'));
$err = false;
}
}
// This will post an error if the query fails
if((isset($err) && $err == true) || !isset($err))
render_error(); ?>

php file reading displaying unwanted content

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.

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