PHP - [php] Make A Remote Post And Get Request
Hey!
Can anyone help with this, is it possible to make a post to a remote website, so when the use runs the script it will post some information to a remote server and then grab some info it gets back in a get request or something along those lines? Hope someone can guide me to more info thanks! Similar TutorialsHello, I need to execute a remote web page (distant server) every X seconds. How is it possible and is there any way to make it look exactly like a normal user request through a standard browser like Firefox, Chrome, etc. ? I've heard of cURL, but it seems that servers may block it, so there must be somehow a difference between a usual user request and a cURL execution. Thank you for any help ! :-) Matthew I am setting up an API for my users, and the user sends post data via cURL. Is there a way I can see what site that the post data is coming from? would $_SERVER['REMOTE_HOST'] work? I am not using that to validate information. A couple months back, I asked on a gaming forum if anyone knew of a website that would track your *Steam Wishlist and email you when one of your wishlist games went on sale. No one at the time knew of a **solution, so I decided to buy "PHP, MySQL and Javascript" and try to roll my own. I managed to get the basics working. After the basics, I started thinking about fun stuff I could do with the data I collected from Steam regarding the games that go on sale regularly. The first part of my code file_get_content's the ***sale page(s) of games, and sucks out the games name, regular price, sale price, and the games homepage URL on Steam. This is enough to accomplish my basic task. The second part is where I need help, and that's getting more details on the game. The additional details I want to get about the game include its Publisher and Developer, and to get that detail I need to go to the games homepage URL I previously got from the global sale page. The issue is this: Some games have an age-restriction limitation, and you have to fill out a date form before entering the games homepage. An example of one of those pages would be: http://store.steampowered.com/agecheck/app/1250/ I want to be able to POST a legal age to the above URL, and then (this is where I'm hazy) "re-load" the same URL, authorized by my previous POST. Is that possible? * Steam is a digital download service for computer games. ** Subsequently, there was another website found. But I was well into developing my solution and having fun. *** Example: http://store.steampowered.com/search/?specials=1 Hi there, I'm running a php based website and I'm getting a lot of remotely posts to the forms. Is any way to prevent this using php or .htacces. Any tip o a site from where I should start? Thank you in advance. Hi all, I am new here and I really thank God that I found this forum! I have read the materials here on working with cURL on javascript-form-submission pages. However, I can't to get my script to work. Can anybody here please help me out or drop me a hint on where to correct my script? ==Situation== My company utilizes http://www.myfax.com/free/ to send our company faxes. My task is to write a code that would submit files for faxes electronically. Note: The site also requires e-mail confirmation but I haven't get to that stage yet. I have run tests on submitting fax requests both by code and manually through the site, and have confirmed that the code doesn't work on the submission level because I managed to receive confirmation e-mails for manual submissions. Also, I tried my script with different staff email addresses because I figured out that it blocks only the same e-mail address from sending more than 2 faxes a day. Code: (php) [Select] <?php //target page url $strPage_url = 'www.myfax.com/free/'; //create array of data to be posted $arrPost_data = array ( 'ctl00$MainSection$tbRecipientName' => 'I am recipient', //max length = 50 'ctl00$MainSection$tbRecipientCompany' => 'I am recipient company', //max length = 50 'ctl00$MainSection$tbRecipientFaxNumber' => '+1 (206) 202-8273', //recipient fax 'ctl00$MainSection$ddlRecipientCountry' => html_entity_decode ('{"c":{"i":"2","n":"United States","t":"1","s":"US"},"m":{"i":"1","v":"+1 (###) ###-####","d":"","f":"","c":"","r":""}}'), 'ctl00$MainSection$tbSenderName' => 'I am sender', //max length = 50 'ctl00$MainSection$tbSenderCompany' => 'I am sender company', //max length = 50 'ctl00$MainSection$tbSenderEmailAddress' => 'abc@example.com', //email 'ctl00$MainSection$nbAntiSpam$nbAntiSpam_NoBotExtender_ClientState' => '-150', //number drawn from inspecting the packages sent by manual form submission 'ctl00$MainSection$fileUpload' => '@/files/file.pdf', //file 'ctl00$MainSection$tbMessage' => 'hello world', //message '__EVENTTARGET' => '', '__EVENTARGUMENT' => '', '__VIEWSTATEENCRYPTED' => '' ); //visit the page and get cookies $curl_connection = curl_init ($strPage_url); curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 0); curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); curl_setopt($curl_connection, CURLOPT_REFERER, "http://www.myfax.com/free/"); curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1); curl_setopt ($curl_connection, CURLOPT_COOKIEJAR, 'CURLCOOKIE'); $strGet_page_contents = curl_exec ($curl_connection); curl_close ($curl_connection); //get page to retrieve view state and event validation if ( preg_match ( '/"__VIEWSTATE"[\s]+?value="([\s\S]+?)"/' , $strGet_page_contents , $arrView_state ) ) { $strView_state = $arrView_state[1]; $arrPost_data['__VIEWSTATE'] = $strView_state; } if ( preg_match ( '/"__EVENTVALIDATION"[\s]+?value="([\s\S]+?)"/' , $strGet_page_contents , $arrEvent_validation ) ) { $strEvent_validation = $arrEvent_validation[1]; $arrPost_data['__EVENTVALIDATION'] = $strEvent_validation; } if ( preg_match ( '/id="ctl00_MainSection_nbAntiSpam_nbAntiSpam_NoBotExtender_ClientState" value="([\s\S]+?)"/' , $strGet_page_contents , $arrAnti_spam ) ) { $strAnti_spam = $arrAnti_spam[1]; $arrPost_data['ctl00$MainSection$nbAntiSpam$nbAntiSpam_NoBotExtender_ClientState'] = $strAnti_spam; } //traverse array and prepare data for posting (key1=value1) foreach ( $arrPost_data as $key => $value) { $arrPost_items[] = $key . '=' . $value; } //create the final string to be posted using implode() $strPost_string = implode ('&', $arrPost_items); //create cURL connection $curl_connection = curl_init($strPage_url); //set options curl_setopt ($curl_connection, CURLOPT_POST, 1); curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 0); curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); curl_setopt($curl_connection, CURLOPT_REFERER, "http://www.myfax.com/free/"); curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1); //set cookie curl_setopt ($curl_connection, CURLOPT_COOKIEFILE, 'CURLCOOKIE'); unlink ( 'CURLCOOKIE' ); curl_setopt($curl_connection, CURLOPT_COOKIE, session_name() . '=' . session_id()); //set header $arrHeaders = array ( 'Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8' ); curl_setopt($curl_connection, CURLOPT_HTTPHEADER, $arrHeaders ); //set data to be posted curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $strPost_string); //perform our request $strResult = curl_exec($curl_connection); //show information regarding the request - for debugging echo "<pre>"; print_r(curl_getinfo($curl_connection)); echo curl_errno($curl_connection) . '-' . curl_error($curl_connection); echo "<hr>"; var_dump ($arrPost_items); echo "</pre>"; //close the connection curl_close($curl_connection); ?> Code: [Select] <?php if ($_SERVER['REQUEST_METHOD'] == 'POST'){ $db = mysql_connect("localhost", "*******" , "*****")or die("Error connecting to database: " . mysql_error()); $db_used = mysql_select_db("pskkorg_drp1", $db)or die("Could not select database: " . mysql_error()); $user_name = mysql_real_escape_string($_POST['username'],$db); $query = mysql_query("SELECT * FROM student WHERE Username = '$user_name'",$db) or die(mysql_error()); if(mysql_num_rows($query) == 1){ echo "Login successful, welcome back " . $user_name . ""; }else{ echo "Login unsuccessful, please ensure you are using the correct details"; } }else{ echo "Error"; } ?> take a look at this code, is there anything wrong?... it always come out the error output when i test it. when i enter this url, http://www.pskk.org/LMS/LMSscripts/FirstTimeUser10.php?Username=149090 it come out Error. suppose it will appear Login Successful since the username 149090 exist in the database. I am testing a url for http post request. It connects to the site then it is disconnected. In fire fox it is giving error that the "connection was reset". In google chrome it is giving error that "Unable to load the webpage because the server sent no data". Following is the script. I am new to curl and also new to http request response. The provider of this site tells me that everything is ok and it is sending data but i am not getting any data or any header of this site. <?php $data = '<?xml version="1.0" encoding="UTF-8"?><Request><Source ClientID="test_xml" Password="1234" /><RequestDetails Language="En"><SearchHotelPriceRequest><ServiceDestination DestinationType="city" DestinationCode="477" /><ImmediateConfirmationOnly>1</ImmediateConfirmationOnly><PeriodOfStay><CheckInDate>2012-03-01</CheckInDate><Duration>3</Duration></PeriodOfStay><Rooms> <Room NumberOfRooms="1" NumberOfAdults="2" /> </Rooms></SearchHotelPriceRequest></RequestDetails></Request>'; $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, 'https://62.218.28.13:8443/monWebService/Request/v2'); curl_setopt($ch, CURLOPT_POST, $data); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $data = curl_exec($ch); curl_close ($ch); echo $data; ?> How do I send multiple headers with this code? Code: [Select] <?php $postdata = http_build_query( array( 'var1' => 'some content', 'var2' => 'doh' ) ); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://example.com/submit.php', false, $context); ?> *this header: Code: [Select] User-Agent: Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16 Hi everyone, I am making a screen scraper in php which scrapes the usernames from forum posts and stores them in an SQL database. I need some help with part of the preg_match code if possible please? The code and also the pseudo code I have so far is:(the pseudocode I am having trouble with but will try to solve my self if possible). Edit: sorry, editted the page as was confusing to read. Please ask for clarificaiton if there is anything I have failed to explain properly. thank you. //I will be placing the following php in the confirmation page people see after making a new post, so for this example lets say the referrer header says: http://www.mysite.com/showthread.php?tid=1' Code: [Select] $threadurl=$_SERVER['HTTP_REFERER']; // scrape the page Code: [Select] $content = file_get_contents($threadurl); // find the pattern in source which makes it easy to find the username- the only things that change are the uid and the color Code: [Select] if (preg_match("/\b uid=792"><span style="color:#ffcc00">fapafap</span></a>\b /i", $content)) { //extract username from this string search Don't know! //copy the username (in this case 'fapafap') to the database along with the referral ID Code: [Select] $query_insert="INSERT INTO newpostersdatabase(username,referrerurl) VALUES('$username','$threadurl')" ; $result=mysql_query ( $query_insert); if(!$result){ die(mysql_error()); } Thank you so much for any guidance, I know that I have totally messed up with the string search also but my brain is too small it seems! This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=359184.0 I need to make my client's site distinguish among different tabs in the same browser. (See http://www.phpfreaks.com/forums/index.php?topic=357772.0 for background.) I create a tab ID when the user first visits the site in a particular tab, and I'm passing it from page to page as a parameter. This seems to be the only way to do what I need. The tab ID is always passed through POST so that the user won't see it. If it were visible, users could make trouble (or more likely get in trouble) by adding or removing the ID themselves. This is not simple where a page is loaded by a hyperlink. The anchor tag passes parameters via GET, period. The solution I found is to link to a script named post.php, which takes the real link target and the tab ID as parameters, sends the browser a form that passes the tab ID to the real link target via POST, and auto-submits the form via JavaScript. This works, but it requires two round trips to the browser to load a page. It's also a pain to code. Is there a more efficient way to do this... perhaps a way to make the server send the browser a POST response, even though it made a GET request? If it matters, the server is Apache 2.x. Hey people of php freaks recently, I've been having issues changing a discord webhook [curl] post request to a website [curl] post request. My knowledge in PHP is very limited so, I really would appreciate some help This is the function: function postToDiscord($message) { $data = array("content" => $message, "username" => "Payouts Bot"); $curl = curl_init("https://discordapp.com/api/webhooks/591662537293168650/eyme87xmCuKne4njucoDSqzojq78NaS9x7t4sgP9m-l5EmrvUeZegkM4wok-L-UdBDxo"); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); return curl_exec($curl); } Currently the discord bot transfers the message into a discord channel and, I do not want that. I want it to transfer it onto a website page. As, I said i'm not very keen on this so please help me.
Edited July 3, 2019 by LegitSpiderman hi friends, I am using one API in which i need to make request for flight search, i am using soapclient to connect with the server to fetch available flights, below is the xml in which request format will be. SOAP 1.1 The following is a sample SOAP 1.1 request. The placeholders shown need to be replaced with actual values. POST /tws_mind/Ws_TravelPortal.asmx HTTP/1.1 Host: 125.16.62.119 Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "http://tempuri.org/Ws_fnAirAvail" <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <Ws_fnAirAvail xmlns="http://tempuri.org/"> <objReq> <destination> <string>string</string> <string>string</string> </destination> <domestic>boolean</domestic> <journeydate> <dateTime>dateTime</dateTime> <dateTime>dateTime</dateTime> </journeydate> <journeytype>string</journeytype> <Noofadults>int</Noofadults> <Noofchild>int</Noofchild> <Noofinfant>int</Noofinfant> <preferedairlines> <string>string</string> <string>string</string> </preferedairlines> <preferredclass>string</preferredclass> <returndate>dateTime</returndate> <source> <string>string</string> <string>string</string> </source> <strPreferredCarrierType>string</strPreferredCarrierType> <GetCachedData>boolean</GetCachedData> </objReq> <objSecurity> <strLoginId>string</strLoginId> <strPassword>string</strPassword> </objSecurity> </Ws_fnAirAvail> </soap:Body> </soap:Envelope> and below is the request which is made by me. $request=array( 'objReq'=>array('destination' => "DEL", 'domestic' => 1, 'journeydate'=>"25/10/2011", 'journeytype'=>"R", 'Noofadults'=>2, 'Noofchild'=>0, 'Noofinfant'=>0, 'preferedairlines'=>"", 'preferredclass'=>"Y", 'returndate'=>"28/10/2011", 'source'=>"BLR", 'strPreferredCarrierType'=>"ANY", 'GetCachedData'=>false ) 'objSecurity'=>array('strLoginId'=>"loginid", 'strPassword'=>"password" ) ); $wsdl="http://*/*/?wsdl"; try{ $cliente=new SoapClient($wsdl); $vem=$cliente->Ws_fnAirAvail($request); } catch (Exception $e) { echo $e->getMessage(); exit; } echo "<pre>"; print_r($vem); My problem is i am getting below response, if i change the request in anyway i always get the same response. Please correct my request in case i made bad request for the server. stdClass Object ( [Ws_fnAirAvailResult] => stdClass Object ( [objclsException] => stdClass Object ( [errorcode] => GEN0E0006 [errortype] => E [errordesc] => Please provide Security object. ) [strMessage] => ) ) Hi, I have a blog page I am working on and I am trying to make some enhancements that I need some help with. In MySQL I have a table with id, title and post. In my page display I want to enable the user to click on the title and display a post on it's own so the URL would look like www.mysite.com/blog/?id=1 or something like that. Here is the PHP function to display the post from MySQL. all on one page. function GetBlogPosts($inId=null, $inTagId =null) { if (!empty($inId)) { $query = mysql_query("SELECT * FROM blog_posts WHERE id = " . $inId . " ORDER BY id DESC LIMIT 2"); } else if (!empty($inTagId)) { $query = mysql_query("SELECT blog_posts.* FROM blog_post_tags LEFT JOIN (blog_posts) ON (blog_post_tags.postID = blog_posts.id) WHERE blog_post_tags.tagID =" . $tagID . " ORDER BY blog_posts.id DESC"); } else { $query = mysql_query("SELECT * FROM blog_posts ORDER BY id DESC"); } $postArray = array(); while ($row = mysql_fetch_assoc($query)) { $myPost = new BlogPost($row["id"], $row['title'], $row['post'], $row['postfull'], $row["author_id"], $row['date_posted']); array_push($postArray, $myPost); } return $postArray; } Doing something wrong, but don't see it. How should one retrieve a POST parameter? My $request->toArray()['html'] works, but I am sure it is not the "right way". <?php namespace App\DataPersister; use ApiPlatform\Core\DataPersister\DataPersisterInterface; use Symfony\Component\HttpFoundation\RequestStack; class ArchivePersister implements DataPersisterInterface { public function __construct(RequestStack $requestStack) { $request = $requestStack->getCurrentRequest(); syslog(LOG_ERR, '$request->getMethod(): '.$request->getMethod()); syslog(LOG_ERR, '$request->getContent(): '.$request->getContent()); syslog(LOG_ERR, '$request->request->get(html): '.$request->request->get('html')); syslog(LOG_ERR, '$request->query->get(html): '.$request->query->get('html')); syslog(LOG_ERR, '$request->get(html): '.$request->get('html')); syslog(LOG_ERR, '$request->toArray(): '.json_encode($request->toArray())); syslog(LOG_ERR, '$request->toArray()[html]: '.$request->toArray()['html']); } } output $request->getMethod(): POST $request->getContent(): {"project":"/projects/1","description":"","html":"<p>{{ project_name }}</p>"} $request->request->get(html): $request->query->get(html): $request->get(html): $request->toArray(): {"project":"\/projects\/1","description":"","html":"<p>{{ project_name }}<\/p>"} $request->toArray()[html]: <p>{{ project_name }}</p> Hey Guys. I am working with a form that shows the grand total on the checkout page. The value of the grand total is inside a hidden field. When click on submit, the _POST array doesn't get back the last value of the grand total. I need to hit the button twice to get the last value. The weird thing is when I echo the value of the grand total it display the latest value, but not with the POST array
For example. If the grand total is $10.00 and I click on submit. It will show the POST['grand_total'] as empty. If I click on submit again it will show the grand total of $10.00.
Below is my code that I am working with. Any help would be really appreciated.
if(isset($_POST['submit'])) { /* Doesn't show if i put it after if($_POST['submit'] */ if(isset($_POST['grand_total'])) { echo $_POST['grand_total']; } } //A bunch of other html/php code. Another class calculates the subtotal assigns it the variable $subtotal $cart_totals = new cartTotals($subtotal, $discounted_amount,$post_values->tip); // Cart class is shown below /* Doesn't show if i put it before if($_POST['submit'] */ if(isset($_POST['grand_total'])) { echo $_POST['grand_total']; } echo "<input name='grand_total' type='hidden' value='$cart_totals->grand_total' />"; // Shows the grand total after second from submission echo "$cart_totals->grand_total"; // Shows grand total after the first submissionCart Totals Class class cartTotals { public $subtotal; public $sales_tax; public $tip; public $grand_total; public $discount_amount; public $href_page; public $invalidCouponMessage; const TEST_ENVIORMENT = FALSE; /** * [ Function gets constructed in the order summary where the [$discount_amount= ""] arg does need to be passed. * But does get passed in when called on the checkout.php page. Therefore we set the default value to an empty string.] * @param [float] $subtotal [subtotal get passed in from the parent class coreCartFunction] * @param string $discount_amount [The class checkCouponCode calculates this discount amount based on the * subtotal and the discount amount. It gets instantiated on the clients side and passed is this construction function. * This is all done on the checkout page.] */ /*The way the construct function works is by invoking all the methods the passed arguments When the methods get invoked the do all the work and set the properties its values. The properties then get echoed out on the client side. */ function __construct($subtotal="", $discount_amount= "", $tip=""){ $this->subTotal($subtotal, $discount_amount);//SubTotal method takes the discount amount and subtracts it from the subtotal. $this->salesTax($subtotal, $discount_amount); $this->tip = $tip; $this->grandTotal(); } private function subTotal($subtotal,$discount_amount) { $rounded_subtotal = round($subtotal-$discount_amount,2); $money_format_subtotal = money_format('%i',$rounded_subtotal); $this->subtotal = $money_format_subtotal; } private function salesTax($subtotal, $discount_amount =""){ $sales_tax = (STORE_SALES_TAX)?(float)STORE_SALES_TAX:8.875; $sales_tax =(($this->subtotal)*$sales_tax)/100; $sales_tax = round($sales_tax,2); $this->sales_tax = $sales_tax; } public function Tip() { //global $post_values; //$last_tip_selected = $post_values->tip > 0 ? $post_values->tip : "" ; $tip_output = "<select id='tip' name='tip'>"; for($tip=0.00; $tip<=11.75; $tip+=0.25){ if( $tip == "2") {$selected = " selected";} else {$selected ="";} $formatted_tip = money_format('%i',$tip); $tip_output .= "<option {$selected} id='selected_tip' value='$formatted_tip'>"."$".$formatted_tip ."</option>".PHP_EOL; } $tip_output .= "</select>"; return $tip_output; } private function grandTotal(){ $grand_total = round($this->sales_tax+$this->subtotal+$this->tip,2); $grand_total_formatted = money_format('%i',$grand_total); $this->grand_total = $grand_total_formatted; } $post='{"cart_items":[{"configuration":{"price":100,"recharge_number":"9999999999"},"product_id":"999","qty":1}]}';i try this n reslut was :There are no valid items in cart: help me plz Edited by ShivaGupta, 30 November 2014 - 01:11 AM. I'm learning PHP, and in the course of this, I'm writing a little app which posts to the same php file. HOWEVER, when I run the app again, the POST values remain. I can use unset() but, is there another way to clear POST data? RON Hi,
I have a series of post to post connections. In one function, the output is a list of the linked post to posts. Here is an example: function countryJob(){ global $post;
$echo = f_print(array( echo '<div class="country-job-text">'.$echo.'</div>';
job, location and city are all post types that can be connected.
I want to create the same as above to create a list of the cites connected to a location (locations are the name for posts which are countries)
How do I discover the connection type and post type needed to create this output? |