Php file get contents port

PHP workaround – how to use file_get_contents() without allow_url_fopen

I admit, the title of this article is somewhat misleading. The PHP function file_get_contents(), which can be used to read files from the internet into a string, just does not work with allow_url_fopen disabled. On that not even this article will change anything.

However, if you want to develop an application or a script, that should work on as many server environments as possible, such as a wordpress plugin, so there is a good workaround for all the environments where allow_url_fopen is disabled. And just this little snippet/workaround is what I want to show and explain to you today.

$file = «http://www.example.com/my_page.php»; if (function_exists(‘curl_version’)) < $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $file); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $content = curl_exec($curl); curl_close($curl); >else if (file_get_contents(__FILE__) && ini_get(‘allow_url_fopen’)) < $content = file_get_contents($file); >else

First, it is checked whether the cURL extension is available on the server. If this is the case, the file is loaded via cURL. If cURL is not available, it is checked if allow_url_fopen is enabled. If this is the case, the file is loaded via file_get_contents().

If both options are not available, an error message is displayed, what should protect the enduser from seeing, for him maybe “cryptic”, error messages.

If you wonder why I give cURL preference over file_get_contents(), the reason is that I’ve made the experience that cURL has somewhat better performance.

In conclusion it can be said, that using the workaround outlined here, the chance that your script is running at as many environments as possible, can be doubled. (Doubled due to the fact you’ll provide two methods for downloading files to the server.) That’s quite something, isn’t it?

What do you think about my snippet? Would you implement it in the same way? How do you deal with the “problem” of deactivated allow_url_fopen?

Источник

file_get_contents не работает на порту 8282

У меня есть следующий базовый сценарий, который делает основной запрос POST (я просто хочу, чтобы он работал, после того, как я добавлю больше вещей):

# Variables $URL = 'http://******:8282/api/incoming_shipment/'; $postdata = http_build_query( array( 'contract_id' => 'Showcare-R124276', 'shipment_from' => 'Montréal', 'shipment_to' => 'Chicago', 'shipping_time' => '2012-08-16 14:51:01', 'tracking_cie' => 'Poste Canada', 'tracking_type' => 'Standard', 'tracking_number' => 'EP645 9834 123 9773' ) ); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents($URL, FALSE, $context); print_r($result); 
Warning: file_get_contents(http://******:8282/api/incoming_shipment/) [function.file-get-contents]: failed to open stream: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. in D:\Inetpub\hightechhandling\api\api_push_contract.php on line 31 Fatal error: Maximum execution time of 30 seconds exceeded in D:\Inetpub\hightechhandling\api\api_push_contract.php on line 31 

Но когда я иду на веб-страницу с моим браузером, он работает отлично. Я пробовал cURL и fsocketopen, но это тоже не сработало. Любая помощь, пожалуйста? Благодаря..

Читайте также:  Python tkinter random color

EDIT Я добавил set_time_limit (500); и теперь вторая ошибка, конечно, исчезла … но первая по-прежнему остается.

Хорошо, нашел проблему. Было глупо. Проблема в том, что сервер, делающий запрос (где находится файл PHP), имеет брандмауэр, а брандмауэр разрешает только внешний порт 21, 22, 80, 3306 и 1433 для внешнего запроса.

Из руководства PHP

void set_time_limit (int $ seconds)

Установите количество секунд, в течение которых сценарий можно запустить. Если это будет достигнуто, скрипт вернет фатальную ошибку. Предел по умолчанию составляет 30 секунд или, если он существует, значение max_execution_time, определенное в php.ini.

Когда вызывается, set_time_limit () перезапускает счетчик тайм-аута с нуля. Другими словами, если таймаутом является значение по умолчанию 30 секунд и 25 секунд для выполнения скрипта, выполняется вызов типа set_time_limit (20), скрипт будет работать в общей сложности за 45 секунд до истечения времени ожидания. Если установлено равным нулю, лимит времени не налагается.

'header' => implode("\r\n", array("Connection: close", "Content-type: application/x-www-form-urlencoded")), 

(особенно соединение: близкий бит)

Также: можете ли вы дублировать проблему на commanline с curl?

Для CentOS использование file_get_contents() для доступа к URL-адресу на порту, отличном от 80, не работает с разрешенным разрешением. Он работает только тогда, когда selinux установлен на «disabled» или «permissive».

Если вы не хотите отключать selinux для обеспечения безопасности, вы можете изменить политику selinux, чтобы HTTPd мог прослушивать 8282

Чтобы указать, какие порты разрешены для порта httpd: semanage -l | grep -w http_port_t

Чтобы добавить порт 8282: порт семантики -a -t http_port_t -p tcp 8282

Источник

Php – file_get_contents on other port

If your action is not idempotent, then you MUST use POST . If you don’t, you’re just asking for trouble down the line. GET , PUT and DELETE methods are required to be idempotent. Imagine what would happen in your application if the client was pre-fetching every possible GET request for your service – if this would cause side effects visible to the client, then something’s wrong.

I agree that sending a POST with a query string but without a body seems odd, but I think it can be appropriate in some situations.

Think of the query part of a URL as a command to the resource to limit the scope of the current request. Typically, query strings are used to sort or filter a GET request (like ?page=1&sort=title ) but I suppose it makes sense on a POST to also limit the scope (perhaps like ?action=delete&id=5 ).

Rest – Understanding REST: Verbs, error codes, and authentication

I noticed this question a couple of days late, but I feel that I can add some insight. I hope this can be helpful towards your RESTful venture.

Point 1: Am I understanding it right?

Читайте также:  Function in java language

You understood right. That is a correct representation of a RESTful architecture. You may find the following matrix from Wikipedia very helpful in defining your nouns and verbs:

When dealing with a Collection URI like: http://example.com/resources/

  • GET: List the members of the collection, complete with their member URIs for further navigation. For example, list all the cars for sale.
  • PUT: Meaning defined as «replace the entire collection with another collection».
  • POST: Create a new entry in the collection where the ID is assigned automatically by the collection. The ID created is usually included as part of the data returned by this operation.
  • DELETE: Meaning defined as «delete the entire collection».

When dealing with a Member URI like: http://example.com/resources/7HOU57Y

  • GET: Retrieve a representation of the addressed member of the collection expressed in an appropriate MIME type.
  • PUT: Update the addressed member of the collection or create it with the specified ID.
  • POST: Treats the addressed member as a collection in its own right and creates a new subordinate of it.
  • DELETE: Delete the addressed member of the collection.

Point 2: I need more verbs

In general, when you think you need more verbs, it may actually mean that your resources need to be re-identified. Remember that in REST you are always acting on a resource, or on a collection of resources. What you choose as the resource is quite important for your API definition.

Activate/Deactivate Login: If you are creating a new session, then you may want to consider «the session» as the resource. To create a new session, use POST to http://example.com/sessions/ with the credentials in the body. To expire it use PUT or a DELETE (maybe depending on whether you intend to keep a session history) to http://example.com/sessions/SESSION_ID .

Change Password: This time the resource is «the user». You would need a PUT to http://example.com/users/USER_ID with the old and new passwords in the body. You are acting on «the user» resource, and a change password is simply an update request. It’s quite similar to the UPDATE statement in a relational database.

My instinct would be to do a GET call to a URL like /api/users/1/activate_login

This goes against a very core REST principle: The correct usage of HTTP verbs. Any GET request should never leave any side effect.

For example, a GET request should never create a session on the database, return a cookie with a new Session ID, or leave any residue on the server. The GET verb is like the SELECT statement in a database engine. Remember that the response to any request with the GET verb should be cache-able when requested with the same parameters, just like when you request a static web page.

Point 3: How to return error messages and codes

Consider the 4xx or 5xx HTTP status codes as error categories. You can elaborate the error in the body.

Failed to Connect to Database: / Incorrect Database Login: In general you should use a 500 error for these types of errors. This is a server-side error. The client did nothing wrong. 500 errors are normally considered «retryable». i.e. the client can retry the same exact request, and expect it to succeed once the server’s troubles are resolved. Specify the details in the body, so that the client will be able to provide some context to us humans.

Читайте также:  Array object methods java

The other category of errors would be the 4xx family, which in general indicate that the client did something wrong. In particular, this category of errors normally indicate to the client that there is no need to retry the request as it is, because it will continue to fail permanently. i.e. the client needs to change something before retrying this request. For example, «Resource not found» (HTTP 404) or «Malformed Request» (HTTP 400) errors would fall in this category.

Point 4: How to do authentication

As pointed out in point 1, instead of authenticating a user, you may want to think about creating a session. You will be returned a new «Session ID», along with the appropriate HTTP status code (200: Access Granted or 403: Access Denied).

You will then be asking your RESTful server: «Can you GET me the resource for this Session ID?».

There is no authenticated mode — REST is stateless: You create a session, you ask the server to give you resources using this Session ID as a parameter, and on logout you drop or expire the session.

Источник

php file_get_contents using post method, on port 443. On apache server error

I need help with a function I got from php.org it was called file_post_contents is was stated to work like file_get_contents, but doing post commands. The reason wanted to post was to keep a key that is sent from one web server to another private and encrypted. I know I need to connect using https on port 443 and the information needs to be sent over post and not get. The code provided is the function from php.org, hitting my server.
It gives the response:
Bad Request

Your browser sent a request that this server could not understand.
Reason: You’re speaking plain HTTP to an SSL-enabled server port.
Instead use the HTTPS scheme to access this URL, please.

Apache/2.2.8 (EL) Server at navolutions.com Port 443

So how do I correct this and send my key over encrypted to prevent data eves dropping.

 function file_post_contents($url,$headers=false)  $url = parse_url($url); if (!isset($url['port']))  if ($url['scheme'] == 'http') elseif ($url['scheme'] == 'https') > $url['query']=isset($url['query'])?$url['query']:''; $url['protocol']=$url['scheme'].'://'; $eol="\r\n"; $headers = "POST ".$url['protocol'].$url['host'].$url['path']." HTTP/1.0".$eol. "Host: ".$url['host'].$eol. "Referer: ".$url['protocol'].$url['host'].$url['path'].$eol. "Content-Type: application/x-www-form-urlencoded".$eol. "Content-Length: ".strlen($url['query']).$eol. $eol.$url['query']; $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30); if($fp)  fputs($fp, $headers); $result = ''; while(!feof($fp)) fclose($fp); if (!$headers)  //removes headers $pattern="/^.*\r\n\r\n/s"; $result=preg_replace($pattern,'',$result); > return $result; > > echo file_post_contents( "https://www.navolutions.com" ); ?> 

Источник

Оцените статью