I am working on a php file that connects to my game server and executes a command. The users enter their username on a HTML form that sends them and the username to a php file that connects to the server. The port is forwarded and the server is ready to receive the info, but I keep getting this error:
Warning: socket_connect() [function.socket-connect]: unable to connect [110]: Connection timed out in /home/moocraft/public_html/test/vote.php on line 8
error: could not connect to host
Here is the HTML file:
<html>
<body>
<form action="vote.php" method="post">
Minecraft Username: <input type="text" name="fname" />
<input type="submit" />
</form>
</body>
</html>
Here is the PHP file:
<?php
$HOST = "207.210.254.141"; //the ip of the bukkit server
$password = "examplepassword1";
$player = $_POST["fname"];
//Can't touch this:
$sock = socket_create(AF_INET, SOCK_STREAM, 0)
or die("error: could not create socket\n");
$succ = socket_connect($sock, $HOST, 4445)
or die("error: could not connect to host\n");
//Authentification
socket_write($sock, $command = md5($password)."<Password>", strlen($command) + 1)
or die("error: failed to write to socket\n");
//Begin custom code here.
socket_write($sock, $command = "/Command/ExecuteConsoleCommand:give $player 264 5;", strlen($command) + 1) //Writing text/command we want to send to the server
or die("error: failed to write to socket\n");
socket_write($sock, $command = "$player voted for MOOcraft and earned 5 diamonds. Vote at moocraft.org;", strlen($command) + 1)
or die("error: failed to write to socket\n");
?>
I can't figure out why I keep getting this. Any help is greatly appreciated.
Try something simple like:
$fp = fsockopen("207.210.254.141", 4445, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)\n";
} else {
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: 207.210.254.141\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
And see what do you get, it might be due to the reason that your server is taking too long to respond
Related
I do have the following code to connect to a JAVA Websocket Server:
$service_port = 10;
$address = 'localhost';
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP );
$result = socket_connect($socket, $address, $service_port);
$xml = '<?xml version="1.0" encoding="UTF-8"?><JAVADEMO><Question="Login-Anfrage"/></JAVADEMO>';
$msg_length = strlen( $xml );
$withLength = pack( "Na{$msg_length}", $msg_length, $xml );
$lngLen = strlen( $withLength );
$send_bytes = socket_write( $socket, $withLength, $lngLen );
while ($out = socket_read($socket, 2048)) {
echo $out."<br />";
}
socket_close($socket);
This works perfect.
Now i have to connect to an SSL server. I have tried to change 'localhost' to 'ssl://localhost' or 'ssl://127.0.0.1' or 'ssl://192.168.0.1', .....
Nothings works. Anyone any idea how to connect to an SSL secured server?
EDIT:
I was missing something: On the server side, there is no Apache running! It's a Java SSL server.
the website that im hosting off of is 000webhost.com
this is in the console that is the error,
java.net.MalformedURLException: no protocol: OxidePKz.net63.net/checkvote.php? username=oxide
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
and this is my check vote page code
<?php
$con = mysql_connect("mysql1.000webhost.com", "a5999082_oxidepk", "(put in right passcode)");
if (!$con) {
die("Could not connect to database: " . mysql_error());
}
mysql_select_db("DATABASE_NAME", $con);
$username = mysql_escape_string($_GET['username']);
if (isset($_GET['username'])) {
$result = mysql_query("SELECT * FROM `votes` where username = '$username'") or die(mysql_error());
$row = mysql_fetch_array($result);
if($row['username'] == $username) {
mysql_query("DELETE FROM `votes` where username = '$username'");
echo "true";
} else {
echo "false";
}
}
i made a my admin php thing with the table name votes
and this is the call back page
$rspscoding = gethostbyname("http://www.oxidepkz.net63.net");
if($_SERVER['REMOTE_ADDR'] == $rspscoding) {
$con = mysql_connect("mysql1.000webhost.com", "a5999082_oxidepk", "(put in right passcode)");
if (!$con) {
die("Could not connect to database: " . mysql_error());
}
mysql_select_db("DATABASE_NAME", $con);
$username = mysql_escape_string($_GET['username']);
if (isset($_GET['username'])) {
mysql_query("INSERT INTO `votes` (username) VALUES ('$username')") or die(mysql_error());
}
mysql_close($con);
}
A few things;
I'm wonderinhg why you are getting back a java exception from a php application
Next gethostbyname("http://www.oxidepkz.net63.vote.html") does NOT take a URL, it takes a hostname like "www.oxidepkz.net63.com" for example according to: http://php.net/manual/en/function.gethostbyname.php
Finally, your URL is malformed since there is no ending slash after the domain name.
"http://www.oxidepkz.net63.vote.html" will not work in any browser
Did it get truncated, perhaps?
I am trying to send a POST request to a php file located on a web server. Currently I am successfully sending the request but the headers are not being sent correctly.
Below is my query string I would like to send:
lastName=Jones&title=Android+Game+Programming+2&price=22.99&isbn=9876543210123&year=2012&firstName=Joe&publisher=Android+Press
and this is how I attempt to send them to the server:
if(method.equalsIgnoreCase("POST")){
//Write the http post request to web server
s.getOutputStream().write(("POST " + path + " HTTP/1.0\r\n").getBytes("ASCII"));
s.getOutputStream().write("Host: www.jdiadt.com\r\n\r\n".getBytes("ASCII"));
//Request Headers
String title = "title: "+request.getParameters().get("title") + "\r\n";
String firstName = "firstName: "+request.getParameters().get("firstName") + "\r\n";
String lastName = "lastName: " + request.getParameters().get("lastName") + "\r\n";
String isbn = "isbn: " + request.getParameters().get("isbn") + "\r\n";
String publisher = "publisher: " + request.getParameters().get("publisher") + "\r\n";
String year = "year: " + request.getParameters().get("year") + "\r\n";
String price = "price: " + request.getParameters().get("price") + "\r\n";
s.getOutputStream().write(title.getBytes("ASCII"));
s.getOutputStream().write(firstName.getBytes("ASCII"));
s.getOutputStream().write(lastName.getBytes("ASCII"));
s.getOutputStream().write(isbn.getBytes("ASCII"));
s.getOutputStream().write(publisher.getBytes("ASCII"));
s.getOutputStream().write(year.getBytes("ASCII"));
s.getOutputStream().write(price.getBytes("ASCII"));
//Blank line
String blankline = "\r\n";
s.getOutputStream().write(blankline.getBytes("ASCII"));
//Flush and wait for response...
s.getOutputStream().flush();
When I run the code I get this notice from the script which leads me to believe I am not sending the headers correctly:
Notice: Undefined index: title in C:\wamp\www\bookstore\createBook.php on line 3
It gives above error for every single line where I try to retrieve the variables sent via POST. Here is code:
$title = $_POST['title'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$publisher = $_POST['publisher'];
$isbn = $_POST['isbn'];
$year = $_POST['year'];
$price = $_POST['price'];
Any information as to what might be wrong?
createBook.php
<?php
$title = $_POST['title'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$publisher = $_POST['publisher'];
$isbn = $_POST['isbn'];
$year = $_POST['year'];
$price = $_POST['price'];
try {
require_once 'BookDAO.php';
require_once 'Book.php';
$dao = new BookDAO();
$book = new Book(NULL, $title, $firstName, $lastName,
$publisher, $isbn, $year, $price);
$dao->insert($book);
$books = $dao->findAll();
if (count($books) > 0) {
echo '<table>';
echo '<tr>';
echo ' <th>Title</th>
<th>First name</th>
<th>Last name</th>
<th>Year</th>
<th>Price</th>
<th>Actions</th>';
echo '</tr>';
foreach ($books as $book) {
echo '<tr>';
echo '<td>' . $book->getTitle() . '</td>';
echo '<td>' . $book->getFirstName() . '</td>';
echo '<td>' . $book->getLastName() . '</td>';
echo '<td>' . $book->getYear() . '</td>';
echo '<td>' . $book->getPrice() . '</td>';
echo '<td>';
echo '<a href="editBookForm.php?id=' . $book->getId() . '">';
echo '<img src="images/edit20.png" alt="Edit Book" />';
echo '</a>';
echo '<a href="deleteBook.php?id=' . $book->getId() . '"';
echo ' onclick="return confirm(\'Are you sure you want to delete';
echo ' this book?\');">';
echo '<img src="images/delete20.png" alt="Delete Book" />';
echo '</a>';
echo '</td>';
echo '</tr>';
}
echo '</table>';
}
else {
echo "<p>There are no books in the database.</p>";
}
echo '<p>';
echo '<a href="createBookForm.php">';
echo '<img src="images/new20.png" alt="New Book" /> New Book';
echo '</a>';
echo '</p>';
}
catch (PDOException $e) {
exit("Connection failed: " . $e->getMessage());
}
?>
Why not use a library like HttpClient? It's got a really nice API for performing HTTP GET, POST and other methods. It will allow you to write code that's less fragile and more understandable.
Link: http://hc.apache.org/httpclient-3.x/
You are setting your parameters in a GET-type (querystring) of way and are trying to get them using POST. You should change either of those so that they are the same.
I fixed the problem myself. For anyone wondering what I did here is my solution.
As you can see in the above code I included with my original question I was trying to send the headers one after the other which is the complete wrong thing to do!
I checked out the following two links (the second one particularly) and found them very helpful in explaining the POST request structure.
http://net.tutsplus.com/tutorials/other/http-headers-for-dummies/
http://ruturajv.wordpress.com/2005/12/25/http-post-request/
I then went back to my code and made the following changes to how I constructed my post request:
//POST REQUEST
if(method.equalsIgnoreCase("POST")){
//CONSTRUCT REQUEST
String blankline = "\r\n";
String query = request.getQueryString();
String length = String.valueOf(query.length());
System.out.println(length);
//Write the http post request to web server
s.getOutputStream().write(("POST " + path + " HTTP/1.0" +"\r\n").getBytes("ASCII"));
s.getOutputStream().write(("Host: localhost.com" + "\r\n").getBytes("ASCII"));
s.getOutputStream().write(("Content-Type: application/x-www-form-urlencoded"+"\r\n").getBytes("ASCII"));
s.getOutputStream().write(("Content-Length: " + length + "\r\n").getBytes("ASCII"));
s.getOutputStream().write(blankline.getBytes("ASCII"));
s.getOutputStream().write(query.getBytes("ASCII"));
//Flush and wait for response...
s.getOutputStream().flush();
I then simply read the response back from the server.
In my app, I want to convert PDF file to images, but it looks like there is not a module in node.js. So i want to use the java application do the work.
Can we call java command in the cloud foundry node app?
Thanks.
Hong
OK, so I have built an express app that does the job;
app.js looks like this;
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, util = require('util')
, fs = require('fs')
, exec = require('child_process').execFile
, http = require('http');
process.env.MAGICK_TMPDIR = __dirname + '/tmp'
var app = express();
app.configure(function(){
app.set('port', process.env.VCAP_APP_PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser({uploadDir:__dirname + "/uploads"}));
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.post('/convert', function(req, res) {
var pdf_file = req.files.pdf.path;
var uploadsPath = __dirname + "/uploads"
var filename = pdf_file.split("/")[pdf_file.split('/').length - 1]
var out = __dirname + '/public/images/' + filename + '.png';
exec('convert', [pdf_file, '-append', out], function(err, stdout, stderr) {
res.redirect('/images/' + filename + '.png');
});
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
The index view looks like this (just a simple multipart form);
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<form action="/convert" method="post" enctype="multipart/form-data">
<label>PDF File</label>
<input type="file" name="pdf" />
<input type="submit" />
</form>
</body>
</html>
This all works fine on my private instance of Cloud Foundry (VCAP) but not on CloudFoundry.com, I think this is due to permissions issues. I will chase this up with the engineering team and find out if it is possible to call ImageMagick with the correct permissions.
=========
UPDATE
I have fixed the problem for CloudFoundry.com, it appears to stop ImageMagick from using /tmp as a temp dir the env var MAGICK_TMPDIR has to be set, you can see this in the top of app.js file now.
Am also redirecting to the image now rather then reading it in, works like a charm! - http://pdf2png.cloudfoundry.com
====
I have an email being generated and sent in one file, a link in that email links to my confirmation page which then should move the users name around database tables according to choices they have made. Problem is i am getting nothing from the confirmation page at all, even when i use just a simple print statement and nothing else. I have been trying to figure it out but to no avail and error reporting is returning blank as well. here at the two files:
email.php (which fully works)
<?php
$link= mysql_connect(...............); //Establish connection to the MySQL server
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db(.....);
$confirm = md5(uniqid(rand()));
$position = $_POST['position'];
$team_name = $_POST['team_name'];
$zip_code = $_POST['zip_code'];
$userId = $_POST['userId'];
$s=mysql_query("SELECT Coach, TeamId FROM TEAM WHERE TEAM.Name = '$team_name' AND TEAM.Zip ='$zip_code'") OR die ("Error 1"); //Get result from query
while($row=mysql_fetch_assoc($s))
{
$coachId = $row['Coach'];
$teamId = $row['TeamId'];
}
$l=mysql_query("SELECT Name, Email FROM USER WHERE USER.UserId = '$userId'") OR die ("Error 3"); //Get result from query
while($row = mysql_fetch_assoc($l))
{
$user_name = $row['Name'];
$user_email = $row['Email'];
}
$q=mysql_query("SELECT Name, Email FROM USER WHERE USER.UserId = '$coachId'") OR die ("Error 4"); //Get result from query
while($coach=mysql_fetch_assoc($q))
{
$to = $coach['Email'];
$name = $user_name;
$subject = "Scoutlet $position Request for The $team_name";
if($position == "Head Coach")
{
$message = "$name has requested to become the Head Coach for the $team_name.";
$message .= "\n\nClick on the following link to give $name permission to be the Head Coach of the $team_name (Located in the ZIP code $zip_code).\n\n";
$message .="Click Here to make $name the Head Coach";
}
else
{
$message = "$name has requested to become a Score Keeper for the $team_name.";
$message .= "\n\nClick on the following link to give $name permission to be a Score Keeper for the $team_name (Located in the ZIP code $zip_code).\n\n";
$message.="http://web.***.***/~***/confirmation.php?key=$confirm"; // way to prevent no spam, dont use txt
}
$headers = "From: ***";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$sent = mail($to, $subject, $message, $headers) ;
if($sent)
{
print "sent";
}
else
{
print "fail";
}
}
$sql=mysql_query("INSERT INTO CONFIRMATION(ConfirmationNumber, UserId, Email, TeamId, TeamName, Position)VALUES('$confirm', '$userId','$user_email','$teamId', '$team_name', '$position')") OR die ("Error 2"); //Get result from query
mysql_close();
?>
confirmation.php
<?
ini_set('display_errors',1);
error_reporting(E_ALL);
$confirm = $_GET['key'];
$link= mysql_connect(***********); //Establish connection to the MySQL server
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
echo "connect4e";
mysql_select_db(**********);
$sql1=mysql_query("SELECT * FROM CONFIRMATION WHERE ConfirmationNumber ='$confirm'") OR die ("Fail 1");
while($row=mysql_fetch_assoc($sql1))
{
$userId= $row['UserId'];
$user_email = $row['Email'];
$teamId = $row['TeamId'];
$team_name = $row['TeamName'];
$position= $row['Position'];
}
$sql2= mysql_query("INSERT INTO USER (Role) VALUES ('$position') WHERE UserId ='$userId'") OR die ("Fail 2");
if($position =="Head Coach")
{
$sql3= mysql_query("INSERT INTO TEAM (Coach) VALUES ('$userId') WHERE TeamId ='$teamId'") OR die ("Fail 3a");
}
else
{ // do a check earlier on to see if the user is already a score keeper for that team
$sql3= mysql_query("INSERT INTO SCOREKEEPS_FOR (ScoreKeeper, Team) VALUES ('$userId', '$teamId')") OR die ("Fail 3b");
}
$to= $user_email;
$subject="Welcome to Our Site";
$headers = "From: ******";
$message="Congratulations, you have been confirmed as a $position for The $team_name.";
$sent = mail($to,$subject,$message,$header);
if(sent)
{
$sql4=mysql_query("DELETE FROM CONFIRMATION WHERE ConfirmationNumber = '$confirm'") OR die ("Fail 5");
}
else
{
print "fail";
}
?>
I've already killed a ton of time just trying to error check which was a waste so hopefully more eyes will help solve it faster. any help or suggestions would be great. thanks in advance
if(sent) >>should be>> if($sent)
Could be your server only executes php with starting tag
<?php
instead of
<?
http://us2.php.net/manual/en/language.basic-syntax.phptags.php
PHP also allows for short tags (which are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option.
in your confirmation.php you're using short open tags <? ... ?>. Make sure your php short open tags is enable or simply use <?php ... ?> instead.