I am trying to make a web ftp explorer like Monsta FTP. Currently I'm trying to make a function that will switch the current directory to the directory I click on.
This is how it currently looks like:
The PHP (index.php):
<?php
if(isset($_POST['file_name'])) {
$file_name = $_POST['file_name'];
ftp_chdir($ftp_conn, $file_name);
echo "<p>".ftp_pwd($ftp_conn)."<p>";
}
// connect to the FTP server
$ftp_server = "xxxxxxxxx";
$ftp_username = "xxxxxxxxx";
$ftp_userpass = "xxxxxxxxx";
$ftp_conn = ftp_connect($ftp_server, 21) or die("Could not connect to $ftp_server");
if ($ftp_conn === false) {
echo "Unable connect to the ftp server.<br>";
} else {
echo "Succesfully connected to the ftp server.<br>";
}
//login to the FTP server
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);
if ($login === true) {
echo "Succesfully logged in to the ftp server.";
} else {
echo "Unable to log in to the ftp server.";
}
//get a list of all files and folders
$contents = ftp_nlist($ftp_conn, '/');
echo "<ul>";
for ($i = 0 ; $i < count($contents) ; $i++) {
echo "<li>".$contents[$i]."</li>";
}
echo "</ul>";
// close connection
ftp_close($ftp_conn);
?>
<!DOCTYPE html>
<html>
<head>
<title>FTP file menager</title>
</head>
<body>
<script src="js/jquery.js"></script>
<script src="js/functions.js"></script>
</body>
</html>
The JS (functions.js):
function post(vally) {
var name = vally;
$.post('index.php', {file_name:name}, function(data) {});
console.log('posted');
}
When I click on one of the links with the folder name, I get "posted" in the console meaning that JQuery (I'm using JQuery 3.2.1 downloaded from jquery.com) posted the data but I don't get any alerts or echos from PHP. I tried putting the if () before and after the connection to the ftp server has been established, but I still get nothing.
Does anyone have an idea on why my code doesn't work?
Try removing ftp_close($ftp_conn); because it closes the ftp connection before the js gets loded and therefore php can no longer execute ftp commands, unless you open the ftp connection in the isset().
Related
I have a simple AJAX function bound to a button that should execute a PostgreSQL query. However, when I click the button that I bound the ajax query to, all I get is the confirmation that the database connection was successful. Nothing seems to happen withe the ajax result (should be printing to console in the handleAjax() function. What am I doing wrong?
This is the javascript code (with jquery):
$(document).ready(function() {
function sendAjax() {
$.ajax({
url: "db/database.php",
success: function (result) {
handleAjax(result);
}
});
}
function handleAjax(result) {
console.log(result);
}
$("#submit-button").on("click", sendAjax);
});
And this it the contents of database.php:
<?php
function dbconn(){
ini_set('display_errors', 1); // Displays errors
//database login info
$host = 'localhost';
$port = 5432;
$dbname = 'sms';
$user = 'postgres';
$password = 'postgres';
// establish connection
$conn = pg_connect("host=$host port=$port dbname=$dbname user=$user password=$password");
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
}
}
$conn = dbconn();
$sql = "SELECT * FROM numbers;";
$result = pg_query( $sql ) or die('Query Failed: ' .pg_last_error());
$count = 0;
$text = 'error';
while( $row = pg_fetch_array( $result, null, PGSQL_ASSOC ) ) {
$text = $row['message'];
//echo $text;
}
pg_free_result( $result );
?>
The problem is in the database.php file, all you get is "Connected." because you don't print your result at the end. Ajax only receive the output of the php file.
So at the end of your php file you should add :
echo $text;
And you also should remove the echo "Connected.";
AJAX is not a magic wand that in magic way reads PHP code. Let's say AJAX is a user. So what does user do.
Open web page
Wait until PHP execute code and display data
Tells you what he sees
If you don't display anything, ajax can't tell you what he saw.
In thi's place is worth to say that the best way to communicate between PHP and AJAX is using JSON format.
Your code generally is good. All you have to do is to display your data. All your data is in your $text var. So let's convert your array ($text) to JSON.
header('Content-Type: application/json');
echo json_encode($text);
First you set content-type to json, so ajax knows that he reads json. Then you encode (convert) your PHP array to js-friendly format (JSON). Also delete unnecessary echoes like 'Conntected' because as I said, AJAX reads everything what he sees.
You should return $conn from dbconn()
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
return $conn;
}
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?
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);
?>
i trying get friends list from facebook using graph api and Graph secret. first i have tired Localhost its Working well.i got taotal friends of facebook. i have used Graph api and secret key.
My code Looks like
facebook.php
<?php
require '/src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'XXXXXXXXXXXXXXXXX',
'secret' => 'XXXXXXXXXXXXXXXXX',
));
$app_id = 'xxxxxxxxxxxxxxxxxx';
$app_secret = 'xxxxxxxxxxxxxxxx';
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
$result = $facebook->api('/me/friends');
print "<pre>";
//print_r($result);
$json_output=($result['summary']['total_count']);
// echo "<h1>".'<p>Following</p>'. $json_output. "</h1>";
echo '<p>Friends</p>'. "<h1>".$json_output. "</h1>";
//echo '<div class="col-md-6 two">."<span>".$json_output."</span>""<p>FRIENDS COUNTR</p></div>';
print "</pre>";
} else {
$statusUrl = $facebook->getLoginUrl();
$loginUrl = $facebook->getLoginUrl(array('scope' => 'user_friends'));
}
?>
this code i called my index html code
my top of the page i have write Looks like
<?php
session_start();
?>
i have include facebook.php in my html page assign particular place its Looks like
<div class="col-md-6 two">
<!--
<span>36</span>
<p>Following</p>--->
<?php include("facebook.php"); ?>
</div>
this code working localhost xampp. When i move this code server side its showing that particular place blank page ?
There is probably some error on your page when running it on the server but you probably have error reporting turned off on the server. If you can turn on PHP error reporting on your server you'll probably be able to track down the problem pretty quickly.
A quick guess would be that you haven't uploaded the required file 'src/facebook.php'
How do I search a folder on my server and display the results on my webpage? I found a similar question at How can I create a search form that searches files in a folder? but I can't figure out how to connect the php script to my html:
<!DOCTYPE html>
<html>
<body>
<div>
<input id="query" type="text"/><button id="search-button" onclick="?????">Search</button>
</div>
<script>
var q=document.getElementById("query");
</script>
<?php
$dir = "/uploads/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if($file == $_POST['q']){
echo(''. $file .''."\n");
}
}
closedir($dh);
}
}
?>
</body>
</html>
You can post info to a php script seamlessly (asynchronously) with jQuery's post method. Then you can return the data to the calling page and display it.
So have the php script that lists/finds the files and the html page separate. Then in the html page use javascript and jQuery to post to that php finder script. Something like:
$.post('phpFileFinder.php', {fileName: fileNameJSvar}, function(data){
$("#divId").html(data);
});
Then in your php script you can have:
$dir = $_POST['fileName'];
$fileArray = array();
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if($file == $_POST['q']){
array_push($fileArray,''. $file .''."\n");
}
}
closedir($dh);
}
print_r($fileArray);
}