Warning: strpos() expects parameter 1 to be string, resource - php

I recently migrated a PHP site to my server and after migration I receive this error message. As I'm not really familiar with PHP, I'd really appreciate any help. Thanks.
Warning: strpos() expects parameter 1 to be string, resource given in
.../public_html/store /product_list.php on line 121
Line 121 is as follows...
$exists = (strpos($handle, "Resource id") !== false) ? true : false;
Here is the rest of the code on the top of the page for relevance.
<?php session_start();
include_once("../includes/define.inc.php");
include("../includes/common.php");
include("../includes/mysql_functions.php");
if( isset( $_GET['category'] ) )
{
$exists = checkIfExists("aw_category", "aw_category_urlalias='". $_GET['category']."'", "aw_category_id");
if( !$exists )
{
header("Location: " . PRODUCT_LIST );
}
}
$get_category = ( isset( $_GET['category'] ) ) ? $_GET['category'] : "";
$category_id = ( $get_category == "" ) ? "" : getCategoryIDByAlias( $get_category );
$get_page = (isset($_GET['page']) ) ? $_GET['page'] : 0;
/*category menu*/
$qry_cat = "SELECT aw_category_urlalias, aw_category_id,aw_category_name,aw_category_order,aw_category_status FROM aw_category WHERE aw_category_status = 1 ORDER BY aw_category_order asc";
$result_cat = Query($qry_cat);
/*product*/
$qry_pro = "SELECT *
FROM aw_product
INNER JOIN aw_category
ON aw_product.aw_product_category = aw_category.aw_category_id
INNER JOIN aw_image
ON aw_product.aw_product_id = aw_image.aw_img_prodid
WHERE aw_product.aw_product_status = 1";
if( $category_id == "" )
{ //Feature Product
$qry_pro .= " AND aw_product.aw_product_category = 1";
} else {
$qry_pro .= " AND aw_product.aw_product_category = ".$category_id."";
}
$qry_pro .= " GROUP BY aw_product.aw_product_id
ORDER BY aw_product.aw_product_priority desc,aw_product.aw_product_date desc";
if( $get_category=="" )
{ //Feature Product
$qry_pro .= " LIMIT 6";
}
$result_pro = Query( $qry_pro );
//$row_pro = mysql_fetch_array($result_pro);
$result_pro2 = Query( $qry_pro );
if( !$get_category == "" )
{
/*Pagination*/
$num_per_page= 12;
$num_rows = mysql_num_rows($result_pro);
$num_pages = ceil($num_rows/$num_per_page);
$nav = "";
$begin = $get_page * $num_per_page;
$qry_pro .= " LIMIT " . $begin . ",12";
$result_pro = Query( $qry_pro );
$row_pro = mysql_fetch_array($result_pro);
if( $get_page > 0 )
{
$nav ="<a class=\"page_a\" href=\"".PRODUCT_LIST."?category=".$get_category."&page=".( $get_page-1 )."\">« Previous</a> | ";
}
for($p=0;$p<$num_pages;$p++)
{
if($get_page == $p)
$nav .="<a class=\"page_a\" style='text-decoration:underline' href=\"".PRODUCT_LIST."?category=".$get_category."&page=".$p."\">".($p+1)."</a> | ";
else
$nav .="<a class=\"page_a\" href=\"".PRODUCT_LIST."?category=".$get_category."&page=".$p."\">".($p+1)."</a> | ";
}
if($get_page<$num_pages-1)
{
$nav .="<a class=\"page_a\" href=\"".PRODUCT_LIST."?category=".$get_category."&page=".($get_page+1)."\"> Next »</a>";
}
}//-------
/*news*/
$qry_news = "SELECT aw_news_title FROM aw_news ORDER BY aw_news_date desc LIMIT 8";
$result_news = Query($qry_news);
function getCategoryIDByAlias( $alias )
{
$query = "SELECT aw_category_id FROM aw_category WHERE aw_category_urlalias='".$alias."'";
$rs = Query( $query );
$row = mysql_fetch_array( $rs );
return $row['aw_category_id'];
}
function checkIfThumbExists( $thumb )
{
//$exists = ( file_exists( $img_src_thumb ) ) ? true : false;
//echo $exists;
//$exists = ( is_file( $img_src_thumb ) ) ? true : false;
//echo $exists;
//$AgetHeaders = #get_headers( $img_src_thumb );
//$exists = ( preg_match( "|200|", $AgetHeaders[0] ) ) ? true : false;
//echo $exists;
//$header_response = get_headers($img_src_thumb, 1);
//$exists = ( strpos( $header_response[0], "404" ) !== false ) ? false : true;;
//echo $exists;
$handle = #fopen($thumb, 'r');
$exists = (strpos($handle, "Resource id") !== false) ? true : false;
if( $exists )
{
$size = getimagesize( $thumb );
if( $size[3] == 'width="214" height="214"')
{
$exists = true;
} else {
$exists = false;
}
}
return $exists;
}
?>

Try replacing line 121 with the following:
$handle = #file_get_contents($thumb);

$handle = #fopen($thumb, 'r');
$handle not is string

The error is clear. Read manual of stropos()
It need to take a string in parameter, but in you case you set there one source($handle = #fopen($thumb, 'r');) and one string("Resource id")
Use file_get_contents, as example.

fopen returns a resource and strpos expects the first parameter to be a string.
You may use file_get_contents instead, but are you sure you want to check the binary data of a image?
$data = file_get_contents($thumb);

I don't know what are you trying to do with this line, but if you want to weather the file exists or not, i recommend you to use the native PHP functión file_exists, that gives you the chance to check if the file exists or not:
$exists = file_exists($thumb)
Here is PHP reference.
http://es1.php.net/manual/es/function.file-exists.php

As mentioned in other answers you are giving strpos a file handle or 'resource', which is wrong.
However, it looks like you want to test is if the file exists so I would simply do:
$handle = #fopen($thumb, 'r');
if($handle)
{
// File exists
}
else
{
// File doesn't exist
}
As fopen() will return a pointer (resource) if the file can be opened, else false if not.
file_get_contents() looks like the wrong option as it appears you are trying to open and image, so why would you want to search the binary for a string.

Related

Ajax call not waiting for server response

I am using WAMP v.2.5 on a Windows10 machine. My project is a PHP project running off a MySQL DB. It includes numerous AJAX calls, which work fine. I have one specific call however which is giving me a 'Unexpected end of input' error.
The call is made from a View, is directed to a global ajax handler PHP script which forwards the request to the Controller, which then asks the Model for the response. The appropriate Model method is being fired. The method contains error checking and will throw exceptions for an empty result. The DB Query within is valid, and returns results when used in the console. 9 times out of 10 however, the ajax fn will complete without receiving / reading the result of the query and thus generates the above error. Sometimes it will work fine.
When placed on a live server, everything works as it should. It's almost as if the script was running too quickly on the local machine to wait for the DB response or for any exception to be thrown.
Can anyone tell me how to properly test what's happening, or have a solution to the above problem?
EDIT:
Trail of affected code:
$(document).ready(function()
{
//some code
updateFilteredScheduleList();
//some code
});
function updateFilteredScheduleList()
{
var opts = $.extend(true, {}, dialogOptions);
getFilteredScheduleResults()
.done(function(returnedData)
{
var returnedDataObj = parseAjaxJSONResponse(returnedData);
if(returnedDataObj.hasOwnProperty('success'))
buildScheduleList(returnedDataObj.response);
})
.error(function(xhr, options, error)
{
opts.message = error;
displayDialog(opts);
return false;
});
}
function getFilteredScheduleResults()
{
var values = getFilterValues();
values.controller = 'WSVisits';
values.method = 'getFilteredScheduleResults';
console.log(values);
return $.ajax({
type: 'post',
cache: false,
data: values,
url: controllersAjaxPath
});
}
function getFilterValues()
{
var values = {};
//get values of view filters
return values;
}
function parseAjaxJSONResponse(data)
{
var opts = $.extend(true, {}, dialogOptions);
try
{
var tmp = JSON.parse(data);
if(tmp.hasOwnProperty('error'))
{
opts.message = tmp.error;
displayDialog(opts);
return false;
}
return tmp;
}
catch(e)
{
opts.message = e.message;
displayDialog(opts);
return false;
}
}
PHP method (slightly edited):
function getFilteredScheduleResults($args = null)
{
$id = intval($args['MyID']);
$region_id = (!$id) ? ( intval($args['RegionID']) > 0) ? intval($args['RegionID']) : 0 : 0;
$county_id = (!$id) ? ( intval($args['CountyID']) > 0) ? intval($args['CountyID']) : 0 : 0;
$language_id = (!$id) ? ( intval($args['LanguageID']) > 0) ? intval($args['LanguageID']) : 0 : 0;
$center_id = (!$id) ? ( intval($args['CenterID']) > 0) ? intval($args['CenterID']) : 0 : 0;
$type_id = (!$id) ? ( intval($args['TypeID']) > 0) ? intval($args['TypeID']) : 0 : 0;
$support_type_id = (!$id) ? ( intval($args['SupportTypeID']) > 0) ? intval($args['SupportTypeID']) : 0 : 0;
$address_token = (!$id) ? ( trim($args['AddressContains']) !== '') ? trim($args['AddressContains']) : null : null;
$purpose_id = (intval($args['PurposeID']) > 0) ? intval($args['PurposeID']) : 0;
$associate_id = (intval($args['AssociateID']) > 0) ? intval($args['AssociateID']) : 0;
if(!empty($args['From']))
{
$from_obj = DateTime::createFromFormat('d/m/Y', $args['From']);
$args['From'] = (!$from_obj) ? null : $from_obj->format('Y-m-d');
}
if(!empty($args['To']))
{
$to_obj = DateTime::createFromFormat('d/m/Y', $args['To']);
$args['To'] = (!$to_obj) ? null : $to_obj->format('Y-m-d');
}
$sql = " /*query*/ WHERE 1 ";
if($id)
$sql.= " AND ( s.MyID = :MyID ) ";
else
{
if($region_id)
$sql.= " AND ( RegionID = :RegionID ) ";
if($county_id)
$sql.= " AND ( CountyID = :CountyID ) ";
if($language_id)
$sql.= " AND ( LanguageID = :LanguageID ) ";
if($center_id)
$sql.= " AND ( CenterID = :CenterID ) ";
if($type_id)
$sql.= " AND ( s.TypeID = :TypeID ) ";
if($support_type_id)
$sql.= " AND ( SupportTypeID = :SupportTypeID ) ";";
if(!is_null($address_token))
$sql.= " AND ( UPPER(CONCAT_WS(' ', Add1, Add2, Add3, CityTown)) LIKE UPPER(:AddressToken) ) ";
}
$sql.= " GROUP BY s.MyID ORDER BY MyName ASC ";
$db = new Database();
try
{
$db->query($sql);
if($id)
$db->bind(':MyID', $id);
else
{
if($region_id)
$db->bind(':RegionID', $region_id);
if($county_id)
$db->bind(':CountyID', $county_id);
if($language_id)
$db->bind(':LanguageID', $language_id);
if($center_id)
$db->bind(':CenterID', $center_id);
if($type_id)
$db->bind(':TypeID', $type_id);
if($support_type_id)
$db->bind(':SupportTypeID', $support_type_id);
if(!is_null($address_token))
$db->bind(':AddressToken', '%' . $address_token . '%');
}
$db->execute();
$tmp = $db->fetchAllAssoc();
$get_assignments_only = (!empty($args['AssignmentsOnly']));
$returned = [];
$sql = " SELECT VisitID FROM visits_ws WHERE MyID = :MyID ";
if($purpose_id)
$sql.= " AND ( VisitPurposeID = :Purpose ) ";
if($associate_id)
$sql.= " AND ( ( Associate1ID = :AssociateID ) OR ( Associate2ID = :AssociateID ) OR ( Associate3ID = :AssociateID ) OR ( Associate4ID = :AssociateID ) ) ";
if(!empty($args['From']))
$sql.= " AND ( VisitDate >= :From ) ";
if(!empty($args['To']))
$sql.= " AND ( VisitDate <= :To ) ";
$db->query($sql);
foreach($tmp as $i => $t)
{
$db->bind(':MyID', $t['MyID']);
if($purpose_id)
$db->bind(':Purpose', $purpose_id);
if($associate_id)
$db->bind(':AssociateID', $associate_id);
if(!empty($args['From']))
$db->bind(':From', $args['From']);
if(!empty($args['To']))
$db->bind(':To', $args['To']);
$db->execute();
$visits = $db->fetchAllAssoc();
if( ($get_assignments_only) && (empty($visits)) )
continue;
if( ( ($purpose_id) || ($associate_id) || (!empty($args['From'])) || (!empty($args['To'])) ) && (empty($visits)) )
continue;
$tmp[$i]['HasVisits'] = (empty($visits)) ? 0 : 1;
$tmp = $schools[$i];
unset($tmp['Name']);
$schools[$i]['Address'] = build_address($tmp);
unset($schools[$i]['Add1']);
unset($schools[$i]['Add2']);
unset($schools[$i]['Add3']);
unset($schools[$i]['CityTown']);
unset($schools[$i]['CityPostCode']);
unset($schools[$i]['Name']);
unset($schools[$i]['LanguageID']);
unset($schools[$i]['PrincipalID']);
unset($schools[$i]['ContactID']);
unset($schools[$i]['TypeID']);
unset($schools[$i]['CenterID']);
unset($schools[$i]['SupportTypeID']);
unset($schools[$i]['CountyID']);
unset($schools[$i]['AreaCodeID']);
unset($schools[$i]['NetworkCodeID']);
unset($schools[$i]['RegionID']);
$returned[] = $tmp[$i];
}
return ['jct_success'=>'ok', 'response'=>$returned];
}
catch(PDOException $e)
{
return ['jct_error'=>$e->getMessage()];
}
}
Found the culprit:
I had to update my Apache max_input_vars to a higher limit to allow the number of individual parameters being returned to actually be returned. Post size was not the issue.

sqlite3 replacement for sqlite_has_more

First of thank you for your help.
The code piece "while (sqlite_has_more($dres))" is using sqlite2 and I need sqlite3. If there isn't a replacement for has_more is there another code I can use to still Find whether or not more rows are available?
F.Y.I. The server updated their stuff which included their sqlite and now I have to fix this last peice of code to get the schedule to populate and not give me this error.
Fatal error: Non-static method SQLite3::open() cannot be called statically in /home/server/public_html/current-list.php on line 57
$row_num = 0;
if ($dbh = SQLite3::open($sked_path))
{
$qsql = "SELECT rowid,* FROM sked ORDER BY sk_dow_num, sk_time_start, sk_time_end";
$dres = SQLite3::query($dbh, $qsql);
if (SQLite3::num_Rows($dres) > 0)
{
$last_dow = "";
$last_start = "0000";
$last_end = "0000";
while (sqlite_has_more($dres))
{
$ska = Sqlite3Result::fetchArray($dres, SQLITE3_ASSOC);
$rid = $ska['rowid'];
$dow = $ska['sk_dow_name'];
$start = $ska['sk_time_start'];
$end = $ska['sk_time_end'];
$title = preg_replace("/<br\s*\/*>/", " ", $ska['sk_show_title']);
$show_dow = strtoupper($dow);
$show_start = strtoupper(formatTimeAmPm($start));
$show_end = strtoupper(formatTimeAmPm($end));
$show_style = "";
if (stristr($title, "Encore Show"))
$show_style = " class=\"$text_style\"";
Something like ...
<?php
$dbh = new SQLite3;
if ( !$dbh->open($sked_path) ) {
trigger_error('...error handling...', E_USER_ERROR);
}
else {
$dres = $dbh->query('
SELECT
rowid,*
FROM
sked
ORDER BY
sk_dow_num, sk_time_start, sk_time_end
');
if ( !$dres ) {
trigger_error('...error handling...', E_USER_ERROR);
}
else {
$ska = $dres->fetchArray(SQLITE3_ASSOC);
if ( !$ska ) {
onNoRecords();
}
else {
do {
doSomethingWithRowData($ska);
}
while( false!=($ska=$dres->fetchArray(SQLITE3_ASSOC)) );
}
}
}
(completely untested)

Updating a MySQL via selected position

I am trying to update a table based on the input provided by a user. There are ten fields which a user can choose to input information into. The table I am trying to input too has a following structure.
leagueTrackID | leagueID | trackID
1 1 1
2 1 2
3 1 12
...
15 1 4
I need the code to update the fields where a new track has been added via looping though each inputted track and place it in a new field which has the matching criteria. The criteria which it needs to be match too is the leagueID. How can this be achieved without overwriting the same column row?
The code below is what I have so far but I have an error with trying to assign the php track variables to either a php array or php list.
$data = mysql_query("SELECT COUNT(leagueID) AS totalTracks , min(leagueTrackID) AS minLeagueID , max(leagueTrackID) AS maxLeagueID , leagueID , trackID
FROM leagueTracks
WHERE leagueID = '$vaildLeagueID'");
$info = mysql_fetch_array( $data );
// get posted track id and assign them to the php track varaibles
if ( $_POST['track1'] == '' ) { $track1 = $info['track1']; } else { $track1 = $_POST['track1']; }
if ( $_POST['track2'] == '' ) { $track2 = $info['track2']; } else { $track2 = $_POST['track2']; }
if ( $_POST['track3'] == '' ) { $track3 = $info['track3']; } else { $track3 = $_POST['track3']; }
if ( $_POST['track4'] == '' ) { $track4 = $info['track4']; } else { $track4 = $_POST['track4']; }
if ( $_POST['track5'] == '' ) { $track5 = $info['track5']; } else { $track5 = $_POST['track5']; }
if ( $_POST['track6'] == '' ) { $track6 = $info['track6']; } else { $track6 = $_POST['track6']; }
if ( $_POST['track7'] == '' ) { $track7 = $info['track7']; } else { $track7 = $_POST['track7']; }
if ( $_POST['track8'] == '' ) { $track8 = $info['track8']; } else { $track8 = $_POST['track8']; }
if ( $_POST['track9'] == '' ) { $track9 = $info['track9']; } else { $track9 = $_POST['track9']; }
if ( $_POST['track10'] == '' ) { $track10 = $info['track10']; } else { $track10 = $_POST['track10']; }
// Assign tracks selected to an array
$tracksArray = array($track1 , '$track2' , '$track3', '$track4', '$track5' , '$track6' ,'$track7', '$track8' , '$track9' , '$tack10');
// Counter
$trackNumber = '1';
// Get the lowest leagueTrackID based on the leagueID being updated
$min = $info['minleagueID'];
// Get the highest leagueTrackID based on the leagueID being updated
$max = $info['maxLeagueID'];
while($min != $max) {
$updateLeagueTracks = mysql_query ("UPDATE userLeague SET trackID = $trackArray['$tracknumber'] WHERE leagueID = '$vaildLeagueID'");
$addTracks = mysql_query($updateLeagueTracks);
$trackNumber++;
$min++;
} // closes the for loop

Correction function calculation in your online ratings

I need your help on this php function.
The function takes the data from the db, does the account of the score and exports it. In practice the score must be calculated for both the buyer and for the seller ($type) but when I go to export I only have one of the buyers. The code in question is below. Thanks in advance for the help.
function shop_get_ratings($user_id, $type = 'seller'){
$type = strtolower($type);
$valid = array('seller','buyer');
if( !in_array($type, $valid)){
return false;
}
$conn = getConnection();
$sql = 'SELECT AVG(i_%s_score) as %s_rating FROM %st_shop_transactions WHERE fk_i_user_id = %d AND i_%s_score IS NOT NULL';
$rs = $conn->osc_dbFetchResults(sprintf($sql,$type,$type, DB_TABLE_PREFIX, $user_id, $type));
$seller_r = 0;
if( false !== $rs && isset($rs[0]['seller_rating']) && !is_null($rs[0]['seller_rating']) ){
$seller_r = (int)$rs[0]['seller_rating'];
}
$sql = 'SELECT COUNT(*) as rating_count FROM %st_shop_transactions WHERE fk_i_user_id = %d AND i_%s_score IS NOT NULL';
$rs = $conn->osc_dbFetchResults(sprintf($sql, DB_TABLE_PREFIX, $user_id, $type));
$seller_r_c = 0;
if( false !== $rs && isset($rs[0]['rating_count']) && !is_null($rs[0]['rating_count']) ){
$seller_r_c = (int)$rs[0]['rating_count'];
}
$percentage = 0;
if( $seller_r > 0 ){
$percentage =($seller_r/5)*100;
}
$stats = array(
'average_rating' => (int)$seller_r,
'rating_percentege' => (float)$percentage,
'rating_count' => (int)$seller_r_c,
);
View::newInstance()->_exportVariableToView($type.'_ratings', $stats);
return $stats;
}
From reading the code, it looks like you should get a rating for the seller ok, but it's the buyer who ends up with a 0 rating.
This is because in the line $sql = 'SELECT AVG(i_%s_score) as %s_rating you are inserting $type in to the query to have the field named seller_type or buyer_type, depending on the type of rating you're trying to get with the function.
However when querying the result set you are explicitly looking for the field named seller_rating. This field won't be set when $type is buyer, so $seller_r will always be 0.
The simplest fix here is likely to name the field as something like avg_rating in the sql, with no $type-dependent var name injection. So, something like:
$sql = 'SELECT AVG(i_%s_score) as avg_rating
FROM %st_shop_transactions
WHERE fk_i_user_id = %d
AND i_%s_score IS NOT NULL';
$rs = $conn->osc_dbFetchResults(
sprintf($sql, $type, DB_TABLE_PREFIX, $user_id, $type)
);
$seller_r = 0;
if (false !== $rs
&& isset($rs[0]['avg_rating'])
&& !is_null($rs[0]['avg_rating'])
){
$seller_r = (int)$rs[0]['avg_rating'];
}

How can I get strpos() to distinguish between '1' and '10' in a string?

I have PHP code that changes the page title depending on a query string within a URL. However, this query string is formed by an incrementing number, and when it includes the number 10 (or 11, 12, etc.) then it uses the number 1's variables instead. Is there any way for strpos to see if/that there's a difference?
Snippet:
<?php
$fullurl = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$title = "";
$meta = "";
if (strpos($fullurl,'planes-trains-automobiles') !== false) {
if (strpos($fullurl,'mag=1') !== false) {
$title = "Title 1";
$meta = "Meta 1";
}
else if (strpos($fullurl,'mag=2') !== false) {
$title = "Title 2";
$meta = "Meta 2";
}
...
else if (strpos($fullurl,'mag=10') !== false) {
$title = "Title 10";
$meta = "Meta 10";
}
Example:
http://myurl-here.com?mag=10 gives me Title 1 not Title 10.
You could just use $_GET['mag']. To be secure, you could check if it is an integer either by
$is_valid = is_numeric($_GET['mag']) && is_int(1*$_GET['mag']);
or
$is_valid = preg_match('/^[\d]+$/',$_GET['mag']);
So you would do:
if ($is_valid):
die('wow so insecure, maybe');
else:
//do whatever you want with $_GET['mag']
Don't work by string matching a full URL, work with the parsed values! For the current request all you need to do is use $_GET['mag'].
if (isset($_GET['mag']) && ctype_digit($_GET['mag'])) {
$title = 'Title ' . $_GET['mag'];
$meta = 'Meta ' . $_GET['mag'];
}
Or possibly:
$titles = array(
1 => 'Title 1',
2 => 'Title 2',
...
);
if (isset($titles[$_GET['mag']])) {
$title = $titles[$_GET['mag']];
}
Or:
switch ($_GET['mag']) {
case 1 :
...
case 2 :
...
...
}
While not the answer as such, your problem can be simply resolved by reordering your IF/ELSE clauses so that you check for 10, 11... before you check for 1:
<?php
if (strpos($fullurl,'planes-trains-automobiles') !== false) {
if (strpos($fullurl,'mag=10') !== false) {
$title = "Title 10";
$meta = "Meta 10";
}
else if (strpos($fullurl,'mag=11') !== false) {
$title = "Title 11";
$meta = "Meta 11";
}
...
else if (strpos($fullurl,'mag=1') !== false) {
$title = "Title 1";
$meta = "Meta 1";
}
Why not extract the number with preg_match?
preg_match('/\d+/', $url, $m);
$title = "Title ".$m[0];
will match
$url= 'http://myurl-here.com?mag=10';
$url= 'http://myurl-here.com?mag=1';
etc
if (strpos($fullurl,'mag=10') !== false) {
$title = "Title 10";
$meta = "Meta 10";
}
else if (strpos($fullurl,'mag=1') !== false) {
$title = "Title 1";
$meta = "Meta 1";
}
else if (strpos($fullurl,'mag=2') !== false) {
$title = "Title 2";
$meta = "Meta 2";
}
This way the if never reaches mag=1, if mag=10 (11, 12 etc, if placed before 1) has already been selected.

Categories