Php get code from url

Get Query String from URL in php

To get the query string from a URL in php, you can use $_GET super global to get specific key value pairs or $_SERVER super global to get the entire string.

// http://theprogrammingexpert.com/?key1=value1&key2=value2&key3=value3 echo $_GET['key1']; echo $_GET['key2']; echo $_SERVER['QUERY_STRING']; //Output: value1 value2 key1=value1&key2=value2&key3=value3

A query string is a part of a URL that assigns values to specified parameters. When building web pages, query strings help us pass and access information to be used on our web pages.

When working in php, the ability to easily access and work with query strings is important.

To get a query string from a URL, there are a few different ways you can get the key value pairs.

To get a specific parameter from a query string, you can use $_GET super global to access individual parameters from the query string by name.

// http://theprogrammingexpert.com/?key1=value1&key2=value2&key3=value3 echo $_GET['key1']; //Output: value1

If you want to get the entire query string, you can use the $_SERVER super global.

// http://theprogrammingexpert.com/?key1=value1&key2=value2&key3=value3 echo $_SERVER['QUERY_STRING']; //Output: key1=value1&key2=value2&key3=value3

After getting the entire query string, you can parse it for the key value pairs with the php parse_str() function.

Using $_GET to Get Query String Parameters in php

The $_GET super global variable allows us to get individual key value pairs from query strings.

There are a few additional cases which occur when using query strings that I want to share with you.

First, in a query string, you can have duplicate key names followed by square brackets. This will create a child array in $_GET for that key with numerically indexed values.

// http://theprogrammingexpert.com/?key[]=value1&key[]=value2&key[]=value3 echo $_GET['key'][0]; echo $_GET['key'][1]; echo $_GET['key'][2]; //Output: value1 value2 value3

If the brackets are not empty, and have keys in them, then for a particular key, the child array belonging to the key will be an associative array.

// http://theprogrammingexpert.com/?key[ex1]=value1&key[ex2]=value2&key[ex3]=value3 echo $_GET['key']['ex1']; echo $_GET['key']['ex2']; echo $_GET['key']['ex3']; //Output: value1 value2 value3

Using $_SERVER to Get Query String in php

You can also use the $_SERVER super global variable to get the entire query string. After getting the query string, you can parse it with the php parse_str() function.

// http://theprogrammingexpert.com/?key1=value1&key2=value2&key3=value3 query_string = $_SERVER['QUERY_STRING']; parse_str(query_string); echo $key1; echo $key2; echo $key3; //Output: value1 value2 value3

Hopefully this article has been useful for you to learn how to get query strings and work with them in php.

Читайте также:  Html image or figure
  • 1. php e – Using M_E and exp() Function to Get Euler’s Constant e
  • 2. php range() – Create Array of Elements Within Given Range
  • 3. php is_float() Function – Check if Variable is Float in php
  • 4. php array_key_exists() Function – Check if Key Exists in Array
  • 5. In PHP isset Method is Used For Checking if Variable is Defined
  • 6. php Square Root with sqrt Function
  • 7. php session_destroy() – Delete Session File Where Session Data is Stored
  • 8. php array_walk() – Modify Elements in Array with Callback Function
  • 9. Capitalize First Letter of String with php ucfirst() Function
  • 10. preg_replace php – Use Regex to Search and Replace

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Источник

PHP – Get HTTP Response Status Code From a URL

This post shows you how to get the HTTP response status code from a URL. To do this, we will use get_headers built-in function, which returns an array with the headers in the HTTP response.

1. Exploring get_headers function

Let’s create a test to check what response headers we will get.

$url = 'https://bytenota.com'; $responseHeaders = get_headers($url, 1); print_r($responseHeaders); 
Array ( [0] => HTTP/1.0 200 OK [Content-Type] => text/html; charset=UTF-8 [Link] => ; rel="https://api.w.org/" [Date] => Tue, 19 Jun 2018 07:42:10 GMT [Accept-Ranges] => bytes [Server] => LiteSpeed [Alt-Svc] => quic=":443"; ma=2592000; v="35,37,38,39" [Connection] => close ) 

As you can see in the result, the HTTP response status code is in the first index value of the array ( HTTP/1.0 200 OK ).

The response status code can be:

  • HTTP/1.0 200 OK:
  • HTTP/1.0 301 Moved Permanently
  • HTTP/1.0 400 Bad Request
  • HTTP/1.0 404 Not Found
  • ect.

You can find the full list of response status code on this page.

2. Implementation

function getHTTPResponseStatusCode($url) < $status = null; $headers = @get_headers($url, 1); if (is_array($headers)) < $status = substr($headers[0], 9); >return $status; > 

In the above code, we have implemented the function that returns an HTTP response status code only from given URL, i.e. we have removed HTTP/1.0 string in the first index value of the array.

3. Usage

The below are two examples showing how to use the implemented function.

$url = 'https://bytenota.com'; $statusCode = getHTTPResponseStatusCode($url); echo $statusCode; 
$url = 'https://google.com/this-is-a-test'; $statusCode = getHTTPResponseStatusCode($url); echo $statusCode; 

Источник

Php php get html from url code example

: Solution 3: Solution: the simplest solution in those cases would be using (untested code, but should work): Solution: If you want to get the HTML source code of an URL, you can use cURL : more info here cUrl — getting the html response body and here php: Get html source code with cURL Solution 1: Try with this, see more options at here Solution 2: If you know, and trust, the source, and the source will always be the same site, then don’t put it through strict SSL verification.

Читайте также:  Find error in html page

Get HTML content from a given HTTPS url

$url = 'https://www.example.com/abc'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Blindly accept the certificate curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // decode response curl_setopt($ch, CURLOPT_ENCODING, true); $response = curl_exec($ch); curl_close($ch); var_dump($response); 
http://php.net/manual/en/function.curl-setopt.php 

If you know, and trust, the source, and the source will always be the same site, then don’t put it through strict SSL verification.

This is from another SO answer, PHP’s cURL: How to connect over HTTPS? :

$url = 'https://www.example.com/abc'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Blindly accept the certificate curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $response = curl_exec($ch); curl_close($ch); var_dump($response); 
function nget($url) < $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_REFERER, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($curl, CURLOPT_POST, FALSE); curl_setopt($curl, CURLOPT_HEADER, TRUE); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE); curl_setopt($curl, CURLOPT_FAILONERROR, TRUE); curl_setopt($curl, CURLOPT_ENCODING, TRUE); curl_setopt($curl, CURLOPT_COOKIEJAR, 'cookie.txt'); curl_setopt($curl, CURLOPT_COOKIEFILE, 'cookie.txt'); curl_setopt($curl, CURLOPT_HTTPHEADER, ['text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9']); curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'); $content = curl_exec($curl); curl_close($curl); return $content; >$url = 'https://example.com'; $m = nget($url); var_dump($m); 

Getting data from the URL in PHP?, It’s not clear whether you’re talking about finding the value of page from within the PHP page handling that URL, or if you have a string containing the URL and you want to parse the page parameter.. If you’re talking about accessing query string parameters from within products.php, you can use the super-global …

Get Text From URL in PHP

the simplest solution in those cases would be using (untested code, but should work):

Get url content PHP, Browse other questions tagged php url curl file-get-contents or ask your own question. The Overflow Blog Great engineering cultures are built on social learning communities

How to get websites source code in to webpage as result using PHP

If you want to get the HTML source code of an URL, you can use cURL :

more info here cUrl — getting the html response body and here php: Get html source code with cURL

How to Get Parameters from a URL String with PHP, Using the parse_url() and the parse_str Functions. This function is aimed at returning the URL components by parsing the URL. So, it parses the URL, returning an associative array that encompasses different components. The syntax of the parse_url() function is as follows:

Источник

Simple Ways of Getting Data from URL in PHP (Web Scraping)

When you need to get data / content from a certain website url (ie. for scrapping, data fetching, or something like that). There are 2 simple ways you can use. By using built-in php function file_get_contents() and using cURL library.

Читайте также:  Log type in java

file_get_contents is so far the most simple way of getting data, but it lacks options if compared to cURL library. So decide wisely which method suits your need. If you just need to get a website content, then file_get_contents is the best choice. But if you need to do something more, like setting user agent, timeout, response type, error handling, or to access HTTPS URLs. cURL is the most capable.

Get Content from URL using PHP file_get_contents()

Getting data using file_get_contens() is as simple as :

 $url="http://example.com"; $data=file_get_contents($url); echo $data; ?> 

It basically fetch anything from given address, whether it’s a URL, or a file path. But for real-world implementation, every tcp connection does need some time to finish the request. In this case, the script would wait until the request processes finished (sending request, waiting, getting data) then continue the execution. If the connection is somehow failed, the script will keep continue so you will need to handle every possible outcome from the connection.

Get Content from URL using PHP DOMDocument class

Another way to fetch a web content in PHP is to use PHP DOMDocument class. In this method, we can directly process the retrieved document by DOM. The downside is, the content is only limited to HTML / XML. Usually, DOMDocument is already bundled in php so you don’t have to install anything.
Using DOMDocument is as simple as :

 $dom = new DOMDocument(); libxml_use_internal_errors(true); $dom->loadHTMLFile('http://example.com/'); $data = $dom->getElementById("banner"); echo $data->nodeValue."\n" ?> 

First, create a new DOMDocument object by
$dom = new DOMDocument();

Then load the HTML File using loadHTMLFile method with url as parameter.
$dom->loadHTMLFile(‘http://example.com/’);

Finally, access the DOM (you can read the docs here)
$dom->getElementById(«elementId»);

In real world, not ALL html document is well formed. Whether it’s an unclosed tags, mismatch brackets, malformed attribute-value pair, etc. Those will raise confuse DOMDocument causing it to throw an exception. To avoid that, we need to set
libxml_use_internal_errors(true);
to suppress libxml’s internal errors.

Get Content from URL using PHPQuery class

If you are familiar with how jquery works, this method is the best for you. This class library is originally created by Tobiasz Cudnik. This class implement css3 selector based on jquery javascript library.
By using PHPQuery class you can do something like:
$doc[‘ul > li’] ->addClass(‘active-list’);
Feels familiar?

You can find more example here.

Beside those three above, there are many more alternatives methods to acquire data from webpages in PHP. IMHO, those three above is the best ways i am already familiar with.

Источник

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