Why can I obtain file size and the time stamp with FTP but not be able to retrieve the actual file? - php

I've been working on this for about 20 hours now and I need some major help. I'm able to get the file size and the timestamp on the file but I am unable to actually obtain the data.
The server I'm trying to get the data from requires FTP over explicit TLS
I'm receiving the same error(s) with both FTP_BINARY and FTP_ASCII in the ftp_fget()
The server the file is coming from is UNIX
If I refresh the page every few hours the errors I get from PHP are different with no change in code
Error 1: 'ftp_fget(): Transfer mode set to BINARY if ftp_get is binary
or it's 'ftp_fget(): Transfer mode set to ASCII' if ftp_get is ascii
Error 2: 'ftp_fget(): Entering Passive Mode(12.345.678.90.12.34)'
On the above errors I read that PASV mode being FALSE is what triggers Error 1, so I think the switching between the errors is for pasv mode working or not working. Not positive though.
<?php
$server = "12.345.678.90";
$local_file = 'inv3.txt';
$file = 'inventory-alp.txt';
$con = ftp_ssl_connect($server,21) or die("Could not connect to $server");
ftp_login($con,"xxxxxx","xxxxxx") or die("Could not login");
ftp_pasv($con,true);
$fsize = ftp_size($con, $file); // works
if ($fsize != -1)
{
echo "</br>$file is $fsize bytes.</br></br>";
}
else
{
echo "</br>Error getting file size.</br></br>";
}
$lastchanged = ftp_mdtm($con, $file); //works
if ($lastchanged != -1)
{
echo date("F d Y H:i:s.",$lastchanged)."</br></br>";
}
else
{
echo "Could not get last modified</br></br>";
}
if (ftp_get($con,$local_file,$file,FTP_ASCII)) //fails
{
echo "successfully written to $local_file";
}
else
{
echo "There was a problem while downloading $file to $local_file";
}
$var = error_get_last();
echo '<pre>';
var_dump($var);
echo '</pre>';
ftp_close($con);
?>
EDIT 1: Solution: I ended up not being able to access what I needed to change the firewall settings and such in php. While this is not the true answer, I did make it work and it is relatively easy.I ended up running across WINSCP, having the ability to connect to the server in a filezilla type layout and then save the session url was nice. All i did was access the saved session in the .exe and was able to set up my connection in half an hour.

What Martin indicated is very true, the SIZE and MDTM commands run synchronized over the main FTP Command Connection only. The transferring of data files, and usually the directory listing also (unless MLST/MSLD is used) requires a separate connection, the Data Connection, which is negotiated by the client and server over the Control Connection using a series of commands, most notably PORT and PASV.
Without going into a ton of detail (There's a link to our white paper later), when the Client & Server negotiate the terms of the Data Connection, one of the end points will tell the other endpoint the specific IP address and Port number for the connection. One endpoint will listen and wait for a connection from the other endpoint. This works great unless there is a firewall in front of the endpoint that is waiting for the inbound connection. If the client/server session is running in Active mode, the Server will actively connect back to the client on the IP/Port which was received by the server from the client in the form of the PORT command. In Passive mode, the Server will passively wait for the client to connect on the IP/Port which was sent by the server to the client in the response to the PASV command sent by the client to the server.
Again, firewalls tend to block FTP data connections, unless the firewall does active FTP NAT'ing or unless Port Forwarding has been set up on the Firewall and a set of passive-ports has been opened and routed to the endpoint specifically.
So check the firewall settings on the client if you want to use Active/Port mode; check the firewall settings on the server if you want to use Passive/PASV mode.
Here's a link to our white paper which outlines the basics of FTP/PASV/PORT, hopefully it'll help you with your issue.
http://www.webdrive.com/wp-content/uploads/FTP_Explained1.pdf
Best of Luck!
Michael

With the FTP protocol, it's perfectly possible that you are able to obtain the file size and the modification timestamp (using SIZE and MDTM commands respectively), but not the file itself.
The SIZE and MDTM commands use the FTP control connection only.
While a file transfer (or a directory listing) requires a separate data connection. And it's likely that there's something that prevents the data connection from being opened.
See (my) article on the FTP connection modes for more details and typical issues with data connections.
Typically a culprit would be a firewall on your webserver. If you have an SSH/terminal access to the webserver, are you able to connect from it to the FTP server?
Another possibility is a misconfigured FTP server. Is the IP address in "Error 2" routable from your web server? (=Is it the real IP address you connect to?)
It is unlikely this is related to an ASCII/BINARY mode. The messages you are getting (Transfer mode set to ...) are status messages, not error messages. They are not related to your problem. It's indeed strange that you got no other message/error.
You can try to use the active mode, instead of the passive.
ftp_pasv($con, false);
But usually the active mode is more problematic.

Related

Fatal error: Uncaught mysqli_sql_exception: No connection could be made because the target machine actively refused [duplicate]

I'm using the WCF4.0 template -REST. I'm trying to make a method that uploads a file using a stream.
The problem always occur at
Stream serverStream = request.GetRequestStream();
Class for streaming:
namespace LogicClass
{
public class StreamClass : IStreamClass
{
public bool UploadFile(string filename, Stream fileStream)
{
try
{
FileStream fileToupload = new FileStream(filename, FileMode.Create);
byte[] bytearray = new byte[10000];
int bytesRead, totalBytesRead = 0;
do
{
bytesRead = fileStream.Read(bytearray, 0, bytearray.Length);
totalBytesRead += bytesRead;
} while (bytesRead > 0);
fileToupload.Write(bytearray, 0, bytearray.Length);
fileToupload.Close();
fileToupload.Dispose();
}
catch (Exception ex) { throw new Exception(ex.Message); }
return true;
}
}
}
REST project:
[WebInvoke(UriTemplate = "AddStream/{filename}", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)]
public bool AddStream(string filename, System.IO.Stream fileStream)
{
LogicClass.FileComponent rest = new LogicClass.FileComponent();
return rest.AddStream(filename, fileStream);
}
Windows Form project: for testing
private void button24_Click(object sender, EventArgs e)
{
byte[] fileStream;
using (FileStream fs = new FileStream("E:\\stream.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
{
fileStream = new byte[fs.Length];
fs.Read(fileStream, 0, (int)fs.Length);
fs.Close();
fs.Dispose();
}
string baseAddress = "http://localhost:3446/File/AddStream/stream.txt";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(baseAddress);
request.Method = "POST";
request.ContentType = "text/plain";
Stream serverStream = request.GetRequestStream();
serverStream.Write(fileStream, 0, fileStream.Length);
serverStream.Close();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
int statusCode = (int)response.StatusCode;
StreamReader reader = new StreamReader(response.GetResponseStream());
}
}
I've turned off the firewall and my Internet connection, but the error still exists. Is there a better way of testing the uploading method?
Stack trace:
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
"Actively refused it" means that the host sent a reset instead of an ack when you tried to connect. It is therefore not a problem in your code. Either there is a firewall blocking the connection or the process that is hosting the service is not listening on that port. This may be because it is not running at all or because it is listening on a different port.
Once you start the process hosting your service, try netstat -anb (requires admin privileges) to verify that it is running and listening on the expected port.
update: On Linux you may need to do netstat -anp instead.
You don't have to restart the PC. Restart IIS instead.
Run -> 'cmd'(as admin) and type "iisreset"
You must set up your system proxy
You have to go through this path
controlpanel>>internet option>>connnection>>LAN settings>>
proxy
no tik:use proxy server
I got a similar error message like TCP error code 10061: No connection could be made because the target machine actively refused it in my current project. I find this 10061 error code cannot distinguish the case that the service endpoint is not started and the case that it is blocked by the firewall. Often, the firewall can be switched off, but the problem is still there.
You can test your code in the below two ways.
Insert code to get time A that service is started and time B that client sends the request to the server. If B is earlier than A, it can cause this problem.
Change your server port to another port that is also available in the system. You will find the same error code reported.
Above is my fix. It works on my machine. I hope it helps!
Check if any other program is using that port.
If an instance of the same program is still active, kill that process.
I had a similar issue. In my case the service would work fine on the developer machine but fail when on a QA machine. It turned out that on the QA machine the application wasn't being run as an administrator and didn't have permission to register the endpoint:
HTTP could not register URL http://+:12345/Foo.svc/]. Your process does
not have access rights to this namespace (see
http://go.microsoft.com/fwlink/?LinkId=70353 for details).
Refer here for how to get it working without being an admin user: https://stackoverflow.com/a/885765/38258
If you use WCF storm, can you even log-in to the WCF service endpoint? If not, and you are hosting it in a Windows service, you probably forgot to register that namespace. It's not very well advertised that this step is required, and it is actually annoying to do.
I use this tool to do this; it automates all those cumbersome steps.
Check whether the port number in file Web.config of your webpage is the same as the one that is hosted on IIS.
I had the same problem on my web server "No connection could be made because the target machine actively refused it 161.x.x.235:5672". I asked the Admin to open the port 5672 on the web server, then it worked fine.
I had a similar problem
rejecting localhost and 127.0.0.1.
cmd(admin) netstat -anb found the port running on 169.254.80.80 (dont know were that ip came from because my network ip was 10.0.0.5.
after putting in this IP it worked.
This Gives correct IP:
IPAddress ipAddress = ipHostInfo.AddressList[0];
Console.WriteLine(ipAddress.ToString());
I also faced problem in .Net Remoting Service in C#.
I got it solved in 3 steps:
Change Port of Protocol in all the files whereever it is being used.
Run your Host Server Program and make it active.
Now run your client program.
I could not restart IIexpress. This is the solution that worked for me
Cleaned the build
Rebuild
With this error I was able to trace it, thanks to #Yaur, you need to basically check the service (WCF) if it's running and also check the outbound and inbound TCP properties on your advance firewall settings.
With similar pattern, my rest client is calling the service API, the service called successfully when debugging, but not working on the published code. Error was: Unable to connect to the remote server.
Inner Exception: System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it serviceIP:443 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
Resolution: Set the proxy in Web config.
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy proxyaddress="http://proxy_ip:portno/" usesystemdefault="True"/>
</defaultProxy>
</system.net>
I had a similar issue. In my case VPN proxy app such as Psiphon ، changed the proxy setup in windows so follow this :
in Windows 10, search change proxy settings and turn of use proxy server in the manual proxy
Make Sure all services used by your application are on, which are using host and port to utilize them . For e.g, as in my case, This error can come, If your application is utilizing a Redis server and it is not being able to connect to it on given port and host, thus producing this error .
For my case, I had an Angular SLA project template with ASP.NET Core.
I was trying to run the IIS Express from the Visual Studio WebUI solution, triggering the "Actively refused it" error.
The problem, in this case, wasn't connected with the Firewall blocking the connection.
It turned out that I had to run the Angular server independently of the Kestrel run because the Server was expecting the UI to run on a specific port but wasn't actually.
For more information, check the official Microsoft documentation.
I had similar problem. In launchSettings, my IIS Express was configured on one port, and there was another launch profile that started on another ApplicationUrl with another port.
Starting the web app up with the IIS Express profile led me to have the error.
I am using the Apache ActiveMQ Artemis AMQP message broker. I started getting the "No connection could be made because the target machine actively refused it" exception when trying to send and receive messages with the broker after a reboot. On a computer where the same type of broker still worked, netstat -anb showed that the broker was listening on the expected port 5672. On the computer with the error, the broker was not listening. On the computer with the error, starting the broker resulted in the following warning's appearing in Microsoft Event Viewer's "Windows Logs > System":
The system failed to register host (A or AAAA) resource records for network adapter
with settings:
Adapter Name : {286EE2DA-3D81-41AE-VE5G-5D761FD3925E}
Host Name : mypc
Primary Domain Suffix : myco.com
DNS server list :
55.77.168.1, 74.86.130.1
Sent update to server : 186.952.335.157:45
IP Address(es) :
182.269.1.437
Either the DNS server does not support the DNS dynamic update protocol or the authoritative zone for the specified DNS domain name does not accept dynamic updates.
To register the DNS host (A or AAAA) resource records using the specific DNS domain name and IP addresses for this adapter, contact your DNS server or network systems administrator.
I was able to use the broker without error after I ran the following in a cmd.exe with administrative privileges, rebooted, and waited about fifteen minutes:
ipconfig /flushdns
ipconfig /renew
ipconfig /registerdns

PHP Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] on heavy query [duplicate]

Sometimes I get the following error while I was doing HttpWebRequest to a WebService. I copied my code below too.
System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream()
ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.PreAuthenticate = true;
request.Credentials = networkCredential(sla);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = v_Timeout * 1000;
if (url.IndexOf("asmx") > 0 && parStartIndex > 0)
{
AppHelper.Logger.Append("#############" + sla.ServiceName);
using (StreamWriter reqWriter = new StreamWriter(request.GetRequestStream()))
{
while (true)
{
int index01 = parList.Length;
int index02 = parList.IndexOf("=");
if (parList.IndexOf("&") > 0)
index01 = parList.IndexOf("&");
string parName = parList.Substring(0, index02);
string parValue = parList.Substring(index02 + 1, index01 - index02 - 1);
reqWriter.Write("{0}={1}", HttpUtility.UrlEncode(parName), HttpUtility.UrlEncode(parValue));
if (index01 == parList.Length)
break;
reqWriter.Write("&");
parList = parList.Substring(index01 + 1);
}
}
}
else
{
request.ContentLength = 0;
}
response = (HttpWebResponse)request.GetResponse();
If this happens always, it literally means that the machine exists but that it has no services listening on the specified port, or there is a firewall stopping you.
If it happens occasionally - you used the word "sometimes" - and retrying succeeds, it is likely because the server has a full 'backlog'.
When you are waiting to be accepted on a listening socket, you are placed in a backlog. This backlog is finite and quite short - values of 1, 2 or 3 are not unusual - and so the OS might be unable to queue your request for the 'accept' to consume.
The backlog is a parameter on the listen function - all languages and platforms have basically the same API in this regard, even the C# one. This parameter is often configurable if you control the server, and is likely read from some settings file or the registry. Investigate how to configure your server.
If you wrote the server, you might have heavy processing in the accept of your socket, and this can be better moved to a separate worker-thread so your accept is always ready to receive connections. There are various architecture choices you can explore that mitigate queuing up clients and processing them sequentially.
Regardless of whether you can increase the server backlog, you do need retry logic in your client code to cope with this issue - as even with a long backlog the server might be receiving lots of other requests on that port at that time.
There is a rare possibility where a NAT router would give this error should its ports for mappings be exhausted. I think we can discard this possibility as too much of a long shot though, since the router has 64K simultaneous connections to the same destination address/port before exhaustion.
The most probable reason is a Firewall.
This article contains a set of reasons, which may be useful to you.
From the article, possible reasons could be:
FTP server settings
Software/Personal Firewall Settings
Multiple Software/Personal Firewalls
Anti-virus Software
LSP Layer
Router Firmware
Computer Turned Off
Computer Not Plugged In
Fiddler
I had the same. It was because the port-number of the web service was changing unexpectedly.
This problem usually happens when you have more than one copy of the project
My project was calling the Web service with a specific port number which I assigned in the Web.Config file of my main project file. As the port number changed unexpectedly, the browser was unable to find the Web service and throwing that error.
I solved this by following the below steps: (Visual Studio 2010)
Go to Properties of the Web service project --> click on Web tab --> In Servers section --> Check Specific port
and then assign the standard port number by which your main project is calling the web service.
I hope this will solve the problem.
Cheers :)
I think, you need to check your proxy settings in "internet options". If you are using proxy/'hide ip' applications, this problem may be occurs.
I had the same problem. The problem is that I didn't start the selenium server. I have downloaded the selenium server and i started it. After starting the selenium server, issue gone and all worked fine.
Refer this : http://coding-issues.blogspot.in/2012/11/no-connection-could-be-made-because.html
I had the same error with my WCF service using Net TCP binding, but resolved after starting the below services in my case.
Net.Pipe.Listener.Adapter
Net.TCP.Listener.Adapter
Net.Tcp Port Sharing Service
In my case, some domains worked, while some did not. Adding a reference to my organization's proxy Url in my web.config fixed the issue.
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy proxyaddress="http://proxy.my-org.com/" usesystemdefault="True"/>
</defaultProxy>
</system.net>
When you call service which has only HTTP (ex: http://example.com) and you call HTTPS (ex: https://example.com), you get exactly this error - "No connection could be made because the target machine actively refused it"
I faced same error because when your Server and Client run on same machine the Client need server local ip address not Public ip address to communicate with server you need Public ip address only in case when Server and Client run on separate machine so use Local ip address in client program to connect with server Local ip address can be found using this method.
public static string Getlocalip()
{
try
{
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
return localIPs[7].ToString();
}
catch (Exception)
{
return "null";
}
}
I got this error in an application that uses AppFabric. The clue was getting a DataCacheException in the stack trace. To see if this is the issue for you, run the following PowerShell command:
#("AppFabricCachingService","RemoteRegistry") | % { get-service $_ }
If either of these two services are stopped, then you will get this error.
For me, I wanted to start the mongo in shell (irrelevant of the exact context of the question, but having the same error message before even starting the mongo in shell)
The process 'MongoDB Service' wasn't running in Services
Start cmd as Administrator and type,
net start MongoDB
Just to see MongoDB is up and running just type mongo, in cmd it will give Mongo version details and Mongo Connection URL
Well, I've received this error today on Windows 8 64-bit out of the blue, for the first time, and it turns out my my.ini had been reset, and the bin/mysqld file had been deleted, among other items in the "Program Files/MySQL/MySQL Server 5.6" folder.
To fix it, I had to run the MySQL installer again, installing only the server, and copy a recent version of the my.ini file from "ProgramData/MySQL/MySQL Server 5.6", named my_2014-03-28T15-51-20.ini in my case (don't know how or why that got copied there so recently) back into "Program Files/MySQL/MySQL Server 5.6".
The only change to the system since MySQL worked was the installation of Native Instruments' Traktor 2 and a Traktor Audio 2 sound card, which really shouldn't have caused this problem, and no one else has used the system besides me. If anyone has a clue, it would be kind of you to comment to prevent this for me and anyone else who has encountered this.
For service reference within a solution.
Restart your workstation
Rebuild your solution
Update service reference in WCFclient project
At this point, I received messsage (Windows 7) to allow system access.
Then the service reference was updated properly without errors.
I would like to share this answer I found because the cause of the problem was not the firewall or the process not listening correctly, it was the code sample provided from Microsoft that I used.
https://msdn.microsoft.com/en-us/library/system.net.sockets.socket%28v=vs.110%29.aspx
I implemented this function almost exactly as written, but what happened is I got this error:
2016-01-05 12:00:48,075 [10] ERROR - The error is: System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it [fe80::caa:745:a1da:e6f1%11]:4080
This code would say the socket is connected, but not under the correct IP address actually needed for proper communication. (Provided by Microsoft)
private static Socket ConnectSocket(string server, int port)
{
Socket s = null;
IPHostEntry hostEntry = null;
// Get host related information.
hostEntry = Dns.GetHostEntry(server);
// Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
// an exception that occurs when the host IP Address is not compatible with the address family
// (typical in the IPv6 case).
foreach(IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
Socket tempSocket =
new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
tempSocket.Connect(ipe);
if(tempSocket.Connected)
{
s = tempSocket;
break;
}
else
{
continue;
}
}
return s;
}
I re-wrote the code to just use the first valid IP it finds. I am only concerned with IPV4 using this, but it works with localhost, 127.0.0.1, and the actually IP address of you network card, where the example provided by Microsoft failed!
private Socket ConnectSocket(string server, int port)
{
Socket s = null;
try
{
// Get host related information.
IPAddress[] ips;
ips = Dns.GetHostAddresses(server);
Socket tempSocket = null;
IPEndPoint ipe = null;
ipe = new IPEndPoint((IPAddress)ips.GetValue(0), port);
tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
Platform.Log(LogLevel.Info, "Attempting socket connection to " + ips.GetValue(0).ToString() + " on port " + port.ToString());
tempSocket.Connect(ipe);
if (tempSocket.Connected)
{
s = tempSocket;
s.SendTimeout = Coordinate.HL7SendTimeout;
s.ReceiveTimeout = Coordinate.HL7ReceiveTimeout;
}
else
{
return null;
}
return s;
}
catch (Exception e)
{
Platform.Log(LogLevel.Error, "Error creating socket connection to " + server + " on port " + port.ToString());
Platform.Log(LogLevel.Error, "The error is: " + e.ToString());
if (g_NoOutputForThreading == false)
rtbResponse.AppendText("Error creating socket connection to " + server + " on port " + port.ToString());
return null;
}
}
This is really specific, but if you receive this error after trying to connect to a database using mongo, what worked for me was running mongod.exe before running mongo.exe and then the connection worked fine. Hope this helps someone.
One more possibility --
Make sure you're trying to open the same IP address as where you're listening. My server app was listening to the host machine's IP address using IPv6, but the client was attempting to connect on the host machine's IPv4 address.
I've received this error from referencing services located on a WCFHost from my web tier. What worked for me may not apply to everyone, but I'm leaving this answer for those whom it may. The port number for my WCFHost was randomly updated by IIS, I simply had to update the end routes to the svc references in my web config. Problem solved.
In my scenario, I have two applications:
App1
App2
Assumption: App1 should listen to App2's activities on Port 5000
Error: Starting App1 and trying to listen, to a nonexistent ghost town, produces the error
Solution: Start App2 first, then try to listen using App1
Go to your WCF project -
properties ->
->
debuggers
-> unmark the checkbox
Enable Edit and Continue
In my case this was caused by a faulty deployment where a setting in my web.config was not made.
A collegue explained that the IP address in the error message represents the localhost.
When I corrected the web.config I was then using the correct url to make the server calls and it worked.
I thought I would post this in case it might help someone.
Using WampServer 64bit on Windows 7 Home Premium 64bit I encountered this exact problem. After hours and hours of experimentation it became apparent that all that was needed was in my.ini to comment out one line. Then it worked fine.
commented out 1 line
socket=mysql
If you put your old /data/ files in the appropriate location, WampServer will accept all of them except for the /mysql/ folder which it over writes. So then I simply imported a backup of the /mysql/ user data from my prior development environment and ran FLUSH PRIVILEGES in a phpMyAdmin SQL window. Works great. Something must be wrong because things shouldn't be this easy.
I had this issue happening often. I found SQL Server Agent service was not running. Once I started the service manually, it got fixed. Double check if the service is running or not:
Run prompt, type services.msc and hit enter
Find the service name - SQL Server Agent(Instance Name)
If SQL Server Agent is not running, double-click the service to open properties window. Then click on Start button. Hope it will help someone.
I came across this error and took some time to resolve it. In my case I had https and net.tcp configured as IIS bindings on same port. Obviously you can't have two things on the same port. I used netstat -ap tcp command to check whether there is something listening on that port. There was none listening. Removing unnecessary binding (https in my case) solved my issue.
It was a silly issue on my side, I had added a defaultproxy to my web.config in order to intercept traffic in Fiddler, and then forgot to remove it!
There is a service called "SQL Server Browser" that provides SQL Server connection information to clients.
In my case, none of the existing solutions worked because this service was not running. I resumed it and everything went back to working perfectly.
I was facing this issue today. Mine was Asp.Net Core API and it uses Postgresql as the database. We have configured this database as a Docker container. So the first step I did was to check whether I am able to access the database or not. To do that I searched for PgAdmin in the start as I have configured the same. Clicking on the resulted application will redirect you to the http://127.0.0.1:23722/browser/. There you can try access your database on the left menu. For me I was getting an error as in the below image.
Enter the password and try whether you are able to access it or not. For me it was not working. As it is a Docker container, I decided to restart my Docker desktop, to do that right click on the docker icon in the task bar and click restart.
Once after restarting the Docker, I was able to login and see the Database and also the error was gone when I restart the application in Visual Studio.
Hope it helps.
it might be because of authorisation issues; that was the case for me.
If you have for example: [Authorize("WriteAccess")] or [Authorize("ReadAccess")] at the top of your controller functions, try to comment them out.
I just faced this right now...
Here on my end, I have 2 separated Visual Studio solutions (.sln)... opened each one in their own Visual Studio instance.
Solution 2 calls Solution 1 code. The problem was related to the port assigned to Solution 1. I had to change the port on solution 1 to another one and then Solution 2 started working again. So make sure you check the port assigned to your project.
Normally, connection scripts do not mention the port to use. For example:
$mysqli = mysqli_connect('127.0.0.0.1', 'user', 'password', 'database');
So, to connect with a manager that doesn't use port 3306, you have to specify the port number on the connection request:
$mysqli = mysqli_connect('127.0.0.0.1', 'user', 'password', 'database', '3307');
To check the connections on the MySQL or MariaDB database manager, use the script:
wamp(64)\www\testmysql.php
by putting 'http://localhost/testmysql.php' in the browser address bar having first modified the script according to your parameters.
I forgot to start the service so it failed because no service was listening on port.
Resolved by starting the service.

Unable to run FTP commands from AWS AMI

I want to connect to an FTP using PHP to upload the reports generated. As per the remote server, the FTP needs to be in ACTIVE mode.
this is my code:
ini_set('display_errors', '1');
error_reporting(E_ALL);
$conn_id = ftp_connect('myftpserver.com', 21);
if($conn_id)
{
// login with username and password
$login_result = ftp_login($conn_id, 'mysuer', 'password');
$passive = ftp_pasv($conn_id,FALSE);
echo "is active?<br/>";
var_dump($passive);
echo 'Login Result:';
var_dump($login_result);
$files_list = ftp_nlist($conn_id, '/MyFolder/');
echo "<br/>files list ";
var_dump($files_list);
}
else
{
var_dump('Unable to connect to FTP Server');
}
When I am running it from the local machine or a normal shared server, I am able fetch the list, but I am unable to run the script from my AWS AMI instance. For testing purpose, I have even opened all inbound traffic too. Still no luck. Also, the point is that if I try with some other ftp details, I am able to get the response of ftp_nlist. But not for this one. I tried it on 3 AWS instances till yet. Yielded the same result.
All I can say is that this is somewhere the issue at my server security group/firewall. But unable to figure it out. Please help.
The response I get from the server:
is active
bool(true)
Login Result:bool(true)
files list bool(false)
Using FTP Active Mode is problematic with AWS Security Groups.
For active mode to work, you will have to open all inbound ports above 1023. If your client supports restricting the range, do so. You will also need to open both port 20 and port 21 inbound and outbound.
The problem is that the FTP client selects a port that it will listen on. Then the FTP client informs the FTP Server of this port number. The FTP Server then connects to this port. This goes against normal AWS Security Group designs meaning only allow specific ports to be open. You can verify this by opening all ports temporarily, test your FTP client and then closing all the ports.
Active Mode is not secure for the FTP client. Passive Mode is not secure for the FTP server (but the better choice).
NOTE: Rotate your FTP credentials often. Your login and password is sent in the clear and are not encrypted.
FTP is a legacy technology, which is still very popular, that should be stored away in the attic.

Cannot connect to server from another server ftp php

I work with 2 servers one is my production server other is my resource server.
I cannot connect to my resource server from my production server over ftp.
I can connect to other servers from my production server.
I can also connect to my resource server from my localhost or filezilla.
I use this code to connect :
$conn_id = ftp_connect("resource server ip", "21", "5");
if ($conn_id) {
echo "connected";
ftp_close($conn_id);
}
print_r(error_get_last());
I don't get any output when I run this script on server(no error).
On localhost it runs no problem.
What can be the problem with this? Is this something that server admin has to resolve? Thanks for help.
You should first check from commandline, whether it's a networking/OS issue or not.
So if you've got shell access to the production server try connecting to the resource server via the commandline ftp client.
If that does not work, you've got a network / firewall / access control problem, not related to php or your software, and you should talk to the sysadmin.
If it does work, then the problem is in your stuff, and you should set the log levels to high, and run this script from commandline, also check the logs of php, php-error, syslog and the resource servers ftp access log and syslog too.
Note: ftp is a not-too-exact beast, the servers and clients have a lot of workarounds built in to treat each other in a way, that works somehow. There could be issues from active (multiple back-and-forth connections) and passive mode (it's like http), also with ls formats and timestamps, timezones and ports.
Also some servers only support ftps (ftp with ssl) - which is not the same as sftp (file transfer over ssh - port 22).
Your production server probably has some firewall rules, and your connection get caught on that, to debug this, please use the commandline ftp client, and/or nmap / netcat.

"php_connect_nonb() failed: Operation now in progress (115)" happens intermittently

We send some files across to a third party with a PHP cron job via FTP.
However sometimes we get the following error:
ErrorException [ 2 ]: ftp_put(): php_connect_nonb() failed: Operation
now in progress (115) ~ MODPATH/fileop/classes/Drivers/Fileop/Ftp.php [ 37 ]
When I say "sometimes" I mean exactly that; most times it goes across fine but about 1 in 5 times we get that error. It's not to do with the files themselves, because they will go happily if we try again.
We've found similar issues online - relating to a bug in PHP with NAT devices or to do with firewall configuration but again the implication is that if this were the case it would never work.
So, why would this work some times and not others?
ftp_set_option($ftpconn, FTP_USEPASVADDRESS, false);
This line of code before setting passivity of the connection ftp_pasv($ftpconn, true);
Solved my problem
FTP(S) uses random ports to set up data connections; an intermittent success rate indicates that not all ports are allowed by a firewall on the client and/or server machines. The port range for incoming (PASV) data connections can be set in the FTP server.
This page has a nice summary:
The easy way is to simply allow FTP servers and clients unlimited
access through your firewall, but if you like to limit their access to
"known" ports, you have to understand the 4 different scenarios.
1) The FTP server should be allowed to accept TCP connections to port
21, and to make TCP connections from port 20 to any (remote ephemeral)
port.
2) The FTP server should be allowed to accept TCP connections to port
21, AND to accept TCP connections to any ephemeral port as well!
3) The FTP client should be allowed to make TCP connections to port
21, and to accept TCP connections from port 20 to any ephemeral port.
4) The FTP client should be allowed to make TCP connections to port
21, and to make TCP connections to any other (remote ephemeral) port
as well!
So, I'm writing this answer after doing some investigation on my FTP server and reading the link you provided elitehosts.com.
I'm using FileZilla FTP server, and there is a specific setting that I had to enter to make it work. Going into the server settings, there is an area titled "Passive mode settings". In that dialog, there is an area titled "IPv4 specific", and within that area there is a setting labeled "External Server IP Address for passive mode transfers:". It's a radio button selection set, and it was on "Default", but since the FTP server is NAT'ed, I changed that radio selection from "Default" to "Use the following IP:" and entered in the external-facing IP address of my gateway provided by my ISP.
After I set this up, it worked! Not terribly sure if your FTP server is NAT'ed, but I thought I would provide the answer on this thread because it seems related.
In addition to Cees answer, I am running vsftp on ec2 and had to comment out the listen_ipv6=YES, listen=YES then "service vsftpd restart".
Although documentation says it will listen on ipv4 as well it wasn't and this resolved the issue.
For me all I had to do was to remove the ftp_pasv( $ftpconn, true ); and everything worked perfectly. I'm not yet sure why but I am trying to find out and I will surely come back when I do get the reason behind it.
This should be a comment under jj_dev2 comment, but I cannot add one due to reputation. But maybe it will be helpful for someone, so I post it here.
We had the same issue as described in the original post. In our case it worked with many customers - except one.
The solution in jj_dev2 comment did work for us. So we investigated what does ftp_set_option($conn, FTP_USEPASVADDRESS, false) actually do. And based on that we found out that in fact customer's FTPS server was configured incorrectly.
In response to PASV command (ftp_pasv($conn, true)) FTP server returns an IP address which the PHP FTP client then will use for data transfers. In our case the FTP server was returning an internal IP address and not the public IP address that we connect to. Customer had to fix their FTP server settings so FTP server would send external IP address in the PASV command response.

Categories