Skip to content

Instantly share code, notes, and snippets.

@alash3al
Last active February 23, 2023 18:13
Show Gist options
  • Save alash3al/aafe8ffa0a6ca12eb35f to your computer and use it in GitHub Desktop.
Save alash3al/aafe8ffa0a6ca12eb35f to your computer and use it in GitHub Desktop.
wget() in PHP, no more curl, just one line call
<?php
/**
* wget just like linux wget command
*
* @author Mohammed Al Ashaal <is.gd/alash3al>
* @version 1.0.0
* @license MIT License
*
* @param string $url example 'http://site.com/xxx?k=v'
* @param string $method example 'GET'
* @param array $headers example array( 'Cookie: k1=v1; k2=v2' )
* @param string $body only if the $methd is not GET
*
* @return array "success" | string "failur"
*/
function wget($url, $method = 'GET', array $headers = array(), $body = '')
{
// prevent timeout
set_time_limit(0);
// get the url components
$url = (object) array_merge(array(
'scheme' => '',
'host' => '',
'port' => 80,
'path' => '/',
'query' => ''
), parse_url($url));
if ( empty($url->host) ) {
$url->host = $url->path;
$url->path = '/';
}
// open socket connection
$socket = fsockopen($url->host, $url->port, $errno, $errstr, 30);
// if there is any error
// exit and print its string
if ( $errno )
return $errstr;
// generate the headers
$headers = array_merge(array
(
sprintf('%s %s?%s HTTP/1.1', strtoupper($method), $url->path, $url->query),
sprintf('Host: %s', $url->host),
'Connection: Close'
), $headers);
// coninue for non-get methods
if ( strtolower($method) !== 'get' )
{
$headers[] = sprintf('Content-Length: %s', strlen($body));
$headers[] = '';
$headers[] = '';
$headers[] = $body;
}
else $headers[] = '';
$headers = join(PHP_EOL, $headers) . PHP_EOL;
// write the headers to the target
fwrite($socket, $headers);
// headers and body from the server
$headers = ''; $body = '';
// generating the headers and the body
if ( ($pos = strpos($response = stream_get_contents($socket), PHP_EOL . PHP_EOL)) !== FALSE ) {
$headers = substr($response, 0, $pos);
$body = substr($response, $pos + 1);
} else $headers = $response;
// close the socket connection
fclose($socket);
// return the result
return array( 'headers' => trim($headers), 'body' => trim($body) );
}
// -------------------
// example:
var_dump(wget('google.com', 'POST', array(), 'xx,cc.vv'));
@mbrughi
Copy link

mbrughi commented Feb 8, 2023

Hi,
with openbasedir restriction in effect return an error:

301 Moved Permanently

Do you have a solution?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment