Let's hone our skills in working with cURL. Which tokens are promising?

Hello! In this article we will discuss how to make money with tokens.

  • How much can you earn: up to 1000% per annum.
  • Is it worth it?: if you have experience working with currency.

General information about tokens

Continues to develop. Every day new projects appear that they promise their investors to replace, enter the market and earn billions. But not every one of them brings real benefits to their clients.

Tokens — alternative cryptocurrencies that provide added value. That is, they are used not only for making payments.

Tokens- these are almost all coins that are made on their own engines, and about half of those that are made on the Bitcoin engine. To become a token in the full sense of the term, you need to offer users something new that can improve business, reduce costs, etc.

Earnings from ICO

Earnings from ICOs are still not sufficiently disclosed in the Ru-segment of the Internet. In fact, this is an excellent profit opportunity for those who know how to analyze the market and know a lot about cryptocurrency. But in the long run, this will lead to a crisis in the niche.

ICO — initial placement of tokens.

There is only one way for an ordinary person to make money from an ICO - speculation. The workflow is approximately as follows:

  1. We go to the Cryptomarket website.
  2. Selecting a promising altcoin.
  3. At the PreICO stage, we buy coins at a discount of up to 10 - 50% (try to do this as early as possible).
  4. We are waiting for it to go on the stock exchange.
  5. We wait until the rate rises to a certain value (usually this is the discount amount).
  6. We sell.

This can be repeated ad infinitum: choose a new crypto coin, enter the preICO stage, buy at a discount and sell. It's just speculation, there's nothing new in it. Of course, at one point it will turn out that many of these speculators simply overheated the market, and it will burst, as happened earlier with the Dotcoms and the mortgage bond market. But who should care?

There are also alternative methods, but they are already suitable for ICO developers. This:

  • Commission for coin promotion. Teams that bring ICOs to the market take 1 - 10% of the profits per own needs— , promotion, improvement of the product. But in reality, only half of the funds are used, the rest ends up in the pockets of the team.
  • They provide intermediation services: supervise teams, analyze market prospects, insure, etc.
  • They create scams.

There are really many ways to make money from ICOs. But almost all of them are inaccessible to the average user. There is only one thing left - speculation.

Pros and cons of making money on tokens

Pros of earning money on tokens:

  • High assets.
  • Big profit.
  • Constant price changes.
  • A huge number of promising projects.

All the advantages boil down to the fact that the market is actively developing. There are many ambitious projects that could bring in a lot of money in the future. And each user has access to an exchange where you can buy an interesting token.

Minuses:

  • High risks.
  • Inability to predict earnings.
  • Lack of regulators on the market.
  • Unstable situation in legislation.

This is a market with crazy risks and a lack of regulation, which means that anyone with huge capital can collapse or inflate the rate in one move, as he pleases.

There is one more disadvantage for the Russian-speaking segment. Most information about tokens is in English: company websites, presentations, information and analysts’ opinions.

Just look at examples of foreign crypto-millionaires. They once invested money in a project that seemed nothing more than fun. Moreover, people invested small amounts, which, with growth of more than 10,000 times over the past 9 years, yielded huge profits. Many crypto millionaires simply do not know what to do with the amounts they receive. There are plenty of such examples in the foreign segment of the Internet.

Tokens are a promising, fast-growing market where you can easily and quickly (within 2-3 years) earn up to 1000% of net profit. But at the same time it is extremely risky.

Which tokens are promising?

In order to understand which tokens may be promising, let's look at 5 examples of the most popular cryptocurrencies and try to understand why they interest users.

Bitcoin- the world's first cryptocurrency. Allowed people to conduct transactions anonymously, excluding intermediaries in the form of banks and global payment systems from the “User - Money - User” scheme. A radically new approach to payments.

Ethereum improved some aspects of Bitcoin. Removed the 21 million limit on the number of issued currencies, reduced the interval between the creation of blocks and made more reliable system transaction confirmation. But this is not the most important thing. The popularity of this cryptocurrency was brought by the system of smart contracts, which completely eliminates the human factor from the chain “Conclusion of a contract - Intermediary - Verification of conditions - Execution of the contract.”

Now the role of “intermediary” is played by automated system- direct benefit for real business.

Ripple— was created entirely using its own code. Allows you to eliminate almost all links from the transaction chain. The system was initially conceived as a cost-saver for bank transfers. Allows you to reduce costs by 70%.

Litecoin- an alternative to Bitcoin, created on its code. Like many others, he uses the source code, trying in every possible way to “upgrade” the current version of the cue ball system. The most important advantage is that the number of blocks is created every 2.5 minutes versus 10 for Bitcoin. Allows you to conduct transactions faster. Resources are used to mine cryptocurrency random access memory computing machine.

Direct benefit for miners. Other resources are used to mine cryptocurrency.

Dash also written in source code Bitcoin with only one difference - the cryptocurrency has complete anonymity. In Bitcoin, you can find the owner of a wallet and track all his transactions. If you know all the final recipients, you can see the whole picture of operations. There is no such thing in the Dash cryptocurrency system: transactions are not published in open access. Even knowing the owner of the wallet, you can never find out who he sent and what he sent.

Direct benefit for anonymous payers. There is no information about transactions.

As we can see, the popularity of tokens has its own reasons. Each of these cryptocurrencies has improved life for one fundamental category. Bitcoin is for all people, Ether is for businessmen, Ripple is for banks, Litecoin is for miners, and Dash is for people who need anonymity.

Opinions on making money on tokens

Earnings on tokens reminds. They have the same features:

  • High volatility.
  • Unpredictability.
  • Dependence on world events.
  • Independence from each specific player.

But unlike real currencies, the exchange rate of which is restrained by the Central Banks of different countries, tokens have no restrictions. The only tool that influences their current rate is demand: the more people are interested in coins, the higher they will cost. One conclusion can be drawn from this:

Perhaps, tools will soon appear that will regulate the cryptocurrency market, preventing fraudulent and unpromising projects at the ICO stage. But today there are quite a lot of dummies, scammers and few truly worthwhile projects.

Cryptocurrency is an ideal tool for speculation. Rates for most top coins change every minute. And in a day you can observe both + 3-5% to the rate and - 3-5%.

Making money from investing in ICOs is very risky.

You will have to rely not on market indicators, not on charts, because they will change as soon as you refresh the page, but on intuition. You need to clearly understand whether the coin will be in demand, where it can be used, why it is needed, and whether there are alternatives.

Conclusion

Tokens remain a promising way to earn money for those who know how to work with currency. Investments, forecasts, analysis - all this is required in order to earn really large sums. Without knowledge and skills, you will not be able to earn anything in this market.

Victor Gromov launched a project called "Anti-Scam" and began writing revealing articles on fraudulent schemes and pyramids that suck money out of gullible users. Having published over a hundred reviews of scammers, the young man switched to proven ways to make money. This was his first acquaintance with the project. What seems strange is that the technique is based on the purchase and instant sale of conventional units called “tokens”. Let’s try to figure out how everything actually works here on our own, without other people’s imposed recommendations.

Anti-Scam Project by Viktor Gromov

Getting acquainted with Viktor Gromov's blog begins on the page http://antilohblog.ru/obzor-iyle-2018/#home. Please note that, apart from the advertising video for the “Token+” project, there is not a single review of the author’s previous works. A logical question arises: where are the claimed hundreds of revealing articles? Why virtual world not familiar with such a character as Viktor Gromov? Why is there not a single review of the fighter for truth outside the blog? The answers to the questions posed will not please those who decide to earn money in a couple of clicks.

We can praise the author of the blog for the published reviews. There are many of them, some even have screenshots of electronic wallets attached. Such hard work always evokes positive emotions among our website team. But! Again the question is: how did they get on the page if there is no tool to add them? The answer is obvious: the author published the entries along with the main text of the page. It is foolish to assume that comments sent by email [email protected] will appear on the blog page. The author will simply ignore them, regardless of the content of the text.

How to make money in the Token+ project?

In order to get to the Token+ project page, the user needs to click on the large green icon under the video. This action takes you to the registration page. It is a primitive form that does not require filling with real data. Several arbitrary symbols in each line, and we become the owners of a bonus from Viktor Gromov. Once in Personal Area, it is not immediately possible to understand what is here and how it works. Based on the knowledge gained from the video posted on the previous page, we are trying to activate the token. True, we don’t fully understand why this is necessary.

After making a couple of meaningless clicks and waiting a little over a minute, we learned about the accrual in the amount 1206 rubles. This amount is not enough to carry out a withdrawal operation, since the minimum threshold is set at 5,000 rubles. Accordingly, the user will have to purchase a second token, then a third... But there is one small detail that requires clarification: we purchase a virtual token unit for real money, and sell it for drawn money.

"Token+" - our reviews

Feedback from our editorial team about earnings in the Token+ project is negative. The user is asked to perform meaningless actions while using own funds. There are no instructions or rules regarding the purchase and sale of tokens. There is no clear algorithm for determining the price of a product. There is no information about the legal entity representing the project. There is no information about the activity of the resource. What is the exchange before us? trading platform? Scam! It is not difficult to verify this (though it is expensive). See below for payment request templates that will pop up one after another:

  1. Purchase of TOKEN D-SE - 600 rubles;
  2. Purchase of TOKEN B-SR – 900 rubles;
  3. Purchase of TOKEN K-RO - 1400 rubles;
  4. Purchase of TOKEN S-BI - 750 rubles;
  5. Purchase of TOKEN R-AI - 1200 rubles;
  6. Purchase of TOKEN P-YI - 800 rubles;
  7. Purchase of TOKEN Q-LC - 2100 rubles;
  8. Connection to the official TOKEN+ network - 450 rubles;
  9. Payment of commission payment system— 550 rubles;
  10. Depositing funds through a secure gateway - 890 rubles;
  11. Registration of accompanying documents to the bank - 530 rubles;
  12. Creation and registration of a digital signature - 780 rubles.

MAIN CHARACTERISTICS
earnings in the “Token+” project

Compliance of the content with what is stated on the site NO
Novelty of the material 0 out of 10
Video tutorial NO
Text guide NO
Feedback NO
Accessibility for beginners Yes
Feedback with the author after purchase NO
Affordable price Yes
Possibility of real earnings NO
Return Guarantee NO

CHECK RESULTS:

Viktor Gromov as the creator of the AntiLohotron project and the platform are two stages of one big scam. At the first level, traps are skillfully placed around the user, preparing him for possible purchases, and telling tales of fabulous profits. At the second level, they steal money fraudulently and leave you with nothing. The creator of this two-way trick is of little interest that the victims of deception are often people who are in dire need of money. He cares only about his own enrichment, even if obtained through criminal means. We recommend staying away from such schemes and only using them as a source of profit.

We ask you to be vigilant and remember visually what the above site looks like. In the future, the author may change both his name and the name of the site.

Editorial « ChecksKursov" sent an official appeal to the hosting and registrar of the above project with a request to thoroughly check for fraud and unconditionally block this address on the Internet. Don't fall for scammers!

We strongly RECOMMEND using it only to earn money on the Internet! Also don't forget to share this disclosure. V in social networks, to PROTECT YOUR FRIENDS AND LOVED ONES from this scam!


Sp-force-hide ( display: none;).sp-form ( display: block; background: rgba(255, 255, 255, 1); padding: 5px; width: 100%; max-width: 100%; border -radius: 0px; -moz-border-radius: 0px; -webkit-border-radius: 0px; font-family: "Times New Roman", Times, serif; background-repeat: no-repeat; background-position: center ; background-size: auto; border-width: 2px; border-color: rgba(255, 34, 0, 1); border-style: solid;).sp-form .sp-form-fields-wrapper ( margin: 0 auto; width: 540px;).sp-form .sp-form-control ( background: rgba(247, 244, 242, 1); border-color: #cccccc; border-style: solid; border-width: 2px ; font-size: 15px; padding-left: 8.75px; padding-right: 8.75px; border-radius: 7px; -moz-border-radius: 7px; -webkit-border-radius: 7px; height: 35px; width : 100%;).sp-form .sp-field label ( color: #444444; font-size: 15px; font-style: normal; font-weight: bold;).sp-form .sp-button ( border- radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; background-color: #ff6500; color: #ffffff; width: 100%; font-weight: 700; font-style: normal; font-family: "Segoe UI", Segoe, "Open Sans", sans-serif; border-width: 1px; border-color: #d65600; border-style: solid; box-shadow: inset 0 -2px 0 0 #c24d00; -moz-box-shadow: inset 0 -2px 0 0 #c24d00; -webkit-box-shadow: inset 0 -2px 0 0 #c24d00;).sp-form .sp-button-container ( text-align: center; width: auto;)

DO YOU WANT TO RECEIVE 500 RUBLES

EVERY MONDAY?


➤ Join our

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

token_get_all — Belirtilen kaynağı PHP dizgeciklerine ayırır

Açıklama

token_get_all (string $kaynak): array

Belirtilen kaynak dizgesi, Zend motorunun sözdizimsel tarayıcısı kullanılarak PHP dil dizgeciklerine çözümlenir.

Dizgeciklerin listesi için Çözümleyici Dizgeciklerinin Listesi sayfasına bakınız veya bir dizgecik değerini dizgesel gösterimine dönüştürmek için token_name() işlevini kullanınız.

Değiştirgeler

Çözümlenecek PHP kaynak kodu.

Dönen Değerler

Dizgecik betimleyicilerinden oluşan bir dizi. Her dizgecik betimleyicisi ya tek bir karakterden ( ; , . , > , ! gibi) oluşur ya da üç elemanlı bir diziden; 0. elemanda dizgecik indisi, 1. elemanda özgün dizgeciğin dizgesel içeriği ve 2. elemanda satır numarası bulunur.

Örnekler

Ornek 1 - token_get_all()örnekleri

$tokens = token_get_all("" );
/* => array(
array(T_OPEN_TAG, "array(T_ECHO, "echo"),
";",
array(T_CLOSE_TAG, "?>")); */

/* Aşağıdaki örnekte dizge beklendiği gibi
T_COMMENT (PHP<5"te" T_ML_COMMENT) olarak değil
T_INLINE_HTML olarak çözümlenmektedir. Bunun sebebi
sağlanan kodda hiçbir ama/kapama etiketinin bulunmayışıdır.
Bu, normal bir dosyadaetiketlerinin dışına
bir açıklama koymaya eşdeğerdir. */
$tokens = token_get_all ("/* açıklama */" );
// => array(array(T_INLINE_HTML, "/* comment */"));
?>

Sürum Bilgisi

Sürum: Açıklama
5.2.2 Satır numaraları 2. elemanda dönmeye başladı.

9 years ago

Yes, some problems (On WAMP, PHP 5.3.0) with get_token_all()

1: bug line numbers
Since PHP 5.2.2 token_get_all() should return Line numbers in element 2..
.. but for instance (5.3.0 on WAMP), it works perfectly only with PHP code (not HMTL miwed), but if you have some T_INLINE_HTML detected by token_get_all() , sometimes you find wrongs line numbers (return next line). .. :(

2: bug warning message can impact loops
Warning with php code uncompleted (ex: php code line by line) :
for example if a comment tag is not closed token_get_all() can block loops on this warning:
Warning: Unterminated comment starting line

This problem seems not to occur in CLI mod (php command line), but only in web mod.

Waiting more stability, used token_get_all() only on PHP code (not HMTL miwed) :
First extract entirely PHP code (with open et close php tag),
Second use token_get_all() on the pure PHP code.

3: Why there not function to extract PHP code (to extract HTML, we have Tidy..)?

Waiting, I used a function:

The code at end of this post:
http://www.developpez.net/forums/d786381/php/langage/
fonctions/analyser-fichier-php-token_get_all/

This function does not support:
- Old notation: "" and "<% %>"
- heredoc syntax
- nowdoc syntax (since PHP 5.3.0)

10 years ago

I wanted to use the tokenizer functions to count source lines of code, including counting comments. Attempting to do this with regular expressions does not work well because of situations where /* appears in a string, or other situations. The token_get_all() function makes this task easy by detecting all the comments properly. However, it does not tokenize newline characters. I wrote the below set of functions to also tokenize newline characters as T_NEW_LINE.

define ("T_NEW_LINE" , - 1 );

function token_get_all_nl ($source)
{
$new_tokens = array();

//Get the tokens
$tokens = token_get_all ($source);

// Split newlines into their own tokens
foreach ($tokens as $token )
{
$token_name = is_array ($token ) ? $token [ 0 ] : null ;
$token_data = is_array ($token ) ? $token [ 1 ] : $token ;

// Do not split encapsed strings or multiline comments
if ($token_name == T_CONSTANT_ENCAPSED_STRING || substr ($token_data , 0 , 2 ) == "/*" )
{
$new_tokens = array($token_name, $token_data);
continue;
}

// Split the data up by newlines
$split_data = preg_split ("#(\r\n|\n)#" , $token_data , - 1 , PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );

Foreach ($split_data as $data)
{
if ($data == "\r\n" || $data == "\n" )
{
// This is a new line token
$new_tokens = array(T_NEW_LINE, $data);
}
else
{
// Add the token under the original token name
$new_tokens = is_array ($token ) ? array($token_name, $data) : $data ;
}
}
}

Return $new_tokens ;
}

function token_name_nl ($token)
{
if ($token === T_NEW_LINE )
{
return "T_NEW_LINE" ;
}

Return token_name ($token);
}

?>

Example usage:

$tokens = token_get_all_nl(file_get_contents("somecode.php" ));

foreach ($tokens as $token )
{
if (is_array($token))
{
echo (token_name_nl ($token [ 0 ]) . ": "" . $token [ 1 ] . ""
" );
}
else
{
echo (
""" . $token . ""
" );
}
}

?>

I"m sure you can figure out how to count the lines of code, and lines of comments with these functions. This was a huge improvement on my previous attempt at counting lines of code with regular expressions. I hope this helps someone, as many of the user contributed examples on this website have helped me in the past.

10 months ago

As a caution: when using TOKEN_PARSE with an invalid php-file, one can get an error like this:
Parse error: syntax error, unexpected "__construct" (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in on line 15
Notice the missing filename as this function accepts a string, not a filename and thus has no idea of ​​the latter.
However an exception would be more appreciated.

More and more people on the Internet are trying to pass themselves off as cool bloggers, although they themselves are not such. Victor Gromov presents his project ANTILOCHOTRON on the website blog-obzor.ru. Victor is trying to convince us that he wrote many reviews of various scams, although there is nothing on his website except one video.

In this video, an unknown author talks about making money with “TOKEN+”. I took the token, activated it, received money, and withdrew it. If Viktor Gromov were really such a famous author and exposer of scams, we would know him and believe in his words.

But Viktor Gromov is a dubious and unknown person. And his way of earning money raises a lot of questions, which we began to analyze.

This is a review of the ANTILOCHOTRON project, Viktor Gromov and the TOKEN+ service. Is it a scam or a way to make good and easy money?

What is TOKEN+?

We have not seen this service before either. “TOKEN+” positions itself as a site for selling tokens, which you can immediately exchange for a random cash prize. Roughly speaking, distributing money to everyone.

If you are a reader of our blog, then you have known for a long time that money does not grow on Internet trees. Every ruble is earned with the same effort and dedication as offline. But a lot of dubious sites are trying to dissuade us from this. They say, take the money, they are giving it out here.

The ANTILOCHOTRON project is also very dubious. Where are all these articles written by Viktor Gromov? If you don’t know what a real blog for a real company looks like, you can visit ours. Only there is much more information on it than on Gromov’s website.

But still, we checked the “TOKEN+” service. Already during the registration process, doubts increased even more. No confirmation, data checking, additional protection account, etc. “TOKEN+”, judging by the information, should be a very monetary service with good functionality, but it is not.

We also checked the possibility of making money on purchased tokens. This is what the process of this dubious income looks like:

  1. Visited the site
  2. Bought tokens
  3. Activated them
  4. Withdrew the money you earned

Why then does the site blog-obzor.ru exist at all? The ANTILOCHOTRON project recommends it as the most reliable way to make money. Those. in fact, we are led to a place where money is distributed, but the same does not happen. Then why was the TOKEN+ website created?

When purchasing tokens, you pay real money, and in exchange you receive an incomprehensible internal currency of an incomprehensible service. Over time, your balance will increase to 5,000 rubles, but you will not be able to withdraw this money.

And it’s not money at all, but just numbers on the screen. After purchasing miracle tokens, you will be asked to make several more transfers under a variety of pretexts.

PURCHASE TOKEN S B.I. — 750 RUB

PURCHASE TOKEN R A.I. — 1200 RUB

PURCHASE TOKEN P YI — 800 RUB

PURCHASE TOKEN Q L.C. — 2100 RUB

Connection to the official TOKEN+ network — 450 RUB

Payment of payment system commission — 550 RUB

Depositing funds through a secure gateway — 890 RUB

And others

But even after this you will not receive the promised money. Project ANTILOCHOTRON – THE REAL SCAM and DIVORCE! Victor Gromov is an ordinary scammer advertising the TOKEN+ service. The whole point is to convince us of the veracity of the information on the blog-obzor.ru website.

In fact, Viktor Gromov never wrote reviews about fraudulent services, because... he himself is a fraud. The very idea of ​​“TOKEN+” has long been outdated, because We have already seen a lot of similar scam sites.

Friends, if you really want to make money on the Internet, go to our section with proven methods of earning money. Here you will find real working diagrams from reliable and verified authors.

Constant support service, only 100% methods. Start earning money today.

cURL is a special tool that is designed to transfer files and data using URL syntax. This technology supports many protocols such as HTTP, FTP, TELNET and many others. cURL was originally designed to be a tool command line. Luckily for us, the cURL library is supported by the language PHP programming. In this article we will look at some of the advanced functions of cURL, and also touch on the practical application of the acquired knowledge using PHP.

Why cURL?

In fact, there are many alternative ways samples of web page content. In many cases, mainly due to laziness, I used simple PHP functions instead of cURL:

$content = file_get_contents("http://www.nettuts.com"); // or $lines = file("http://www.nettuts.com"); // or readfile("http://www.nettuts.com");

However, these functions have virtually no flexibility and contain a huge number of shortcomings in terms of error handling, etc. Additionally, there are certain tasks that you simply can't accomplish with these standard features: cookie interaction, authentication, form submission, file uploads, etc.

cURL is a powerful library that supports many different protocols, options and provides detailed information O URL request Oh.

Basic structure

  • Initialization
  • Assignment of parameters
  • Execution and fetching result
  • Freeing up memory

// 1. initialization $ch = curl_init(); // 2. specify parameters, including url curl_setopt($ch, CURLOPT_URL, "http://www.nettuts.com"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); // 3. get HTML as the result $output = curl_exec($ch); // 4. close the connection curl_close($ch);

Step #2 (that is, calling curl_setopt()) will be discussed much more in this article than all other steps, because At this stage, all the most interesting and useful things that you need to know happen. In cURL there are a huge number of different options that must be specified in order to be able to configure the URL request in the most careful way. We will not consider the entire list, but will focus only on what I consider necessary and useful for this lesson. You can study everything else yourself if this topic interests you.

Error Checking

In addition, you can also use conditional statements to check the operation for success:

// ... $output = curl_exec($ch); if ($output === FALSE) ( echo "cURL Error: " . curl_error($ch); ) // ...

Here I ask you to note a very important point: we must use “=== false” for comparison, instead of “== false”. For those who are not in the know, this will help us distinguish between an empty result and a boolean value false, which will indicate an error.

Receiving the information

Another additional step is to obtain data about the cURL request after it has been executed.

// ... curl_exec($ch); $info = curl_getinfo($ch); echo "Took " . $info["total_time"] . "seconds for url". $info["url"]; //…

The returned array contains the following information:

  • "url"
  • "content_type"
  • "http_code"
  • “header_size”
  • “request_size”
  • "filetime"
  • “ssl_verify_result”
  • “redirect_count”
  • “total_time”
  • “namelookup_time”
  • “connect_time”
  • “pretransfer_time”
  • “size_upload”
  • “size_download”
  • “speed_download”
  • “speed_upload”
  • “download_content_length”
  • “upload_content_length”
  • “starttransfer_time”
  • “redirect_time”

Redirect detection depending on browser

In this first example, we will write code that can detect URL redirects based on various settings browser. For example, some websites redirect browsers cell phone, or any other device.

We're going to use the CURLOPT_HTTPHEADER option to define our outgoing HTTP headers, including the user's browser name and available languages. Eventually we will be able to determine which sites are redirecting us to different URLs.

// test the URL $urls = array("http://www.cnn.com", "http://www.mozilla.com", "http://www.facebook.com"); // testing browsers $browsers = array("standard" => array ("user_agent" => "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5 .6 (.NET CLR 3.5.30729)", "language" => "en-us,en;q=0.5"), "iphone" => array ("user_agent" => "Mozilla/5.0 (iPhone; U ; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A537a Safari/419.3", "language" => "en"), "french" => array ("user_agent" => "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; GTB6; .NET CLR 2.0.50727)", "language" => "fr,fr-FR;q=0.5")); foreach ($urls as $url) ( echo "URL: $url\n"; foreach ($browsers as $test_name => $browser) ( $ch = curl_init(); // specify the url curl_setopt($ch, CURLOPT_URL, $url); // specify headers for the browser curl_setopt($ch, CURLOPT_HTTPHEADER, array("User-Agent: ($browser["user_agent"])", "Accept-Language: ($browser["language"])" )); // we don't need the contents of the page curl_setopt($ch, CURLOPT_NOBODY, 1); // we need to get HTTP headers curl_setopt($ch, CURLOPT_HEADER, 1); // return results instead of output curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); // was there an HTTP redirect? if (preg_match("!Location: (.*)!", $output, $matches)) ( echo " $test_name: redirects to $matches\n"; ) else ( echo "$test_name: no redirection\n"; ) ) echo "\n\n"; )

First, we specify a list of URLs of sites that we will check. More precisely, we need the addresses of these sites. Next we need to define browser settings to test each of these URLs. After this, we will use a loop in which we will go through all the results obtained.

The trick we use in this example to set cURL settings will allow us to get not the content of the page, but only the HTTP headers (stored in $output). Next, using a simple regex, we can determine whether the string “Location:” was present in the received headers.

When you run this code, you should get something like the following result:

Creating a POST request to a specific URL

When forming GET request The transmitted data can be passed to the URL via a “query string”. For example, when you do a Google search, the search term is placed in the address bar of the new URL:

Http://www.google.com/search?q=ruseller

In order to simulate this request, you don't need to use cURL facilities. If laziness completely overcomes you, use the “file_get_contents()” function to get the result.

But the thing is that some HTML forms send POST requests. The data of these forms is transported through the body of the HTTP request, and not as in the previous case. For example, if you filled out a form on a forum and clicked on the search button, then most likely a POST request will be made:

Http://codeigniter.com/forums/do_search/

We can write a PHP script that can simulate this kind of URL request. First let's create a simple file to accept and display POST data. Let's call it post_output.php:

Print_r($_POST);

Then we create a PHP script to make the cURL request:

$url = "http://localhost/post_output.php"; $post_data = array ("foo" => "bar", "query" => "Nettuts", "action" => "Submit"); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // indicate that we have a POST request curl_setopt($ch, CURLOPT_POST, 1); // add variables curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); $output = curl_exec($ch); curl_close($ch); echo $output;

When you run this script you should get a result like this:

Thus, the POST request was sent to the post_output.php script, which in turn output the superglobal $_POST array, the contents of which we obtained using cURL.

Uploading a file

First, let's create a file in order to generate it and send it to the upload_output.php file:

Print_r($_FILES);

And here is the script code that performs the above functionality:

$url = "http://localhost/upload_output.php"; $post_data = array ("foo" => "bar", // file to upload "upload" => "@C:/wamp/www/test.zip"); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); $output = curl_exec($ch); curl_close($ch); echo $output;

When you want to upload a file, all you have to do is pass it as a normal post variable, preceded by an @ symbol. When you run the written script, you will get the following result:

Multiple cURL

One of the most strengths cURL is the ability to create "multiple" cURL handlers. This allows you to open a connection to multiple URLs simultaneously and asynchronously.

In the classic version of the cURL request, the execution of the script is suspended and waits for the completion of the request URL operation, after which the script can continue. If you intend to interact with a whole bunch of URLs, this will lead to quite a significant investment of time, since in the classic version you can only work with one URL at a time. However, we can correct this situation by using special handlers.

Let's look at the example code I took from php.net:

// create several cURL resources $ch1 = curl_init(); $ch2 = curl_init(); // specify the URL and other parameters curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/"); curl_setopt($ch1, CURLOPT_HEADER, 0); curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/"); curl_setopt($ch2, CURLOPT_HEADER, 0); //create a multiple cURL handler $mh = curl_multi_init(); //add several handlers curl_multi_add_handle($mh,$ch1); curl_multi_add_handle($mh,$ch2); $active = null; //execute do ( $mrc ​​= curl_multi_exec($mh, $active); ) while ($mrc == CURLM_CALL_MULTI_PERFORM); while ($active && $mrc ​​== CURLM_OK) ( if (curl_multi_select($mh) != -1) ( do ( $mrc ​​= curl_multi_exec($mh, $active); ) while ($mrc == CURLM_CALL_MULTI_PERFORM); ) ) //closing curl_multi_remove_handle($mh, $ch1); curl_multi_remove_handle($mh, $ch2); curl_multi_close($mh);

The idea is that you can use multiple cURL handlers. Using a simple loop, you can keep track of which requests have not yet completed.

There are two main loops in this example. The first do-while loop calls curl_multi_exec(). This function is not blockable. It runs as fast as it can and returns the status of the request. As long as the returned value is the constant 'CURLM_CALL_MULTI_PERFORM', this means that the work has not yet completed (for example, in this moment HTTP headers are sent to the URL); That's why we keep checking this return value until we get a different result.

In the next loop we check the condition while the variable $active = "true". It is the second parameter to the curl_multi_exec() function. The value of this variable will be "true" as long as any of the existing changes are active. Next we call the curl_multi_select() function. Its execution is "blocked" while there is at least one active connection, until a response is received. When this happens, we return to the main loop to continue executing queries.

Now let's apply what we have learned to an example that will be really useful for large quantity of people.

Checking links in WordPress

Imagine a blog with a huge number of posts and messages, each of which contains links to external Internet resources. Some of these links might already be dead for various reasons. The page may have been deleted or the site may not be working at all.

We are going to create a script that will analyze all links and find non-loading websites and 404 pages, and then provide us with a detailed report.

Let me say right away that this is not an example of creating a plugin for WordPress. This is absolutely a good testing ground for our tests.

Let's finally begin. First we need to fetch all the links from the database:

// configuration $db_host = "localhost"; $db_user = "root"; $db_pass = ""; $db_name = "wordpress"; $excluded_domains = array("localhost", "www.mydomain.com"); $max_connections = 10; // initialization of variables $url_list = array(); $working_urls = array(); $dead_urls = array(); $not_found_urls = array(); $active = null; // connect to MySQL if (!mysql_connect($db_host, $db_user, $db_pass)) ( die("Could not connect: " . mysql_error()); ) if (!mysql_select_db($db_name)) ( die("Could not select db: " . mysql_error()); ) // select all published posts that have links $q = "SELECT post_content FROM wp_posts WHERE post_content LIKE "%href=%" AND post_status = "publish" AND post_type = "post ""; $r = mysql_query($q) or die(mysql_error()); while ($d = mysql_fetch_assoc($r)) ( // fetch links using regular expressions if (preg_match_all("!href=\"(.*?)\"!", $d["post_content"], $matches)) ( foreach ($matches as $url) ( $tmp = parse_url($url) ; if (in_array($tmp["host"], $excluded_domains)) ( continue; ) $url_list = $url; ) ) ) // remove duplicates $url_list = array_values(array_unique($url_list)); if (!$url_list) ( die("No URL to check"); )

First, we generate configuration data for interaction with the database, then we write a list of domains that will not participate in the check ($excluded_domains). We also define a number characterizing the number of maximum simultaneous connections that we will use in our script ($max_connections). We then join the database, select the posts that contain links, and accumulate them into an array ($url_list).

The following code is a bit complicated, so walk through it from start to finish:

// 1. multiple handler $mh = curl_multi_init(); // 2. add a set of URLs for ($i = 0; $i< $max_connections; $i++) { add_url_to_multi_handle($mh, $url_list); } // 3. инициализация выполнения do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); // 4. основной цикл while ($active && $mrc == CURLM_OK) { // 5. если всё прошло успешно if (curl_multi_select($mh) != -1) { // 6. делаем дело do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); // 7. если есть инфа? if ($mhinfo = curl_multi_info_read($mh)) { // это значит, что запрос завершился // 8. извлекаем инфу $chinfo = curl_getinfo($mhinfo["handle"]); // 9. мёртвая ссылка? if (!$chinfo["http_code"]) { $dead_urls = $chinfo["url"]; // 10. 404? } else if ($chinfo["http_code"] == 404) { $not_found_urls = $chinfo["url"]; // 11. рабочая } else { $working_urls = $chinfo["url"]; } // 12. чистим за собой curl_multi_remove_handle($mh, $mhinfo["handle"]); // в случае зацикливания, закомментируйте данный вызов curl_close($mhinfo["handle"]); // 13. добавляем новый url и продолжаем работу if (add_url_to_multi_handle($mh, $url_list)) { do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); } } } } // 14. завершение curl_multi_close($mh); echo "==Dead URLs==\n"; echo implode("\n",$dead_urls) . "\n\n"; echo "==404 URLs==\n"; echo implode("\n",$not_found_urls) . "\n\n"; echo "==Working URLs==\n"; echo implode("\n",$working_urls); function add_url_to_multi_handle($mh, $url_list) { static $index = 0; // если у нас есть ещё url, которые нужно достать if ($url_list[$index]) { // новый curl обработчик $ch = curl_init(); // указываем url curl_setopt($ch, CURLOPT_URL, $url_list[$index]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_NOBODY, 1); curl_multi_add_handle($mh, $ch); // переходим на следующий url $index++; return true; } else { // добавление новых URL завершено return false; } }

Here I will try to explain everything in detail. The numbers in the list correspond to the numbers in the comment.

  1. 1. Create a multiple handler;
  2. 2. We will write the add_url_to_multi_handle() function a little later. Each time it is called, processing of a new url will begin. Initially, we add 10 ($max_connections) URLs;
  3. 3. To get started, we must run the curl_multi_exec() function. As long as it returns CURLM_CALL_MULTI_PERFORM, we still have something to do. We need this mainly to create connections;
  4. 4. Next comes the main loop, which will run as long as we have at least one active connection;
  5. 5. curl_multi_select() hangs waiting for the URL search to complete;
  6. 6. Once again, we need to get cURL to do some work, namely fetch the return response data;
  7. 7. Information is verified here. As a result of executing the request, an array will be returned;
  8. 8. The returned array contains a cURL handler. We will use it to select information about a separate cURL request;
  9. 9. If the link was dead, or the script timed out, then we should not look for any http code;
  10. 10. If the link returned us a 404 page, then the http code will contain the value 404;
  11. 11. B otherwise, we have a working link in front of us. (You can add additional checks for error code 500, etc...);
  12. 12. Next we remove the cURL handler because we no longer need it;
  13. 13. Now we can add another url and run everything we talked about before;
  14. 14. At this step, the script completes its work. We can remove everything we don’t need and generate a report;
  15. 15. Finally, we will write a function that will add the url to the handler. The static variable $index will be incremented every time this function will be called.

I used this script on my blog (with some broken links that I added on purpose to test it) and got the following result:

In my case, the script took a little less than 2 seconds to crawl through 40 URLs. The increase in productivity is significant when working with more big amount URL addresses. If you open ten connections at the same time, the script can execute ten times faster.

A few words about other useful cURL options

HTTP Authentication

If the URL has HTTP authentication, then you can easily use the following script:

$url = "http://www.somesite.com/members/"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // specify the username and password curl_setopt($ch, CURLOPT_USERPWD, "myusername:mypassword"); // if redirection is allowed curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // then save our data in cURL curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, 1); $output = curl_exec($ch); curl_close($ch);

FTP upload

PHP also has a library for working with FTP, but nothing prevents you from using cURL tools here:

// open the file $file = fopen("/path/to/file", "r"); // the url should contain the following content $url = "ftp://username: [email protected]:21/path/to/new/file"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_UPLOAD, 1); curl_setopt($ch, CURLOPT_INFILE, $fp); curl_setopt($ch, CURLOPT_INFILESIZE, filesize("/path/to/file")); // specify the ASCII mod curl_setopt($ch, CURLOPT_FTPASCII, 1); $output = curl_exec ($ch); curl_close($ch);

Using Proxy

You can perform your URL request through a proxy:

$ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"http://www.example.com"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // specify the address curl_setopt($ch, CURLOPT_PROXY, "11.11.11.11:8080"); // if you need to provide a username and password curl_setopt($ch, CURLOPT_PROXYUSERPWD,"user:pass"); $output = curl_exec($ch); curl_close($ch);

Callback functions

It is also possible to specify a function that will be triggered even before the cURL request completes. For example, while the response content is loading, you can start using the data without waiting for it to fully load.

$ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"http://net.tutsplus.com"); curl_setopt($ch, CURLOPT_WRITEFUNCTION,"progress_function"); curl_exec($ch); curl_close($ch); function progress_function($ch,$str) ( echo $str; return strlen($str); )

A function like this MUST return the length of the string, which is a requirement.

Conclusion

Today we learned how you can use the cURL library for your own selfish purposes. I hope you enjoyed this article.

Thank you! Have a good day!

Internet