- HTTP context options
- Examples
- Notes
- See Also
- User Contributed Notes 10 notes
- Saved searches
- Use saved searches to filter your results more quickly
- License
- schmittjoh/php-option
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
HTTP context options
GET , POST , or any other HTTP method supported by the remote server.
Defaults to GET .
Additional headers to be sent during request. Values in this option will override other values (such as User-agent: , Host: , and Authentication: ), even when following Location: redirects. Thus it is not recommended to set a Host: header, if follow_location is enabled.
Value to send with User-Agent: header. This value will only be used if user-agent is not specified in the header context option above.
By default the user_agent php.ini setting is used.
Additional data to be sent after the headers. Typically used with POST or PUT requests.
URI specifying address of proxy server. (e.g. tcp://proxy.example.com:5100 ).
When set to true , the entire URI will be used when constructing the request. (e.g. GET http://www.example.com/path/to/file.html HTTP/1.0 ). While this is a non-standard request format, some proxy servers require it.
Defaults to false .
Follow Location header redirects. Set to 0 to disable.
The max number of redirects to follow. Value 1 or less means that no redirects are followed.
Defaults to 1.1 as of PHP 8.0.0; prior to that version the default was 1.0 .
Read timeout in seconds, specified by a float (e.g. 10.5 ).
By default the default_socket_timeout php.ini setting is used.
Fetch the content even on failure status codes.
Defaults to false .
Examples
Example #1 Fetch a page and send POST data
$postdata = http_build_query (
array(
‘var1’ => ‘some content’ ,
‘var2’ => ‘doh’
)
);
$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 ( ‘http://example.com/submit.php’ , false , $context );
Example #2 Ignore redirects but fetch headers and content
$opts = array( ‘http’ =>
array(
‘method’ => ‘GET’ ,
‘max_redirects’ => ‘0’ ,
‘ignore_errors’ => ‘1’
)
);
$context = stream_context_create ( $opts );
$stream = fopen ( $url , ‘r’ , false , $context );
// header information as well as meta data
// about the stream
var_dump ( stream_get_meta_data ( $stream ));
// actual data at $url
var_dump ( stream_get_contents ( $stream ));
fclose ( $stream );
?>
Notes
Note: Underlying socket stream context options
Additional context options may be supported by the underlying transport For http:// streams, refer to context options for the tcp:// transport. For https:// streams, refer to context options for the ssl:// transport.
Note: HTTP status line
When this stream wrapper follows a redirect, the wrapper_data returned by stream_get_meta_data() might not necessarily contain the HTTP status line that actually applies to the content data at index 0 .
array ( 'wrapper_data' => array ( 0 => 'HTTP/1.0 301 Moved Permanently', 1 => 'Cache-Control: no-cache', 2 => 'Connection: close', 3 => 'Location: http://example.com/foo.jpg', 4 => 'HTTP/1.1 200 OK', .
The first request returned a 301 (permanent redirect), so the stream wrapper automatically followed the redirect to get a 200 response (index = 4 ).
See Also
User Contributed Notes 10 notes
Note that if you set the protocol_version option to 1.1 and the server you are requesting from is configured to use keep-alive connections, the function (fopen, file_get_contents, etc.) will «be slow» and take a long time to complete. This is a feature of the HTTP 1.1 protocol you are unlikely to use with stream contexts in PHP.
Simply add a «Connection: close» header to the request to eliminate the keep-alive timeout:
// php 5.4 : array syntax and header option with array value
$data = file_get_contents ( ‘http://www.example.com/’ , null , stream_context_create ([
‘http’ => [
‘protocol_version’ => 1.1 ,
‘header’ => [
‘Connection: close’ ,
],
],
]));
?>
note that both http and https transports require the same context name http
// OK example:
// this will work as expected
// note the url with https but context with http
$correct_data = file_get_contents(‘https://example.com’, false, stream_context_create(array(‘http’ => array(. ))));
// INVALID example:
// this will not work, the context will be ignored
// note the url with https also context with https
$correct_data = file_get_contents(‘https://example.com’, false, stream_context_create(array(‘https’ => array(. ))));
note that for both http and https protocols require the same ‘http’ context keyword:
// CORRECT example:
// this will work as expected
// note the url with https but context with http
$correct_data = file_get_contents ( ‘https://example.com’ , false , stream_context_create (array( ‘http’ => array(. ))));
// INVALID example:
// this will not work, the context will be ignored
// note the url with https also context with https
$correct_data = file_get_contents ( ‘https://example.com’ , false , stream_context_create (array( ‘https’ => array(. ))));
watch your case when using methods (POST and GET). it must be always uppercase. in case of you write it in lower case it wont work.
Note that setting request_fulluri to true will *change* the value of $_SERVER[‘REQUEST_URI] on the receiving end (from /abc.php to http://domain.com/abc.php).
If you want to use Basic Auth while using get_headers(), use stream_context options below.
I am using HEAD method here, but please feel free to use GET also.
$targetUrl = ‘http or https target url here’ ;
$basicAuth = base64_encode ( ‘username:password’ );
stream_context_set_default (
[
‘http’ => [
‘method’ => ‘HEAD’ ,
‘header’ => ‘Authorization: Basic ‘ . $basicAuth
]
]);
$result = get_headers ( $targetUrl );
If you use the proxy server and encounter an error «fopen(http://example.com): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request» note that in many situations you need also set the parameter «request_fulluri» to «true» in your stream options. Without this option the php script sends the empty request to the server as «GET / HTTP/0.0» and the proxy server replies to it with the «HTTP 400» error.
For example (working sample):
$stream = stream_context_create (Array( «http» => Array( «method» => «GET» ,
«timeout» => 20 ,
«header» => «User-agent: Myagent» ,
«proxy» => «tcp://my-proxy.localnet:3128» ,
‘request_fulluri’ => True /* without this option we get an HTTP error! */
)));
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
License
schmittjoh/php-option
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
This package implements the Option type for PHP!
The Option type is intended for cases where you sometimes might return a value (typically an object), and sometimes you might return a base value (typically null) depending on arguments, or other runtime factors.
Often times, you forget to handle the case where a base value should be returned. Not intentionally of course, but maybe you did not account for all possible states of the system; or maybe you indeed covered all cases, then time goes on, code is refactored, some of these your checks might become invalid, or incomplete. Suddenly, without noticing, the base value case is not handled anymore. As a result, you might sometimes get fatal PHP errors telling you that you called a method on a non-object; users might see blank pages, or worse.
On one hand, the Option type forces a developer to consciously think about both cases (returning a value, or returning a base value). That in itself will already make your code more robust. On the other hand, the Option type also allows the API developer to provide more concise API methods, and empowers the API user in how he consumes these methods.
Installation is super-easy via Composer:
$ composer require phpoption/phpoption
or add it by hand to your composer.json file.
Using the Option Type in your API
class MyRepository < public function findSomeEntity($criteria): \PhpOption\Option < if (null !== $entity = $this->em->find(. )) < return new \PhpOption\Some($entity); > // We use a singleton, for the None case. return \PhpOption\None::create(); > >
If you are consuming an existing library, you can also use a shorter version which by default treats null as None , and everything else as Some case:
class MyRepository < public function findSomeEntity($criteria): \PhpOption\Option < return \PhpOption\Option::fromValue($this->em->find(. )); // or, if you want to change the none value to false for example: return \PhpOption\Option::fromValue($this->em->find(. ), false); > >
Case 1: You always Require an Entity in Calling Code
$entity = $repo->findSomeEntity(. )->get(); // returns entity, or throws exception
Case 2: Fallback to Default Value If Not Available
$entity = $repo->findSomeEntity(. )->getOrElse(new Entity()); // Or, if you want to lazily create the entity. $entity = $repo->findSomeEntity(. )->getOrCall(function() < return new Entity(); >);
No More Boiler Plate Code
// Before $entity = $this->findSomeEntity(); if (null === $entity) < throw new NotFoundException(); > echo $entity->name; // After echo $this->findSomeEntity()->get()->name;
No More Control Flow Exceptions
// Before try < $entity = $this->findSomeEntity(); > catch (NotFoundException $ex) < $entity = new Entity(); > // After $entity = $this->findSomeEntity()->getOrElse(new Entity());
More Concise Null Handling
// Before $entity = $this->findSomeEntity(); if (null === $entity) < return new Entity(); > return $entity; // After return $this->findSomeEntity()->getOrElse(new Entity());
Trying Multiple Alternative Options
If you’d like to try multiple alternatives, the orElse method allows you to do this very elegantly:
return $this->findSomeEntity() ->orElse($this->findSomeOtherEntity()) ->orElse($this->createEntity());
The first option which is non-empty will be returned. This is especially useful with lazy-evaluated options, see below.
The above example has the flaw that we would need to evaluate all options when the method is called which creates unnecessary overhead if the first option is already non-empty.
Fortunately, we can easily solve this by using the LazyOption class:
return $this->findSomeEntity() ->orElse(new LazyOption(array($this, 'findSomeOtherEntity'))) ->orElse(new LazyOption(array($this, 'createEntity')));
This way, only the options that are necessary will actually be evaluated.
Of course, performance is important. Attached is a performance benchmark which you can run on a machine of your choosing. The overhead incurred by the Option type comes down to the time that it takes to create one object, our wrapper, and one additional method call to retrieve the value from the wrapper. Unless you plan to call a method thousands of times during a request, there is no reason to stick to the object|null return value; better give your code some options!
If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. You may view our full security policy here.
PHP Option Type is licensed under Apache License 2.0.
Available as part of the Tidelift Subscription
The maintainers of phpoption/phpoption and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.