Header not working in php - javascript

I have a program that brings an image from the database and displays it inside an image div in my website. The below code was working successfully on my local wamp server but when I moved it to an online server it did not work anymore.
<?php
session_start();
include 'dbConnector.php';
$uID = $_SESSION['loggedUserID'];
$sql = "SELECT photo FROM hostmeuser WHERE userID = '$uID'";
$result = $conn->query($sql);
if(!$row = mysqli_fetch_assoc($result))
{
$imgData = "Assets/man.jpg";
}
else
{
$imgData = $row['photo'];
}
header("content-type: image/jpg");
echo $imgData;
?>
I have noticed that all (header) functions are not working on the new server and I have no control over this server so I replaced every:
header("Location: example.php")
with:
?>
<script type="text/javascript">
window.location.replace("example.php");
</script>
<?php
it is working fine now on most cases but not this one!
header("content-type: image/jpg");
Can you suggest any solution for this? or at least do you know how to represent this command in javascript?

Related

Sql Php Ajax - Check if change in database

I currently have a ajax script to run a notiload.php file which runs every 5 seconds to check if theres a change in the database, if theres a change it then outputs "1 New" for a message. However as I will be introducing a notification sound in that file. It will chime every 5 secconds when the file is loaded. Of course this will piss people off. So I need the script to check if theres a change in the database. I have a time and date stamp of every message, with the message being viewed as 2 and not as 1. So if theres a change in the database I will need it to call that file or play a sound.
here is my ajax script inside the main page
<script type="text/javascript">
$(document).ready(function(){
refreshTable<?= $FriendName->id ?>();
});
function refreshTable<?= $FriendName->id ?>(){
$('#NotiLoad<?=$FriendName->id?>').load('elements/notiload.php?id=<?=$FriendName->id?>', function(){
setTimeout(refreshTable<?= $FriendName->id ?>, 5000);
});
}
</script>
<div id="NotiLoad<?= $FriendName->id ?>" style="display: inline-block;"></div>
And here is the php of notiload.php
<?php
session_start();
// redirect to index page if not superuser
$con = mysqli_connect('localhost','root','','');
if (!$con) {
die('Could not connect to Socialnetwk DB: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
?>
<?php
$uid = $_GET['id'];
$mid = $_SESSION['user']['id'];
?>
<?php $usrload = $con->query("SELECT * FROM message WHERE sender = $uid AND recipient = $mid AND seen = '2' OR sender = $mid AND recipient = $uid AND seen = '2'"); ?>
<?php while($FriendName = $usrload->fetch_object()): ?>
<h6 style="display:inline-block;font-size: 10px;color:#37BC9B">1 New</h6>
<?php endwhile;?>

How to see errors about server sent events?

I coded a website using HTML5 Server Sent Events and it's working like charm on Godaddy shared hosting, however the same site with exactly the same code isn't working on 101domain shared hosting.
Rest all is working fine, except chat functionality using Server Sent Events.
How to find the errors in the script.
Here is the HTML page, with SSE javascript code.
<?php
$get_value_this_url = "globalchat";
?>
<div id="chat">
<div id="chats-div">
<p id="tip">(tip! kickstart a discussion by sharing this page)</p>
<ul id="chats-ul">
<?php
/*This session id will be used to fetch the latest chat via SSE*/
$_SESSION["id"] = 1;
if($stmt = $con->prepare("SELECT `icicinbbcts_id`, `icicinbbcts_user`, `icicinbbcts_chats` FROM `icicinbbcts_chats` WHERE `icicinbbcts_video_id` = ? ORDER BY `icicinbbcts_id` DESC LIMIT 25")){
$stmt->bind_param("s", $video_id);
$video_id = $get_value_this_url;
if ($stmt->execute()) {
$stmt->bind_result($id, $user, $chats);
$stmt->store_result();
if($stmt->num_rows() > 0){
$_SESSION["offset"] = $stmt->num_rows;
}
while ($stmt->fetch()) {
//print_r($user .": ". $chats."<br>");
echo '<li class="chats"><span id="nicknameChats">'.$user.'</span>: '.$chats.'</li>';
//echo '<span class="line-spacing"></span>';
$_SESSION["offset"] = $stmt->num_rows;
if($_SESSION["id"] < $id){
$_SESSION["id"] = $id;
}
}
}else
echo $stmt->error;
}else
echo $stmt->error;
$stmt->free_result();
$stmt->close();
?>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("auto_update.php?r=<?php echo $get_value_this_url; ?>");
source.onmessage = function(event) {
var obj = JSON.parse(event.data);
$("#chats-ul").append('<li class="chats"><span id="nicknameChats">'+obj.user+'</span>: '+obj.chats+'</li>');
$('#chats-ul').scrollTop($(window).height());
};
} else {
document.getElementById("chats-ul").innerHTML = "Your browser doesn't support a part of HTML5, so please use modern browsers like Chrome, Firefox, etc.";
}
</script>
</ul>
</div>
<input id="text-area" class="q" name="text-input" form="textForm" maxlength="140" placeholder="Type to comment" ></input>
</div>
And here's the server side PHP script.
<?php session_start(); ?>
<?php //error_reporting(E_ALL); ?>
<?php require "connection.php";?>
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
if($stmt = $con->prepare("SELECT `icicinbbcts_id`, `icicinbbcts_user`, `icicinbbcts_chats` FROM `icicinbbcts_chats` WHERE `icicinbbcts_video_id` = ? AND `icicinbbcts_id` > ? ORDER BY `icicinbbcts_id` DESC")){
$stmt->bind_param("si", $video_id, $row_id);
$row_id = $_SESSION["id"];
$video_id = mysqli_real_escape_string($con, strip_tags($_GET["r"]));
if ($stmt->execute()) {
$stmt->bind_result($id, $user, $chats);
$stmt->store_result();
if($stmt->num_rows > 0){
while ($row = $stmt->fetch()) {
if($_SESSION["id"] < $id){
$send = array("user" => $user, "chats" => $chats);
echo "retry: 100\n";
echo "data: ".json_encode($send)."\n\n";
ob_end_flush();
flush();
$_SESSION["id"] = $id;
}
}
}
}else
echo $stmt->error;
}else
echo $stmt->error;
$stmt->close();
?>
The same above code works perfectly on Godaddy shared hosting, however the save code just isn't working on 101domain.
I tried putting charset UTF-8 in both PHP and HTML, but that din't help, I tried adding ob_flush in server side PHP script and it din't help too.
There's nothing wrong with connection.php because same file on other pages works fine.
On chat functionality the chat messages are getting inserted into the database, however it's not showing on the page, unless we refresh the page.
How to check for errors and how to debug Server Sent Events?
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
I did console.log and didn't find the log in chrome, when I placed console.log code at the point shown below in the code.
<script>
if(typeof(EventSource) !== "undefined") {
console.log("SSE is supported"); //placing console.log here, displays the message in chrome developer tool
var source = new EventSource("auto_update.php?r=<?php echo $get_value_this_url; ?>");
source.onmessage = function(event) {
console.log("message isn't received from server"); //placing console.log here doesn't display any log message in Chrome Developer Tool
var obj = JSON.parse(event.data);
$("#chats-ul").append('<li class="chats"><span id="nicknameChats">'+obj.user+'</span>: '+obj.chats+'</li>');
$('#chats-ul').scrollTop($(window).height());
};
} else {
document.getElementById("chats-ul").innerHTML = "Your browser doesn't support a part of HTML5, so please use modern browsers like Chrome, Firefox, etc.";
}
</script>
So from the console.log above, we see that the SSE script is not receiving messages from backend, and backend code is shown above, can you show what's wrong with the backend code?
Since the result it works with one provider but not another, it is probably a server configuration issue.
Here are some things you can try to narrow down the issue:
In the javascript script use console.log(event) to check if you are getting anything from the server
Check the network tab in the developer tools area of browsers (in Chrome choose other to view server sent events).
If there is no output then try narrowing the problem down on the server. Resolev SSE output early to see if SSE mechanism works. Bit by bit resolve the SSE later and later until it breaks. If there is a difference on a specific line between providers it may be due to the PHP version. To compare php versions run <?php phpinfo() ? in a php file.
If you find a difference contact your provider!
You want to report errors?
<?php
// Turn off error reporting
error_reporting(0);
// Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Report all errors
error_reporting(E_ALL);
// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
?>

how to make the result appear in popup widow?

I want to make the result comes out in a popup window.
Code:
<?php
$con=mysqli_connect("localhost","root","1234","fyp");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT password FROM admin WHERE email = '$_POST[email]' AND Admin = '$_POST[admin]'");
while($row = mysqli_fetch_array($result))
echo "your password is : " . " $row['password']" ;
mysqli_close($con);
?>
Is it possible to make it echoed in popup window like javascript alert messages ??
I have tried this but still not working
echo "<script> alert ("<?php echo 'your password is: ' . '$row['password']'?>")</script>";
I found a maybe strange solution for this a while back.
echo "<style onload=\"jsfunc($row['password']);\"></style>";
//in your html or javascript add this function
<script type='text/javascript'>
function jsfunc(data){
alert(data);
}
</script>
the style tag is invisible and will run the function onload, so when its gets echoed. Also I use the style tag because its one of the few tags where the onload works when you echo it like this.
Its a strange solution but it works.
There are some serious flaws in your code, including it being open to SQL Injection. I'd recommend changing it to look more like this:
$con = new MySQLi("localhost","root","1234","fyp");
if($con->connect_errorno) {
echo "Failed to connect to MySQL: ".$sql->connect_error;
}
$email = $sql->real_escape_string($_POST['email']);
$admin = $sql->real_escape_string($_POST['admin']);
$query = "SELECT password FROM admin WHERE email = '$email' AND Admin = '$admin'";
$result = $sql->query($query);
if($result) {
$row = mysqli_fetch_assoc($result);
$pass = $row['password'];
echo '<script> alert("Your password is '.$pass.'");</script>';
} else {
//do some error handling
}
//the closing of a mysqli connection is not required but
mysqli_close($con);
Real escape string is not 100% proof against injection but is a good place to start with sanitising your inputs. Additionally I would strongly advise against storing your passwords in plain text. Please take a look at the PHP sha1() function or the SQL equivalent when storing the passwords initially.
Use this code
<?php
$alert='your password is: '.$row['password'];
?>
<script>
alert("<?php echo $alert; ?>");
</script>
It will work for sure.

Javascript and PHP scan for nudity

I am trying to not allow the uploading of files that have nudity to my server. I found javascript online that will scan a photo for nudity. It comes with demo pics and an html file and js files. I am using PHP to upload the file and I am having trouble not allowing if the scan find that the pic has nudity.
Here is my code sample:
$q= "insert into $table values('', '$email', '$aim', '$icq', '$yahoo', '$homepage', '0', '0', '0', '0', '0', '0', '', now(),'$myip','$email2','$password','$title','$download','$approved','$allowdelete','$author','$facebook','$piclink','$domain','$option3','$secret')";
$result = mysql_query($q) or die("Failed: $sql - ".mysql_error());
$q = "select max(id) from $table";
$result = mysql_query($q);
$resrow = mysql_fetch_row($result);
$id = $resrow[0];
$file = $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], "pics/".$id.".".$picext);
$picfile=$id.".".$picext;
echo '<script type="text/javascript" <src="nude.js">';
echo 'nude.load("pics/".<? echo $picfile; ?>);nude.scan(function(result){if(!result){ <? $nude = false; ?>;}else{ $nude = true;}})';
echo '</script>';
if ($nude === false) {
$q = "update $table set picfile = '".$id.".".$picext."' where id='$id'";
$result = mysql_query($q);
Header("Location: index.php?id=$id");
} else{
echo '<script type="text/javascript">';
echo 'alert("Nudity found. Please try again.")';
echo '</script>';
$q = "delete from $table where id='$id'";
$result = mysql_query($q);
unlink("pics/".$picfile);
Header("Location: new2.php");
}
The code uploads the file and then it's supposed to check the file for nudity and delete it and tell the user to try again if nudity is found. If nudity is not found the user is brought to the main page of the site.(This is the add new photo page). All of the PHP is working fine, but since the javascript doesn't seem to be running the file i uploaded and then since $nude isn't set it goes into the else of the if statement and again the js doesnt run(no alert box), and then the file is deleted. How can I make the javascript run to scan my uploaded pic for nudity? What am I doing wrong here?
Any help is greatly appreciated!
P.S.
For those that would like to see the js file that is doing the scanning: http://pastebin.com/MpG7HntQ
The problem is that this line:
echo 'nude.load("pics/".<? echo $picfile; ?>);nude.scan(function(result){if(!result){ <? $nude = false; ?>;}else{ $nude = true;}})';
Doesn't do what you think it does.
When you output JavaScript via echo(), that code runs on the browser or client side and doesn't run until after the PHP script has finished.
You'll either need to port the code to PHP or use an AJAX call to report the validity of the images.

Consuming web services with PHP

I am completely new to web services and I want to implement one. I did some research and I came across this site http://www.9lessons.info/2012/05/create-restful-services-api-in-php.html. The thing is given here but I have no idea on how to consume this web service as a client.
Let's say I have a client file which is supposed to display the users.
How do i do that?
Thanks.
Here is a sample JSON Web-service code snippet for u to learn....
but you should have a basic knowledge b4 to dive in...!
for example below code is in submit_user_details.php
you need to call the page for example
*localhost/appname/webservices/submit_user_details.php*
<?php
require_once('../Connections/db_connection.php');
?>
<?php
error_reporting(E_ERROR);
$json = file_get_contents('php://input');
$obj = json_decode($json);
$pin=$obj->{'pin'};
$name=$obj->{'name'};
$phone=$obj->{'phone'};
$second_number=$obj->{'second_number'};
$home_no=$obj->{'home_no'};
$email=$obj->{'email'};
//mysql_select_db($db, $db_connection)or die ('->>Error selecting database'.mysql_error());
$query = "UPDATE `haji_members` SET `name`= '".$name."',`phone`= '".$phone."',`secondary_phone`= '".$second_number."',`home_number`= '".$home_no."',`email`= '".$email."' WHERE pincode='".$pin."'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
$posts = array();
if($result != 1)
{
$post = array("message"=>"0");
$posts[] = array('post'=>$post);
}
else{
$post = array("message"=>"1");
$posts[] = array('post'=>$post);
}
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
#mysql_close($db_connection);
?>
The output would look like
{"posts":[{"post":{"tot_count":"0","username":null,"password":null}}]}

Categories

Resources