So, basically I'm trying to get some values from an Arduino board to be saved to my SQL database stored on my PC.
I've looked at multiple resources online, and spent about 5-6 hours trying to crack this, but now i'm here asking for your help.
So, Heres what seems to be working.
Im able to send values to the database Directly by typing in :
[http://localhost/myapp/write_data.php?value1=2&value2=10]
to google chrome. This gives me the expected output from the PHP script and updates into the database. However, when I run it on the Arduino it goes through the code as if its working, but it isnt sending any data to the SQL Server.
Below is the Arduino Code.
#include <SPI.h>
#include <Ethernet.h>
int rand1 = 0;
int rand2 = 0;
//EthServer(80);
//IPAddress server(10,0,0,1);
char server[] =("10.0.0.1");
EthernetClient client;
byte mac[] = {
0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x0
};
byte ip[] = { 10, 0, 0, 2 };
void setup(void)
{
// start serial port
Serial.begin(9600);
Ethernet.begin(mac, ip);
}
void printIPAddress()
{
Serial.print("My IP address: ");
for (byte thisByte = 0; thisByte < 4; thisByte++) {
// print the value of each byte of the IP address:
Serial.print(Ethernet.localIP()[thisByte], DEC);
Serial.print(".");
}
Serial.println();
}
void loop() {
delay(1000);
rand1 = random(1, 3);
rand2 = random(25);
Serial.println(rand1);
Serial.println(rand2);
// Connect to the server (your computer or web page)
if (client.connect(("http://10.0.0.1"), 80)) {
client.print("GET /myapp/write_data.php?"); // This
client.print("value1="); // This
client.print(rand1); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
client.print(";");
client.print("value2=");
client.print(rand2);
client.println(" HTTP/1.1"); // Part of the GET request
client.println("Host: 10.0.0.1"); // IMPORTANT: If you are using XAMPP you will have to find out the IP address of your computer and put it here (it is explained in previous article). If you have a web page, enter its address (ie.Host: "www.yourwebpage.com")
client.println("Connection: close"); // Part of the GET request telling the server that we are over transmitting the message
client.println(); // Empty line
client.println(); // Empty line
client.stop(); // Closing connection to server
}
else {
// If Arduino can't connect to the server (your computer or web page)
Serial.println("--> connection failed\n");
printIPAddress();
}
delay(10000);
}
Then here I have the PHP Script
//connect
$link=new mysqli("localhost", "root", "", "myappdb");
//check connection
if ($link==false) {
die("Connection failed: " . mysqli_connect_error());
}
//insert values
$sql = "INSERT INTO resistence (phase, max_reading)
VALUES (". $_GET['value1'] .",". $_GET['value2'].")";
//// Check if values have been inserted, confirm with user that values are correct.
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
echo "Values inserted are Phase " . $_GET['value1']. " and Max_Reading ". $_GET['value2']. ".";
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
/////
//close connection
mysqli_close($link);
?>
Any help at all would be awesome.
Cheers
John
If you don't get reponse "connection failed" then it should be connected. Try
client.print("&");
instead
client.print(";");
If that still doesn't work, in the PHP file, use
error_log("text");
and check the server error.log to figure out if PHP script is even started, and check if $_GET variable is set at all.
EDIT: addition:
You shouldn't use client.connect in if statement.
client.connect returns an int (1,-1,-2,-3,-4) indicating connection status
SUCCESS 1
TIMED_OUT -1
INVALID_SERVER -2
TRUNCATED -3
INVALID_RESPONSE -4
So print out the return and then continue with debugging. Must be problem with the IP address you provided.
Related
Kindly help me in my code. I have arduino code that is sending and getting data from mySql. It is running well and storing data to the database. The problem is that, if I switch ON the button the value 1 is stored in the database, but when I switch OFF the button the value 0 is not stored in the database.
Here is my arduino code:
//Arduino Code
#include <SoftwareSerial.h>
SoftwareSerial s(5,6);//Rx,Tx
int buttonPinBulb = 11;
int relay1 = 10;
int buttonBulb;
int currentStatus = LOW;
unsigned long lastMillis = 0;
const unsigned long debounceTime = 100;
void setup() {
// put your setup code here, to run once:
pinMode(buttonPinBulb, INPUT_PULLUP);
pinMode(relay1, OUTPUT);
s.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
buttonBulb = digitalRead(buttonPinBulb);
bulbOnOff(buttonBulb);
}
int bulbOnOff(int buttonBulb) {
unsigned long currentMillis = millis();
// protect against overflow
if ( (currentMillis - lastMillis > debounceTime) || (currentMillis < lastMillis)) {
if (buttonBulb != currentStatus) {
digitalWrite(relay1, buttonBulb);
//Serial.println(!buttonBulb);
currentStatus = buttonBulb;
// update database here
if(s.available()>0)
{
s.write(!buttonBulb);
}
lastMillis = currentMillis;
}
}
return 0;
}
The following is nodeMCU ESP8266 code
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <SoftwareSerial.h>
SoftwareSerial s(D6, D5); //RX,TX
int buttonBulb;
int Led_OnBoard = 2;
const char* ssid = "iPhone"; // Your wifi Name
const char* password = "Qaser.shah.123"; // Your wifi Password
const char *host = "172.20.10.6"; //Your pc or server (database) IP, example : 192.168.0.0 , if you are a windows os user, open cmd, then type ipconfig then look at IPv4 Address.
void setup() {
// put your setup code here, to run once:
wifiConnection();
s.begin(115200);
}
int wifiConnection() {
pinMode(Led_OnBoard, OUTPUT); // Initialize the Led_OnBoard pin as an output
Serial.begin(115200);
WiFi.mode(WIFI_OFF); //Prevents reconnection issue (taking too long to connect)
delay(1000);
WiFi.mode(WIFI_STA); //This line hides the viewing of ESP as wifi hotspot
WiFi.begin(ssid, password); //Connect to your WiFi router
Serial.println("");
Serial.print("Connecting");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
digitalWrite(Led_OnBoard, LOW);
delay(250);
Serial.print(".");
digitalWrite(Led_OnBoard, HIGH);
delay(250);
}
digitalWrite(Led_OnBoard, HIGH);
//If connection successful show IP address in serial monitor
Serial.println("");
Serial.println("Connected to Network/SSID");
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
s.write("s");
if (s.available() > 0)
{
buttonBulb = s.read();
Serial.println(buttonBulb);
int result = updateDatabase(buttonBulb);
if(result != 0){
//error updating database
Serial.print("error updating database");
}
}
}
int updateDatabase(int buttonBulb){
HTTPClient http; //Declare object of class HTTPClient
//String ButtonState;
String buttonValueSend, postData;
buttonValueSend = String(buttonBulb); //String to interger conversion
//Post Data
postData = "buttonBulb=" + buttonValueSend;
http.begin("http://172.20.10.6/Nodemcu_db_record_view/InsertDB.php"); //Specify request destination
http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header
int httpCode = http.POST(postData); //Send the request
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
Serial.println("Button Value send=" + buttonValueSend);
http.end(); //Close connection
return 0;
}
The following is my php code which stores the Arduino data
<?php
//Creates new record as per request
//Connect to database
$servername = "localhost"; //example = localhost or 192.168.0.0
$username = "root"; //example = root
$password = "";
$dbname = "automation";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Database Connection failed: " . $conn->connect_error);
}
//Get current date and time
date_default_timezone_set('Asia/Karachi');
$d = date("Y-m-d");
$t = date("H:i:s");
if(!empty($_POST['buttonBulb']))
{
$buttonBulb = $_POST['buttonBulb'];
$sql = "INSERT INTO project (ButtonState, Date, Time) VALUES ('".$buttonBulb."', '".$d."', '".$t."')"; //nodemcu_ldr_table = Youre_table_name
if ($conn->query($sql) === TRUE) {
echo "OK";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
See the image of output
In this image OK is printing at Value 1 but not printing OK at value 0
I think there is something wrong or I forgot something, that is why it is not happening.
Thanks a lot for any appericiation.
You can create a separate function to update the database and only call the update when the button state is changed.
Combined with my answer on your previous question it would look like this:
void loop() {
unsigned long currentMillis = millis();
if ( (currentMillis - lastMillis > debounceTime)
|| (currentMillis < lastMillis)) { // protect against overflow
int buttonBulb = digitalRead(buttonPinBulb);
if (buttonBulb != currentStatus) {
digitalWrite(relay1, buttonBulb);
Serial.println(buttonBulb);
currentStatus = buttonBulb;
// update database
int result = updateDatabase(buttonBulb);
if (result != 0) {
// error updating database
}
}
lastMillis = currentMillis;
}
}
int updateDatabase(int buttonvalue) {
HTTPClient http; //Declare object of class HTTPClient
String buttonValueSend, postData;
buttonValueSend = String(buttonvalue); //String to integer conversion
// ...
http.end(); //Close connection
return 0; // for example return 0 on success, -1 on error
}
I have found the problem. The problem was in my php code that is why the 1 will stored in the database but 0 would not.
Here is what I have change in php code
I just removed if(!empty(&_POST['buttonBulb'])){}
The code that was used in if statement now it is outside from if statement.
Reason
The behind that, when I send 1 to this code it is OK but if send 0 the is statement assumes there is no value and buttonBulb variable is empty.
Thankyou all of you who help me in this code. Now I am going to next step of this project and if I have some problems I will ask.
Specially thanks to #Danny_ds
I am working on a very important project using Arduino Uno and SIM900 GSM Module. Basically I correctly read the ID from an RFID Card(RFID-RC522) and I need to send the ID using an URL to the Host Provider's Database(000webhost) and I need to get the OUTPUT of my query but as you will see a simple change in the code and the output is completely changed.
Here is the code for the PHP file that needs to send the OUTPUT:
<?php
$dbhost = "localhost";
$dbuser = "*******";
$dbpass = "*******";
$db = "********";
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
mysqli_select_db($conn,$db);
date_default_timezone_set('Europe/Rome');
$date = date("Y-m-d G:i:s");
$code=$_REQUEST['code'];
$sql_u = "SELECT * FROM users WHERE code='$code'";
$res_u = mysqli_query($conn, $sql_u);
if (mysqli_num_rows($res_u) > 0)
{
echo "ALREADY EXISTENT $code";
}
else
{
$sql = "INSERT INTO users(code,used) VALUES ('$code','$date')";
if (mysqli_query($conn, $sql)) {
echo "SUCCESS $code";
} else {
echo "ERROR INSERTING $code";
}
}
mysqli_close($conn);
?>
Anyways, here is the Arduino Code:
#include <SoftwareSerial.h>
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9
#define SS_PIN 10
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
SoftwareSerial myGsm(7, 8);
String UID = "";
String pUID;
void setup() {
Serial.setTimeout(100);
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522
myGsm.begin(19200);
Serial.begin(9600);
myGsm.println("AT+CGATT=1");
printSerialData();
myGsm.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
printSerialData();
myGsm.println("AT+SAPBR=3,1,\"APN\",\"internet.wind\"");
printSerialData();
myGsm.println("AT+SAPBR=2,1");
printSerialData();
myGsm.println("AT+SAPBR=1,1");
printSerialData();
myGsm.println("AT+HTTPINIT");
printSerialData();
}
void loop() {
if (!mfrc522.PICC_IsNewCardPresent()) {
return;
}
if (!mfrc522.PICC_ReadCardSerial()) {
return;
}
pUID = UID;
UID = mfrc522.PICC_DumpDetailsToSerialUid(&(mfrc522.uid));
if (UID != pUID) {
Serial.print("RFID Code: ");
Serial.print(UID);
Serial.print("\n");
String url = "http://mywebsite.000webhostapp.com/test.php?code=", code = "";
url += UID;
code = "";
String httpara = "";
httpara += "AT+HTTPPARA=\"URL\",";
httpara += url;
url = "http://mywebsite.000webhostapp.com/test.php?code=";
myGsm.println(httpara); // setting the httppara,
printSerialData();
myGsm.println("AT+HTTPPARA=\"CID\",1");
printSerialData();
myGsm.println("AT+HTTPACTION=0"); //submit the GET request
//delay(8000);//the delay is important if the return datas are very large, the time required longer.
printSerialData();
myGsm.println("AT+HTTPREAD=0,20"); // read the data from the website you access
//delay(3000);
printSerialData();
}
}
void printSerialData() {
String readI = myGsm.readStringUntil("\r\n");
Serial.println(readI);
}
The OUTPUT for this code is:
AT+CGATT=1
OK
AT+SAPBR=3,1,"CONTYPE","GPRS"
OK
AT+SAPBR=3,1,"APN","internet.wind"
OK
AT+SAPBR=2,1
+SAPBR: 1,3,"X.X.X.X"
OK
AT+SAPBR=1,1
OK
RFID Code: 172D9B32
AT+HTTPPARA="URL",http://mywebsite.000webhostapp.com/test.php?code=172D9B32
OK
AT+HTTPPARA="CID",1
OK
AT+HTTPACTION=0
OK
AT+HTTPREAD=0,20
OK
If you take a closer look at the last part of the Arduino code, under the line myGsm.println("AT+HTTPACTION=0"); and under the line myGsm.println("AT+HTTPREAD=0,20"); there are some delays that almost all the other SIM900 examples use... I didn't use the delays but with the help from other people, I made it in a way that as soon as the SIM900 has an OUTPUT it just prints it out and eliminating the delay this way. It works fine for all the other commands, but for the last 2 commands it just does something random I think because it should give me the result from the echo of the php file...
NOW look if I enable the two delays:
myGsm.println("AT+HTTPACTION=0"); //submit the GET request
delay(8000);//the delay is important if the return data are very large, the time required longer.
printSerialData();
myGsm.println("AT+HTTPREAD=0,20"); // read the data from the website you access
delay(3000);
printSerialData();
By enabling these 2 line now the OUTPUT is this(correct):
AT+CGATT=1
OK
AT+SAPBR=3,1,"CONTYPE","GPRS"
OK
AT+SAPBR=3,1,"APN","internet.wind"
OK
AT+SAPBR=2,1
+SAPBR: 1,1,"X.X.X.X"
OK
AT+SAPBR=1,1
OK
AT+HTTPINIT
OK
RFID Code: 172D9B32
AT+HTTPPARA="URL",http://mywebsite.000webhostapp.com/test.php?code=172D9B32
OK
AT+HTTPPARA="CID",1
OK
AT+HTTPACTION=0
OK
+HTTPACTION:0,200,16
AT+HTTPREAD=0,20
+HTTPREAD:16
SUCCESS 172D9B32
OK
I'm using this domain http://www.decathlon.commonarchitecture.ca/ to host my phpmyadmin database and php code. I would like to read a specific column of the database in the serial monitor, displaying each number one right after the other. I'm unsure of whether to work with a GSM shield, an Ethernet shield or an Arduino wifi shield. Here is my php code (indents are off I know):
<?php
$dbhost = "mysql.commonarchitecture.ca";
$username = "arduinodb";
$password = "*******";
$db = "arduinodb" ;
mysql_connect("$dbhost" , "$username" , "$password");
//echo "Connected" ;
//select db
mysql_select_db($db);
//echo "Connected to db" ;
$sql="SELECT * FROM data";
$records=mysql_query($sql);
?>
<!DOCTYPE html>
<html>
<head>
<title> Consumption Data </title>
</head>
<body>
<table width="600" border="1" cellpadding="1" cellspacing"1">
<tr>
<th>Day</th>
<th>Date</th>
<th>Water Consumption (liters per person)</th>
<tr>
<?php
while($data=mysql_fetch_assoc($records)) {
echo "<tr>";
echo "<td>".$data['id']."</td>";
echo "<td>".$data['date']."</td>";
echo "<td>".$data['value']."</td>";
echo "</tr>";
}//end while
?>
</table>
</body>
</html>
The code works, however I'm unsure of how to go about reading the data on an Arduino (very new to Arduino)
Here's my Arduino code paired with an ethernet shield
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, *, *);
EthernetClient client;
char server[] = "www.decathlon.commonarchitecture.ca";
void setup()
{
Serial.begin(9600);
// attempt a DHCP connection:
Serial.println("Attempting to get an IP address using DHCP:");
if (!Ethernet.begin(mac)) {
// if DHCP fails, start with a hard-coded address:
Serial.println("failed to get an IP address using DHCP, trying
manually");
Ethernet.begin(mac, ip);
}
Serial.print("My address:");
Serial.println(Ethernet.localIP());
}
void loop()
{
// connect to the server
if (client.connect(server, 80))
{
// print to serial monitor
Serial.println("connected...");
Serial.println("ARDUINO: forming HTTP request message");
// send data the server through GET request
client.print("GET /index.php?value");
client.println(" HTTP/1.1");
client.print("HOST: ");
client.println(server);
Serial.println("ARDUINO: HTTP message sent");
// give server time to receive request
delay(1000);
// get the response from the page and print it to serial port
// to ascertain that request was received properly
if(client.available())
{
Serial.println("ARDUINO: HTTP message received");
Serial.println("ARDUINO: printing received headers and
script response...\n");
while(client.available())
{
char c = client.read();
Serial.print(c);
}
}
else
{
Serial.println("ARDUINO: no response received / no response
received in time");
}
client.stop();
}
// do nothing forever after:
while(true);
}
My issue now is in getting the Arduino to read my php data, can I not use an http GET request to display data in my serial monitor? Am I using this function properly? There's a ton of documentation on posting Arduino sensor data to the web using php/my sql but not as much on retrieval of set data back into the serial monitor. Here's what the monitor reads currently...
Attempting to get an IP address using DHCP:
My address:192.168.*.*
connected...
ARDUINO: forming HTTP request message
ARDUINO: HTTP message sent
ARDUINO: no response received / no response received in time
I'm working with Arduino and its GSM Shield. This is a hardware device that allows me to make an HTTP GET request to any IP address or web URL.
So we build a PHP script that reads URL parameters, and submits that data to the database. It will be saving our Arduino data when it pings our server.
Right now, when I visit the URL with the parameters in my browser, it works great. Everything saves and can be accessed via DB. But when the Arduino makes the request or I ping the URL with cURL, the record doesn't get saved.
The response I get shows that it is loading the page and spitting back the expected HTML. Why is my PHP not reading these URL parameters and saving them?
I've looked into sessions, etc no luck.
Thanks in advance!!
EDIT:::
handle_data.php (parses parameters, saves them to DB)
<?php
// Setup our DB login info
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "arduino";
if (!empty($_GET['lat']) && !empty($_GET['lon'])) {
function getParameter($par, $default = null){
if (isset($_GET[$par]) && strlen($_GET[$par])) return $_GET[$par];
elseif (isset($_POST[$par]) && strlen($_POST[$par]))
return $_POST[$par];
else return $default;
}
$lat = getParameter("lat");
$lon = getParameter("lon");
$person = $lat.",".$lon.",".$time.",".$sat.",".$speed.",".$course."\n";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO gps_data (latitude, longitude)
VALUES (".$lat.", ".$lon.")";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
// close connection
$conn->close();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
else {
};
?>
Here's the Arduino Code:
if(started) {
//GPRS attach, put in order APN, username and password.
//If no needed auth let them blank.
if (inet.attachGPRS("internet.wind", "", ""))
Serial.println("status=ATTACHED");
else Serial.println("status=ERROR");
delay(1000);
//Read IP address.
gsm.SimpleWriteln("AT+CIFSR");
delay(5000);
//Read until serial buffer is empty.
gsm.WhileSimpleRead();
//TCP Client GET, send a GET request to the server and
//save the reply.
numdata=inet.httpGET("http://cd5d6640.ngrok.io", 80, "/handle_data.php?lat=44.87654&lon=-88.77373", msg, 50);
//Print the results.
Serial.println("\nNumber of data received:");
Serial.println(numdata);
Serial.println("\nData received:");
Serial.println(msg);
}
Note - We're developing on localhost with MAMP, using ngrok to tunnel to localhost:8888. It works fine when you visit the ngrok url in the browser, but not when we hit it with a request. The url included is irrelevant and not active.
I've been trying to connect to a Twitch chat via IRC. I've added an echo function to test where I had connected or not as that page was blank and an account didn't join the IRC.
Here is my code:
<?php
set_time_limit(0);
ini_set('display_errors', 'on');
$datatwitch= array(
'server' => 'irc.twitch.tv',
'port' => 6667,
'nick' => 'greatbritishbgbot',
'name' => 'greatbritishbgbot',
'pass' => 'oauth:HERE',
);
?>
<?php
//The server host is the IP or DNS of the IRC server.
$server_host = $datatwitch['server'];
//Server Port, this is the port that the irc server is running on. Deafult: 6667
$server_port = $datatwitch['port'];
//Server Chanel, After connecting to the IRC server this is the channel it will join.
$server_chan = "#greatbritishbg";
//login password
$nickname = $datatwitch['name'];
$nickname_pass = $datatwitch['pass'];
//Ok, We have a nickname, now lets connect.
$server = array(); //we will use an array to store all the server data.
//Open the socket connection to the IRC server
$server['SOCKET'] = #fsockopen($server_host, $server_port, $errno, $errstr, 2);
if($server['SOCKET'])
{
//Ok, we have connected to the server, now we have to send the login commands.
echo "connected";
SendCommand("PASS $nickname_pass \n\r"); //Sends the password not needed for most servers
SendCommand("NICK $nickname\n\r"); //sends the nickname
SendCommand("USER $nickname USING PHP IRC\n\r"); //sends the user must have 4 paramters
while(!feof($server['SOCKET'])) //while we are connected to the server
{
$server['READ_BUFFER'] = fgets($server['SOCKET'], 1024); //get a line of data from the server
echo "[RECIVE] ".$server['READ_BUFFER']."<br>\n\r"; //display the recived data from the server
/*
IRC Sends a "PING" command to the client which must be anwsered with a "PONG"
Or the client gets Disconnected
*/
//Now lets check to see if we have joined the server
if(strpos($server['READ_BUFFER'], "422")) //422 is the message number of the MOTD for the server (The last thing displayed after a successful connection)
{
//If we have joined the server
SendCommand("JOIN $server_chan\n\r"); //Join the chanel
}
if(substr($server['READ_BUFFER'], 0, 6) == "PING :") //If the server has sent the ping command
{
SendCommand("PONG :".substr($server['READ_BUFFER'], 6)."\n\r"); //Reply with pong
//As you can see i dont have it reply with just "PONG"
//It sends PONG and the data recived after the "PING" text on that recived line
//Reason being is some irc servers have a "No Spoof" feature that sends a key after the PING
//Command that must be replied with PONG and the same key sent.
}
flush(); //This flushes the output buffer forcing the text in the while loop to be displayed "On demand"
}
} else {
echo "connection failed";
}
function SendCommand ($cmd)
{
global $server; //Extends our $server array to this function
#fwrite($server['SOCKET'], $cmd, strlen($cmd)); //sends the command to the server
echo "[SEND] $cmd <br>"; //displays it on the screen
}
?>
It appears I can't Get passed if($server['SOCKET']). Is there anyway I can diagnose this? As I have directly connect with the details in hexChat.
The server had actually been preventing me to use fsocket. After contacting my host and moving away from a shared host it started to work.
Please take a look at this answer: https://stackoverflow.com/a/24835967/1163786
Especially:
$socket = fsockopen($bot["Host"], $bot["Port"], $error1, $error2);
if(!$socket) {
echo 'Crap! fsockopen failed. Details: ' . $error1 . ': ' . $error2;
}
To get the details about the socket error = reason for socket not connecting.
Currently, you have $errno, $errstr on fsockopen, but echo only "connection failed".