Hi I have used a code snippet from a tutorial for a chat application all of its scripts are working fine but after I tweak it to make the code work based on my requirements almost all of the scripts are working except for retrieving the conversation
The error I'm having is it doesn't retrieve the conversation from my database
here is the modified script
//Create the JSON response.
$json = '{"messages": {';
//Check to ensure the user is in a chat room.
if(!isset($_GET['chat'])) {
$json .= '"message":[ {';
$json .= '"id": "0",
"user": "Admin",
"text": "You are not currently in a chat session. <a href="">Enter a chat session here</a>",
"time": "' . date('h:i') . '"
}]';
} else {
$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_POST['rid'], PDO::PARAM_STR);
$stmt6->execute();
foreach($stmt6->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$comb = $usern . $_POST['name'];
//Validation if msgid exists before creating a new table on the 2nd database
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd . "chat_conversation";
$sql7 = "SELECT msgid, message_content, username , message_time FROM $tblpre WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( ':chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
//Loop through each message and create an XML message node for each.
if(count($message_query) > 0) {
$json .= '"message":[ ';
while($message_array = $stmt7->fetch(PDO::FETCH_ASSOC)) {
$json .= '{';
$json .= '"id": "' . $message_array['msgid'] . '",
"user": "' . htmlspecialchars($message_array['username']) . '",
"text": "' . htmlspecialchars($message_array['message_content']) . '",
"time": "' . $message_array['message_time'] . '"
},';
}
$json .= ']';
} else {
//Send an empty message to avoid a Javascript error when we check for message lenght in the loop.
$json .= '"message":[]';
}
}
//Close our response
$json .= '}}';
echo $json;
Here is the code for calling this script
//Gets the current messages from the server
function getChatText() {
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
receiveReq.open("GET", 'includes/getChat.php?chat='+uid+'&last=' + lastMessage, true);
receiveReq.onreadystatechange = handleReceiveChat;
receiveReq.send(null);
}
}
function sendChatText() {
if (sendReq.readyState == 4 || sendReq.readyState == 0) {
sendReq.open("POST", 'includes/getChat.php?last=' + lastMessage, true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.onreadystatechange = handleSendChat;
var param = 'message=' + document.getElementById('txtA').value;
param += '&name='+user;
param += '&uid='+uid;
param += '&rid='+document.getElementById('trg').value;
sendReq.send(param);
document.getElementById('txtA').value = '';
}
}
//When our message has been sent, update our page.
function handleSendChat() {
//Clear out the existing timer so we don't have
//multiple timer instances running.
clearInterval(mTimer);
getChatText();
}
function handleReceiveChat() {
if (receiveReq.readyState == 4) {
//Get a reference to our chat container div for easy access
var chat_div = document.getElementById('clog');
var response = eval("(" + receiveReq.responseText + ")");
for(i=0;i < response.messages.message.length; i++) {
chat_div.innerHTML += response.messages.message[i].user;
chat_div.innerHTML += ' <font class="chat_time">' + response.messages.message[i].time + '</font><br />';
chat_div.innerHTML += response.messages.message[i].text + '<br />';
chat_div.scrollTop = chat_div.scrollHeight;
lastMessage = response.messages.message[i].id;
}
mTimer = setTimeout('getChatText();',20000); //Refresh our chat in 2 seconds
}
}
Am I missing something here or doing something wrong?
You should rewrite using json_encode:
$messages = array();
//Check to ensure the user is in a chat room.
if(!isset($_GET['chat'])) {
$message_object = (object) array(
"id"=>"0",
"user"=>"Admin",
"text"=>"You are not currently in a chat session. <a href=\"\">Enter a chat session here</a>",
"time"=>date('h:i')
);
$messages[] = (object) array("message"=>$message_object);
} else {
$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_POST['rid'], PDO::PARAM_STR);
$stmt6->execute();
foreach($stmt6->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$comb = $usern . $_POST['name'];
//Validation if msgid exists before creating a new table on the 2nd database
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd . "chat_conversation";
$sql7 = "SELECT msgid, message_content, username , message_time FROM $tblpre WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( ':chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
//Loop through each message and create an XML message node for each.
if(count($message_query) > 0) {
$message_object = (object) array(
"id"=>$message_array['msgid'],
"user"=>htmlspecialchars($message_array['username']),
"text"=>htmlspecialchars($message_array['message_content']),
"time"=>$message_array['message_time'
);
$messages[] = (object) array("message"=>$message_object);
} else {
//Send an empty message to avoid a Javascript error when we check for message lenght in the loop.
$messages[] = (object) array("message"=>array());
}
}
//Close our response
$result = (object) array('messages'=>$messages);
$json = json_encode($result);
echo $json;
Related
I using the below php chat script to create chat section between two users on my web app. I am having a problem with the Ajax posting. When a user submits a chat it doesn't post or show in the chat window. I tried to inspect the error and this is the error message
Failed to load resource: the server responded with a status of 404 (Not Found)
The same error message is shown for submit.php and refresh.php.
Here's my code:
JS
//CHAT FUNCTION
var lastTimeID = 0;
$(document).ready(function() {
$('#btnSend').click( function() {
sendChatText();
$('#chatInput').val("");
});
startChat();
});
function startChat(){
setInterval( function() { getChatText(); }, 2000);
}
function getChatText() {
$.ajax({
type: "GET",
url: "refresh.php?lastTimeID=" + lastTimeID
}).done( function( data )
{
var jsonData = JSON.parse(data);
var jsonLength = jsonData.results.length;
var html = "";
for (var i = 0; i < jsonLength; i++) {
var result = jsonData.results[i];
html += '<div style="color:#' + result.color + '">(' + result.chattime + ') <b>' + result.usrname +'</b>: ' + result.chattext + '</div>';
lastTimeID = result.id;
}
$('#view_ajax').append(html);
});
}
function sendChatText(){
var chatInput = $('#chatInput').val();
if(chatInput != ""){
$.ajax({
type: "GET",
url: "submit.php?chattext=" + encodeURIComponent( chatInput )
});
}
}
chatClass.php
<?PHP
class chatClass
{
public static function getRestChatLines($id)
{
$arr = array();
$jsonData = '{"results":[';
$statement = $db->prepare( "SELECT id, usrname, color, chattext, chattime FROM chat WHERE id > ? and chattime >= DATE_SUB(NOW(), INTERVAL 1 HOUR)");
$statement->bind_param( 'i', $id);
$statement->execute();
$statement->bind_result( $id, $usrname, $color, $chattext, $chattime);
$line = new stdClass;
while ($statement->fetch()) {
$line->id = $id;
$line->usrname = $usrname;
$line->color = $color;
$line->chattext = $chattext;
$line->chattime = date('H:i:s', strtotime($chattime));
$arr[] = json_encode($line);
}
$statement->close();
$jsonData .= implode(",", $arr);
$jsonData .= ']}';
return $jsonData;
}
public static function setChatLines( $chattext, $usrname, $color) {
$statement = $db->prepare( "INSERT INTO chat( usrname, color, chattext) VALUES(?, ?, ?)");
$statement->bind_param( 'sss', $usrname, $color, $chattext);
$statement->execute();
$statement->close();
}
}
?>
submit.php
<?php
require_once( "chatClass.php" );
$chattext = htmlspecialchars( $_GET['chattext'] );
chatClass::setChatLines( $chattext, $_SESSION['usrname'], $_SESSION['color']);
?>
refresh.php
<?php
require_once( "chatClass.php" );
$id = intval( $_GET[ 'lastTimeID' ] );
$jsonData = chatClass::getRestChatLines( $id );
print $jsonData;
?>
I have a xamp based webserver and I installed attendance system , I have 10 users registered to enter their attendance by login individually... issue is in login page accept any password and not giving error that password is wrong. Like you enter user id john#abcd.com & password gfjhgh its accept and entered to index page , the original password is 123456 but its accept every thing you type. Please tell me how to solve. It should says that you entered wrong password and can not login.
Code is below:
// Account Log In
if (isset($_POST['submit']) && $_POST['submit'] == 'signIn') {
if($_POST['emailAddy'] == '') {
$msgBox = alertBox($accEmailReq, "<i class='fa fa-times-circle'></i>", "danger");
} else if($_POST['password'] == '') {
$msgBox = alertBox($accPassReq, "<i class='fa fa-times-circle'></i>", "danger");
} else {
$usrEmail = htmlspecialchars($_POST['emailAddy']);
$check = "SELECT userId, userFirst, userLast, isActive FROM users WHERE userEmail = '".$usrEmail."'";
$res = mysqli_query($mysqli, $check) or die('-1' . mysqli_error());
$row = mysqli_fetch_assoc($res);
$count = mysqli_num_rows($res);
if ($count > 0) {
// If the account is Active - Allow the login
if ($row['isActive'] == '1') {
$userEmail = htmlspecialchars($_POST['emailAddy']);
$password = encodeIt($_POST['password']);
if($stmt = $mysqli -> prepare("
SELECT
userId,
userEmail,
userFirst,
userLast,
location,
superUser,
isAdmin
FROM
users
WHERE
userEmail = ?
AND password = ?
")) {
$stmt -> bind_param("ss",
$userEmail,
$password
);
$stmt -> execute();
$stmt -> bind_result(
$userId,
$userEmail,
$userFirst,
$userLast,
$location,
$superUser,
$isAdmin
);
$stmt -> fetch();
$stmt -> close();
if (!empty($userId)) {
if(!isset($_SESSION))session_start();
$_SESSION['tz']['userId'] = $userId;
$_SESSION['tz']['userEmail'] = $userEmail;
$_SESSION['tz']['userFirst'] = $userFirst;
$_SESSION['tz']['userLast'] = $userLast;
$_SESSION['tz']['location'] = $location;
$_SESSION['tz']['superUser'] = $superUser;
$_SESSION['tz']['isAdmin'] = $isAdmin;
// Add Recent Activity
$activityType = '1';
$tz_uid = $userId;
$activityTitle = $userFirst.' '.$userLast.' '.$accSignInAct;
updateActivity($tz_uid,$activityType,$activityTitle);
// Update the Last Login Date for User
$sqlStmt = $mysqli->prepare("UPDATE users SET lastVisited = NOW() WHERE userId = ?");
$sqlStmt->bind_param('s', $userId);
$sqlStmt->execute();
$sqlStmt->close();
header('Location: index.php');
} else {
// Add Recent Activity
$activityType = '0';
$tz_uid = '0';
$activityTitle = $accSignInErrAct;
updateActivity($tz_uid,$activityType,$activityTitle);
$msgBox = alertBox($accSignInErrMsg, "<i class='fa fa-warning'></i>", "warning");
}
}
} else {
// Add Recent Activity
$activityType = '0';
$tz_uid = $row['userId'];
$activityTitle = $row['userFirst'].' '.$row['userLast'].' '.$signInUsrErrAct;
updateActivity($tz_uid,$activityType,$activityTitle);
// If the account is not active, show a message
$msgBox = alertBox($inactAccMsg, "<i class='fa fa-warning'></i>", "warning");
}
} else {
// Add Recent Activity
$activityType = '0';
$tz_uid = '0';
$activityTitle = $noAccSignInErrAct;
updateActivity($tz_uid,$activityType,$activityTitle);
// No account found
$msgBox = alertBox($noAccSignInErrMsg, "<i class='fa fa-times-circle'></i>", "danger");
}
}
}
// Reset Account Password
if (isset($_POST['submit']) && $_POST['submit'] == 'resetPass') {
// Validation
if ($_POST['accountEmail'] == "") {
$msgBox = alertBox($accEmailReq, "<i class='fa fa-times-circle'></i>", "danger");
} else {
$usrEmail = htmlspecialchars($_POST['accountEmail']);
$query = "SELECT userEmail FROM users WHERE userEmail = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s",$usrEmail);
$stmt->execute();
$stmt->bind_result($emailUser);
$stmt->store_result();
$numrows = $stmt->num_rows();
if ($numrows == 1) {
// Generate a RANDOM Hash for a password
$randomPassword = uniqid(rand());
// Take the first 8 digits and use them as the password we intend to email the Employee
$emailPassword = substr($randomPassword, 0, 8);
// Encrypt $emailPassword for the database
$newpassword = encodeIt($emailPassword);
//update password in db
$updatesql = "UPDATE users SET password = ? WHERE userEmail = ?";
$update = $mysqli->prepare($updatesql);
$update->bind_param("ss",
$newpassword,
$usrEmail
);
$update->execute();
$qry = "SELECT userId, userFirst, userLast, isAdmin FROM users WHERE userEmail = '".$usrEmail."'";
$results = mysqli_query($mysqli, $qry) or die('-2' . mysqli_error());
$row = mysqli_fetch_assoc($results);
$theUser = $row['userId'];
$isAdmin = $row['isAdmin'];
$userName = $row['userFirst'].' '.$row['userLast'];
if ($isAdmin == '1') {
// Add Recent Activity
$activityType = '3';
$activityTitle = $userName.' '.$admPassResetAct;
updateActivity($theUser,$activityType,$activityTitle);
} else {
// Add Recent Activity
$activityType = '3';
$activityTitle = $userName.' '.$usrPassResetAct;
updateActivity($theUser,$activityType,$activityTitle);
}
$subject = $siteName.' '.$resetPassEmailSub;
$message = '<html><body>';
$message .= '<h3>'.$subject.'</h3>';
$message .= '<p>'.$resetPassEmail1.'</p>';
$message .= '<hr>';
$message .= '<p>'.$emailPassword.'</p>';
$message .= '<hr>';
$message .= '<p>'.$resetPassEmail2.'</p>';
$message .= '<p>'.$resetPassEmail3.' '.$installUrl.'sign-in.php</p>';
$message .= '<p>'.$emailTankYouTxt.'<br>'.$siteName.'</p>';
$message .= '</body></html>';
$headers = "From: ".$siteName." <".$siteEmail.">\r\n";
$headers .= "Reply-To: ".$siteEmail."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
mail($usrEmail, $subject, $message, $headers);
$msgBox = alertBox($resetPassMsg1, "<i class='fa fa-check-square'></i>", "success");
$stmt->close();
} else {
// Add Recent Activity
$activityType = '1';
$tz_uid = '0';
$activityTitle = $resetPassMsgAct;
updateActivity($tz_uid,$activityType,$activityTitle);
// No account found
$msgBox = alertBox($resetPassMsg2, "<i class='fa fa-times-circle'></i>", "danger");
}
}
}
if (isset($_POST['submit']) && $_POST['submit'] == 'signIn') {
if($_POST['emailAddy'] == '') {
$msgBox = alertBox($accEmailReq, "<i class='fa fa-times-circle'></i>", "danger");
} else if($_POST['password'] == '') {
$msgBox = alertBox($accPassReq, "<i class='fa fa-times-circle'></i>", "danger");
} else {
$usrEmail = htmlspecialchars($_POST['emailAddy']);
$password = encodeIt($_POST['password']);
$check = "SELECT userId, userFirst, userLast, isActive FROM users WHERE userEmail = '".$usrEmail."'";
$res = mysqli_query($mysqli, $check) or die('-1' . mysqli_error());
$row = mysqli_fetch_assoc($res);
$count = mysqli_num_rows($res);
if ($count > 0) {
I'm only assuming that the first time you tried to login is that the session was save and you did not destroy the session.
if ((isset($_SESSION['tz']['userId'])) && ($_SESSION['tz']['userId'] != '')) {
header('Location: index.php');
}
thus making that condition always true.
If you want to prevent/avoid the user in logging in without the valid credentials.
Matching the records in the DB
$check = "SELECT userEmail, password FROM users WHERE userEmail = '".$usrEmail."' AND password = '".$password."'";
$res = mysqli_query($mysqli, $check) or die('-1' . mysqli_error());
$row = mysqli_fetch_assoc($res);
$count = mysqli_num_rows($res);
if ($count > 0) {
//match found
}
else {
//no match found or username/password doesn't match
}
I've made a script that requests information via Json. For some variables this works just fine, for others it doesn't.
When I use alert() for the variable neighbour1 it says the variable is undefined, when doing the same for the variables number and colour it works just fine.
This is the request script:
function getcolours() {
var hr = new XMLHttpRequest();
hr.open("GET", "camp_map_script.php", true);
hr.setRequestHeader("Content-type", "application/json");
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
for (var obj in data) {
number = data[obj].number;
colour = data[obj].colour;
neighbour1 = data[obj].n1;
alert (neighbour1);
window["colour" + number] = colour;
var x = document.getElementsByClassName(number + ' ' + colour);
x[0].style.display = "block";
}
}
}
hr.send(null);
}
This is the php part:
<?php
include_once("../php_includes/check_login_status.php");
?><?php
$number = "";
$sql = "SELECT camp_id FROM users WHERE username='$log_username'";
$query = mysqli_query($connect, $sql);
$row = mysqli_fetch_row($query);
$campid = $row[0];
$sql = "SELECT players FROM campaigns WHERE id='$campid'";
$query = mysqli_query($connect, $sql);
$row = mysqli_fetch_row($query);
$players = $row[0];
$number = ($players*2)-1;
$sql = "SELECT number, colour, player, n1, n2, n3, n4, n5, n6, n7, n8 FROM lands WHERE camp_id='$campid' ORDER BY number";
$query = $connect->query($sql);
$jsonData = '{';
if ($query->num_rows > 0) {
while($row = $query->fetch_assoc()) {
$jsonData .= '"obj'.$row["number"].'":{"number":"'.$row["number"].'", "colour":"'.$row["colour"].'", "player":"'.$row["player"].'", "n1":"'.$row["n1"].'"},';
}
}
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
$connect->close();
?>
Also when I check the php document the variable n1 is echoed correctly. So the error must be on the java script side or the transit.
It is probably something stupid that I'm overlooking but I just don't see it. I've copy pasted the working parts and changed them to work with other variables but it still doesn't work. :/
I'm trying about 2 days to fix this I will blow my mind I can't anymore..When I am running it in localhost it's just working fine but when I am trying it online its just returns same values...and all values not returns the search term I can't understand why.
Jquery
$(document).ready(function($){
$('#quick-search-input2').autocomplete({
source:'All/home/directsearch.php',
minLength:2,
autoFocus: true,
select: function(event,ui){
var code = ui.item.id;
if(code != '') {
location.href = 'Movies/' + code;
}
},
html: true,
open: function(event, ui) {
$('ul.ui-autocomplete').slideDown(500)('complete');
$(".ui-autocomplete").css("z-index", 1000);
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("" + item.label + "")
.appendTo(ul);
};
});
PHP
$server = 'localhost';
$user = 'root';
$password = '';
$database = 'search';
$mysqli = new MySQLi($server,$user,$password,$database);
/* Connect to database and set charset to UTF-8 */
if($mysqli->connect_error) {
echo 'Database connection failed...' . 'Error: ' . $mysqli->connect_errno . ' ' . $mysqli->connect_error;
exit;
} else {
$mysqli->set_charset('utf8');
}
$term = stripslashes($_GET ['term']);
$term = mysql_real_escape_string($_GET ['term']);
$a_json = array();
$a_json_row = array();
include '../../connect.php';
/* ***************************************************************************** */
if ($data = $mysqli->query("SELECT * FROM search WHERE (title LIKE '%$term%' or keywords LIKE '%$term%') and serie = '' and visible = '' and complete = '' group by title, year order by clicks desc LIMIT 5")) {
while($row = mysqli_fetch_array($data)) {
$title = $row['title'];
$year = htmlentities(stripslashes($row['year']));
$type = $row['type'];
$customercode= htmlentities(stripslashes($row['link']));
$category= htmlentities(stripslashes($row['category']));
$synopsis= htmlentities(stripslashes($row['synopsis']));
$img= htmlentities(stripslashes($row['img']));
$id= htmlentities(stripslashes($row['id']));
$category = str_replace(" | ",", ", $category);
$shit = "'";
$ltitle = strtolower($title);
if ($type == "DL-HD")
{
$qualityresponse = '<img class="quality-banner img-responsive" src="Design/types/HD.png">';
}
else if ($type == "Non-HD")
{
$qualityresponse = '<img class="quality-banner img-responsive" src="Design/types/NonHD.png">';
}
else if ($type == "CAM")
{
$qualityresponse = '<img class="quality-banner img-responsive" src="Design/types/CAM.png">';
}
else
{
$qualityresponse = "";
}
$stitle = preg_replace("/[^A-Za-z0-9]/", "", $ltitle);
$a_json_row["id"] = $customercode;
$a_json_row["value"] = ''.$term.'';
$a_json_row["label"] = '
'.$qualityresponse.'<span class="titles">'.$title.'</span><p>'.$year.'</p></center>
';
array_push($a_json, $a_json_row);
}
}
$foundnum = mysql_num_rows(mysql_query("SELECT * FROM search WHERE (title LIKE '%$term%' or keywords LIKE '%$term%') and serie = '' and visible = '' and complete = '' group by title, year order by clicks desc LIMIT 5"));
if ($foundnum == 0)
{
$a_json_row["label"] = '
<li class="ac-no-results ac-item-hover ac-item-selected">No Movies found</li>
';
array_push($a_json, $a_json_row);
}
echo json_encode($a_json);
flush();
$mysqli->close();
$term = mysql_real_escape_string($_GET ['term']);
to
$term = mysqli->real_escape_string($_GET ['term']);
When I try to parse my PHP-generated XML file using the jQuery Feeds plugin, it doesn't do what it's supposed to - loop through the template below and output the XML <title> tag in the place of <!=title!>. Instead, it returns just one instance of the template with nothing in place of <!=title!>.
Nothing is returned in the Chrome JavaScript console.
Strangely, I have a similar PHP-generated XML file that works just fine.
Here's the jQuery I'm using:
$('.feed').feeds({
feeds: {
feed1: 'http://www.comfyshoulderrest.com/scrape.php?id=1' // this one doesn't work
},
//max: 3,
loadingTemplate: '<h1 class="feeds-loader">Loading items...</h1>',
entryTemplate: '<div class="item"><div class="image"><img src="images/tie.jpg" style="width: 100%;"></div>' +
'<div class="text"><ul class="list-inline">' +
'<li><span class="price text-warning"><strong>£7.00</strong></span> <span class="text-muted"><strike>£14.00</strike></span></li>' +
'<li class="text-muted"><strong>Topman</strong></li></ul>' +
'<!=title!>' +
'</div></div>'
});
Here's the code that generates the XML file:
<?php
function scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country) {
header("Content-Type: application/xml; charset=UTF-8");
$xml = new SimpleXMLElement('<rss/>');
$xml->addAttribute("version", "2.0");
$channel = $xml->addChild("channel");
$channel->addChild("product_url", $product_url);
$channel->addChild("shop_name", $shop_name);
$channel->addChild("photo_url", $photo_url);
$channel->addChild("was_price", $was_price);
$channel->addChild("now_price", $now_price);
$html = file_get_contents($list_url);
$doc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($html)) {
$doc->loadHTML($html);
libxml_clear_errors(); // remove errors for yucky html
$xpath = new DOMXPath($doc);
/* FIND LINK TO PRODUCT PAGE */
$products = array();
$row = $xpath->query($product_location);
/* Create an array containing products */
if ($row->length > 0)
{
foreach ($row as $location)
{
$product_urls[] = $product_url_root . $location->getAttribute('href');
}
}
$imgs = $xpath->query($photo_location);
/* Create an array containing the image links */
if ($imgs->length > 0)
{
foreach ($imgs as $img)
{
$photo_url[] = $photo_url_root . $img->getAttribute('src');
}
}
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
$result = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i]
);
$item = $channel->addChild("item");
$item->addChild("product_url", $result['product_url']);
$item->addChild("shop_name", $result['shop_name']);
$item->addChild("photo_url", $result['photo_url']);
}
//print_r($result);
}
else
{
echo "this is empty";
}
echo $xml->asXML();
}
/* CONNECT TO DATABASE */
$dbhost = "xxx";
$dbname = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id'];
/* GET FIELDS FROM DATABASE */
$result = mysqli_query($con, "SELECT * FROM scrape WHERE id = '$id'");
while($row = mysqli_fetch_array($result)) {
$list_url = $row['list_url'];
$shop_name = $row['shop_name'];
$photo_location = $row['photo_location'];
$photo_url_root = $row['photo_url_root'];
$product_location = $row['product_location'];
$product_url_root = $row['product_url_root'];
$was_price_location - $row['was_price_location'];
$now_price_location - $row['now_price_location'];
$gender = $row['gender'];
$country = $row['country'];
scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country);
}
mysqli_close($con);
?>