问题
<?php
$a="https://sayat.me/chitmarike";
$html=file_get_contents("$a");
$headers = get_headers($a);
preg_match('~id="bar" value="([^"]*)"~', $html, $img);
$img1 = $img[1];
echo $img1;
preg_match('/(?<=csam=).*?(?=;)/', $headers, $cook);
$cook1 = $cook[1];
echo $cook1;
?>
I want to extract the value of csam
from the cookie header.
This is what it looks like:
Array
(
[0] => HTTP/1.1 200 OK
[1] => Date: Fri, 07 Apr 2017 19:05:03 GMT
[2] => Content-Type: text/html; charset=UTF-8
[3] => Connection: close
[4] => Set-Cookie: __cfduid=d6dea25f00686a7cef5f0a3d21195207c1491599902; expires=Sat, 07-Apr-18 19:05:23 GMT; path=/; domain=.sayat.me; HttpOnly
[5] => Set-Cookie: PHPSESSID=m3hvgquu2vtcp9ingqmkttqgs2; path=/
[6] => Expires: Thu, 19 Nov 1981 08:52:00 GMT
[7] => Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
[8] => Pragma: no-cache
[9] => Set-Cookie: csam=5844bc1d44; expires=Fri, 07-Apr-2017 19:35:36 GMT; Max-Age=1800; path=/
[10] => X-CSRF-Protection: SAM v2.0
[11] => Set-Cookie: country=IN; expires=Sun, 07-May-2017 19:05:36 GMT; Max-Age=2592000; path=/
[12] => Vary: Accept-Encoding
[13] => McID: sam-web4
[14] => Server: cloudflare-nginx
[15] => CF-RAY: 34bf420dae9069fb-LHR
)
But i am getting this error
Warning: preg_match() expects parameter 2 to be string, array given in C:\xampp\htdocs\sayat\index.php on line 9
What am i doing wrong?
回答1:
Spending time to read and well understand an error message isn't wasted time. Error messages are simple and clear: preg_match() expects parameter 2 to be string, array given
. Conclusion, in: preg_match('/(?<=csam=).*?(?=;)/', $headers, $cook);
, $headers
is an array when preg_match expects the subject (the second parameter) to be a string, nothing more, nothing less.
Problem, $headers
is filled by get_headers that returns an array. Two possible ways to solve the problem:
- implode the array and search the resulting string with your pattern or rewrite it like this:
/csam=\K[^;]+/
- set the second parameter of
get_headers
to 1 and use the array structure to find the information you want:
Example:
$a="https://sayat.me/chitmarike";
$headers = get_headers($a, 1);
foreach ($headers['Set-Cookie'] as $v) {
if ( strpos($v, 'csam=') === 0 ) {
$cook = substr($v, 5, strpos($v, ';') - 5);
break;
}
}
回答2:
Function get_headers returns an array, but preg_match requires a string, as it is said in the error.
Concatenate the result of get_headers
before calling preg_match
.
来源:https://stackoverflow.com/questions/43286664/preg-match-expects-parameter-2-to-be-string-array-given-not-working