What i'm trying to achieve is this:
1st- I want to query a page like google but without filling it's search filed manually
2nd- I want to get the result and save it to a database
I saw an example of doing this with C# here
http://www.farooqazam.net/c-sharp-auto-click-button-and-auto-fill-form/comment-page-1/#comment-27256
but i'd like to do it with php, can you help me please?
Thanks
You should use cURL to do so, not only because it is way faster than file_get_contents, but also because it has many more features. Another reason to use it is that, as Xeoncross correctly mentioned in the comments, file_get_contents may be disabled by your webhost for security reasons.
A basic example would be this one:
$curl_handle = curl_init();
curl_setopt( $curl_handle, CURLOPT_URL, 'http://example.com' );
curl_exec( $curl_handle ); // Execute the request
curl_close( $curl_handle );
If you need the return data from the request, you need to specify the CURLOPT_RETURNTRANSFER option:
$curl_handle = curl_init();
curl_setopt( $curl_handle, CURLOPT_URL, 'http://example.com' );
curl_setopt( $curl_handle, CURLOPT_RETURNTRANSFER, true ); // Fetch the contents too
$html = curl_exec( $curl_handle ); // Execute the request
curl_close( $curl_handle );
There are tons of cURL options, for example, you can set a request timeout:
curl_setopt( $curl_handle, CURLOPT_CONNECTTIMEOUT, 2 ); // 2 second timeout
For a reference of all options see the curl_setopt() reference.
$html = file_get_contents('http://example.com');
is the simplest version you'll get.
<?php
$r = new HttpRequest('http://example.com/feed.rss', HttpRequest::METH_GET);
$r->setOptions(array('lastmodified' => filemtime('local.rss')));
$r->addQueryData(array('category' => 3));
try {
$r->send();
if ($r->getResponseCode() == 200) {
file_put_contents('local.rss', $r->getResponseBody());
}
} catch (HttpException $ex) {
echo $ex;
}
?>
From the php manual...
You can use PHP CUrl, for detailed manupulations with the site you access!
you can even perform get and posts on the site you access, or use services from different sites (in case the site provides services!).
If you find the name of the field (q) you want to fill on the remote page (Google), you can fill it by using GET syntax:
http://www.google.com/?q=hello
Related
I would like to get the instance metadata (like AZ) for the current EC2, using AWS SDK.
I was able to find an alternative solution, but it is not using the SDK just a file_get_contents
How is it possible with the SDK?
The solution proposed by JasonQ-AWS is useful to get information about all instances and applications in your account. However, it does not tell you what information describes the instance that is really executed by the current process.
For that you have to use IMDSv2 which requires two CURL commands, the first one to get a TOKEN and the second one to get the actual metadata of the current instance.
In PHP the code can therefore be :
$ch = curl_init();
// get a valid TOKEN
$headers = array (
'X-aws-ec2-metadata-token-ttl-seconds: 10' );
$url = "http://169.254.169.254/latest/api/token";
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "PUT" );
curl_setopt( $ch, CURLOPT_URL, $url );
$token = curl_exec( $ch );
echo "<p> TOKEN :" . $token;
// then get metadata of the current instance
$headers = array (
'X-aws-ec2-metadata-token: '.$token );
$url = "http://169.254.169.254/latest/dynamic/instance-identity/document";
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "GET" );
$result = curl_exec( $ch );
echo "<p> RESULT :" . $result;
All you have to do is to extract the desired information. You can also ask for a unique information, such as the instance id with a more specific url like :
$url = "http://169.254.169.254/latest/meta-data/instance-id";
By current EC2 instance, are you referring to PHP code running on an EC2, and you would like to inject that metadata into some variables for use?
Or do you mean you have an object created with the PHP SDK such as with something like:
$ec2Client = new Aws\Ec2\Ec2Client([
'region' => 'us-east-1',
'version' => 'latest'
]);
If you mean the second way, you can access that data through describeInstances like this:
$result = $ec2Client->describeInstances();
echo "Instances: \n";
foreach ($result['Reservations'] as $reservation) {
foreach ($reservation['Instances'] as $instance) {
echo "InstanceId: {$instance['InstanceId']} - {$instance['State']['Name']} \n";
echo "Availability Zone: {$instance['Placement']['AvailabilityZone']} \n";
}
echo "\n";
}
You can also filter by adding parameters to the method call such as by type or instanceId.
If you're just running PHP code on the EC2 instance and you want that info, you can check out this page for some options: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html
I don't think this is possible at all. IMDSv2 info like AZ, instance-id, instance-type, etc is readable via https://169.254.169.254 and if you look into the source code for the SDK, it only pulls temporary credentials via IMDSv2 (https://github.com/aws/aws-sdk-php/search?q=169.254)
and does not allow arbitrary IMDSv2 queries.
Unless I'm missing something, you need to pull this data yourself or use some 3rd-party library which does that for you in PHP.
$data = file_get_contents("http://randomword.setgetgo.com/get.php");
var_dump($data);
I keep getting false when sending this get request, anyone have an idea why?
It works just fine with a simple php script I wrote hosted from the same domain, might that be the issue, how do I go about sending a get request to this API if that is the case?
I tried using curl as well with the same result. It works with my test script but not the API.
As noted in the various comments above, the code originally posted works fine for me but not for the OP - most likely due to a restriction placed upon various standard PHP functions by the webhost. As an alternative, cURL should be able to retrieve the content unless a similar restriction has been placed on standard curl functions too.
$url='http://randomword.setgetgo.com/get.php';
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_USERAGENT, 'curl-wordfetcher' );
$result = curl_exec( $ch );
if( curl_errno( $ch ) ) echo 'Curl error: ' . curl_error( $ch );
curl_close( $ch );
print_r( $result );
I'm creating a wordpress plugin and I'm having trouble getting a cURL call to function correctly.
Lets say I have a page www.domain.com/wp-admin/admin.php?page=orders
Within the orders page I have a function that looks to see if a button was clicked and if so it needs to do a cURL call to the same page (www.domain.com/wp-admin/admin.php?page=orders&dosomething=true) to kick off a different function. The reason I'm doing it this way is so I can have this cURL call be async.
I'm not getting any errors, but I'm also not getting any response back. If I change my url to google.com or example.com I will get a response. Is there an authentication issue or something of that nature possibly?
My code looks something like this.. I'm using gets, echos, and not doing async just for the ease of testing.
if(isset($_POST['somebutton']))
{
curlRequest("http://www.domain.com/wp-admin/admin.php?page=orders&dosomething=true");
}
if($_GET['dosomething'] == "true")
{
echo("do something");
exit;
}
function curlRequest($url) {
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
return($response);
}
You're not supposed to use CURL in WordPress Plugins.
Instead use the wp_ function for issuing HTTP requests, e.g.
function wp_plugin_event_handler () {
$url = 'http://your-end-point';
$foo = 'bar';
$post_data = array(
'email' => urlencode($foo));
$result = wp_remote_post( $url, array( 'body' => $post_data ) );
}
add_action("wp_plugin_event", "wp_plugin_event_handler");
In the past I've run into issues where WordPress plugins event handlers would hang with CURL. Using the WP_ functions instead worked as expected.
The admin section of the blog is password-protected, of course. You'll need to pass authentication data. Look up http authentication for details. Look specifically here:
http://www.php.net/manual/en/function.curl-setopt.php
You'll want to set the CURLOPT_USERPWD option and possibly CURLOPT_HTTPAUTH.
I'm developing a web application for sending SMS to mobile from website like 160by2.
I can prepare the URL required for the HTTP GET request as mentioned in the API provided by the SMS Gateway provider smslane.com, here is the link for the API.
how to send the HTTP request from PHP?
I used cURL for that purpose but the response is not displayed. here is the code i used,
<?php
$url="http://smslane.com/vendorsms/pushsms.aspx?user=abc&password=xyz&msisdn=919898123456&sid=WebSMS&msg=Test message from SMSLane&fl=0";
$ch = curl_init();
curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
curl_setopt( $ch, CURLOPT_URL, $url );
$content = curl_exec( $ch );
$response = curl_getinfo( $ch );
curl_close ( $ch );
echo $content;
?>
fsockopen() was not used because port number unknown, mailed the support team for port number. (if any code for fsockopen through GET method is invited :). )
are there any other methods for doing this?
any help is welcome.
Thanks in advance.
EDIT
Could any one tell me is there any other way to send this HTTP Request except cURL and if possible give code for that.
I'm asking this because the current cURL code taking too much time for execution and fails after 60 seconds, i increased max_execution_time to 120 in php.ini on my local system even though it is not doing good for me :( .
Your problem is the way you are constructing the URL. The spaces you are including in the query string will result in a malformed request URL being sent.
Here is an example that replicates your circumstances:
request.php:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,
'http://your_server/response.php?foo=yes we can&baz=foo bar'
);
$content = curl_exec($ch);
echo $content;
response.php:
<?php
print_r($_GET);
The output of request.php is:
Array
(
[foo] => yes
)
The reason for this is the query string is not properly encoded and the server interpreting the request assumes the URL ends at the first space, which in this case is in the middle of the query: foo=yes we can&baz=foo bar.
You need to build your URL using http_build_query, which will take care of urlencoding your query string properly and generally makes the code look a lot more readable:
echo http_build_query(array(
'user'=>'abc',
'password'=>'xyz',
'msisdn'=>'1234',
'sid'=>'WebSMS',
'msg'=>'Test message from SMSLane',
'fl'=>0
));
You also need to set CURLOPT_RETURNTRANSFER:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
<?php
print file_get_contents("http://some_server/some_file.php?some_args=true");
?>
The below code will make a HTTP request with curl and return the response in $content.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,'http://www.anydomain.com/anyapi.php?a=parameters');
$content = curl_exec($ch);
echo $content;
?>
nothing wrong with your code that I can see right off. have you tried pasting the url into a browser so you can see the response? you could even use wget to download the response to a file. I suppose if you want to try fsocket that you would use port 80 as that's the default http port.
Try using following code.
$r = new HttpRequest('http://www.xencomsoftware.net/configurator/tracker/ip.php', HttpRequest::METH_GET);
try {
$r->send();
echo $r->getResponseCode();
if ($r->getResponseCode() == 200)
{
}
}
make sure that you have loaded HttpRequest extension (share object0 in your server.
How can I make a post request to a different php page within a php script? I have one front end computer as the html page server, but when the user clicks a button, I want a backend server to do the processing and then send the information back to the front end server to show the user. I was saying that I can have a php page on the back end computer and it will send the information back to the front end. So once again, how can I do a POST request to another php page, from a php page?
Possibly the easiest way to make PHP perform a POST request is to use cURL, either as an extension or simply shelling out to another process. Here's a post sample:
// where are we posting to?
$url = 'http://foo.com/script.php';
// what post fields?
$fields = array(
'field1' => $field1,
'field2' => $field2,
);
// build the urlencoded data
$postvars = http_build_query($fields);
// open connection
$ch = curl_init();
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
// execute post
$result = curl_exec($ch);
// close connection
curl_close($ch);
Also check out Zend_Http set of classes in the Zend framework, which provides a pretty capable HTTP client written directly in PHP (no extensions required).
2014 EDIT - well, it's been a while since I wrote that. These days it's worth checking Guzzle which again can work with or without the curl extension.
Assuming your php install has the CURL extension, it is probably the easiest way (and most complete, if you wish).
Sample snippet:
//set POST variables
$url = 'http://domain.com/get-post.php';
$fields = array(
'lname'=>urlencode($last_name),
'fname'=>urlencode($first_name),
'email'=>urlencode($email)
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
Credits go to http://php.dzone.com.
Also, don't forget to visit the appropriate page(s) in the PHP Manual
index.php
$url = 'http://[host]/test.php';
$json = json_encode(['name' => 'Jhonn', 'phone' => '128000000000']);
$options = ['http' => [
'method' => 'POST',
'header' => 'Content-type:application/json',
'content' => $json
]];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
test.php
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
echo $data['name']; // Jhonn
For PHP processing, look into cURL. It will allow you to call pages on your back end and retrieve data from it. Basically you would do something like this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_URL,$fetch_url);
curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt ($ch,CURLOPT_USERAGENT, $user_agent;
curl_setopt ($ch,CURLOPT_CONNECTTIMEOUT,60);
$response = curl_exec ( $ch );
curl_close($ch);
You can also look into the PHP HTTP Extension.
Like the rest of the users say it is easiest to do this with CURL.
If curl isn't available for you then maybe
http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
If that isn't possible you could write sockets yourself
http://petewarden.typepad.com/searchbrowser/2008/06/how-to-post-an.html
For those using cURL, note that CURLOPT_POST option is taken as a boolean value, so there's actually no need to set it to the number of fields you are POSTing.
Setting CURLOPT_POST to TRUE (i.e. any integer except zero) will just tell cURL to encode the data as application/x-www-form-urlencoded, although I bet this is not strictly necessary when you're passing a urlencoded string as CURLOPT_POSTFIELDS, since cURL should already tell the encoding by the type of the value (string vs array) which this latter option is set to.
Also note that, since PHP 5, you can use the http_build_query function to make PHP urlencode the fields array for you, like this:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
Solution is in target="_blank" like this:
http://www.ozzu.com/website-design-forum/multiple-form-submit-actions-t25024.html
edit form like this:
<form method="post" action="../booking/step1.php" onsubmit="doubleSubmit(this)">
And use this script:
<script type="text/javascript">
<!--
function doubleSubmit(f)
{
// submit to action in form
f.submit();
// set second action and submit
f.target="_blank";
f.action="../booking/vytvor.php";
f.submit();
return false;
}
//-->
</script>
Although not ideal, if the cURL option doesn't do it for you, may be try using shell_exec();
CURL method is very popular so yes it is good to use it. You could also explain more those codes with some extra comments because starters could understand them.