PHP - Can A Server Answer A Get Request With A Post Response?
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. Similar TutorialsI have an application which receives multiple requests at once and it advantageous to process them as a group. I am thinking I should be doing something like the following, however, as I just came up with it on my own, would appreciate a critique. Is this a common design pattern or should I be doing something differently? Note that I have three questions asking specific questions in the below code (look for the comments with question marks).
Thanks <?php class Request { private $response, $data; public function __construct(array $data) { $this->data=$data; return $this->response=new Response($this); } public function getResponse():Response { return $this->response; } public function updateResponse($results):self { $this->response->setResults($results); return $this; } } <?php class Response { private $request, $results; public function __construct(Request $request) { //I don't really see the need for this. Any need? $this->request=$request; } public function setResults($results):self { $this->results=$results; return $this; } public function getResults() { return $this->results; } }
<?php class Container implements \Iterator { private $position = 0; private $requests, $response; public function __construct(WorkerObject $worker, array $inputArray) { $this->requests=[]; $this->responses=[]; foreach($inputArray as $i =>$inputData) { $this->requests[$i]=new Request($inputData); $this->responses[]=$this->responses[$i]->getResponse(); } //Should WorkerObject be responsible to execute Request::updateResponse() method? $worker->process_requests(...$this->requests); //Or should I iterate over my requests upon completion and execute updateResponse() method? } public function __construct() { $this->position = 0; } public function rewind() { $this->position = 0; } public function current() { return $this->responses[$this->position]; } public function key() { //Will this work? return $this->requests[$this->position]; } public function next() { ++$this->position; } public function valid() { return isset($this->responses[$this->position]); } } <?php //... $container=new Container(new WorkerObject, $inputArray); foreach($container as $request => $response) { //... }
Hello, I am trying to do multiple curl requests and get the response for each one output to the screen. I have wrote the following code, but only appear to be getting the last response when outputting $result. What am i doing wrong? Is there a way to wait for each curl request to be completed before appending to $result so I can see them all? Thanks very much if (isset($_POST['submit'])) { $result = array(); foreach ($textAr as $line) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true ); curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate"); $result[] = curl_exec ($ch); } curl_close ($ch); echo "<pre>"; print_r($result); echo "</pre>"; }
sorry for posting..i already make it You would think the answer would be all over the Internet and easy to find, but it’s not. I have searched many times, and in all the multitude of search results I have still never found an adequate usable answer. The MOST you ever find is someone saying how easy it is with PHP, but they don’t tell you how, even when the person they are answering asks them (odd). You can be that one in a billion person who finally answers it for real and helps someone out. I have a simple HTML form with data fields first_name, last_name, email, phone, country, a few hidden inputs, and a single submit button, like so: (Please note: the method is GET, not Post.) <form action="https://MyDomainOnMyServer.com/MyPHPScript.php”> <input type="text" name="first_name" value="" /> <input type="text" name="last_name" value="" /> <input type="text" name="email" value="" /> <input type="text" name="phone" value="" /> <input type="hidden" name="type" value="type123"> <input type="hidden" name="project" value="new123"> <select required name="country"> <option value="">Choose your country</option> <option value="US">United States</option> <option value="CA">Canada</option> <option value="GB">United Kingdom</option> <option value="Many More">Many More Countries</option> </select> <input type="submit" value="Submit Form" /> </form> NOTE: Originally, the form action would have been: action="https://TheirExampleDomainOnTheirRemoteServer.com/TheirRemotePHPScript.php" name="form1234" Upon clicking the single submit button only, what I need to have happen is this: 1. Send me an email to whatever@whatever.tld containing all the form submission data 2. Place the form submission data into a MySQL database having the corresponding data fields 3. Send the form submission contents including the hidden input values to "https://TheirExampleDomainOnTheirRemoteServer.com/TheirRemotePHPScript.php" name="form1234" AS IF that had remained set as the original form action to begin with So basically what I’m trying to obtain is the cleanest possible PHP script that will do those three things, which is essentially what others have asked for over the years in search results I have found, but no one has ever provided it in a clear instance that works. If I can just see such a script, I should be able to see how it works and then do what I need. Thanks. Reply Hi- I have to post to a URL, grab one field our of the JSON output/response and format nicely to the user. I've tried a few things with some help but none seem to be working. So any help or direction would be greatly appreciate it!! Attempt 1 (works but not formatted nicely) if I post using the browser, it works. the data is sent to the URL (web service) and I can see in the web service logs that the entry has been recorded. the problem is that since i have the URL in "action", i'm taken to that page and the user gets to see the JSON output Code: [Select] //here's the HTML form in offer.php <form action="http://somewebservice.com/<?php echo $PrizeID;?>" method="post" name="myform"> <input name="account" id="account" type="hidden" value="<?php echo $account;?>"/> <input name="dob" id="dob" type="hidden" value="<?php echo $dob;?>"/> <input name="site" id="site" type="hidden" value="<?php echo $site;?>"/> <input id="submit" type="submit" value="submit"/> </form> //here's the output (JSON) after clicking submit {"Prize":"XXXXXX","ConfirmationCode":"######","Error":false,"ErrorMsg":null} Attempt 2 (doens't work) i tried using php but after submit, the page refreshes and no entry is recorded in the web service log Code: [Select] //here's the HTML form in offer.php <form name="myform"> <input name="account" id="account" type="hidden" value="<?php echo $account;?>"/> <input name="dob" id="dob" type="hidden" value="<?php echo $dob;?>"/> <input name="site" id="site" type="hidden" value="<?php echo $site;?>"/> <input id="submit" type="submit" value="submit"/> //here's the php in offer.php <?php if(isset($_POST['submit'])){ $options = array( 'http'=>array( 'method'=>"POST", 'content'=>http_build_query(array( 'account' => $account, 'dob' => $dob, 'site' => $site )) )); $context = stream_context_create($options); $result = file_get_contents("http://somewebservice.com/{$PrizeID}",NULL,$context); var_dump($result); } ?> Last attempt (doesn't work) i tried using php & curl so that i can process in the back and show only the ConfirmationCode to the user in a nice format but it doesn't work. after submit, i'm taken to process.php where i see nothing and no entry is recorded in the web service log Code: [Select] //here's the HTML form in offer.php <form action="process.php" method="post" name="myform"> <input name="account" id="account" type="hidden" value="<?php echo $account;?>"/> <input name="dob" id="dob" type="hidden" value="<?php echo $dob;?>"/> <input name="site" id="site" type="hidden" value="<?php echo $site;?>"/> <input id="submit" type="submit" value="submit"/> </form> //here's the PHP in process.php <?php $postvars=file_get_contents("php://input"); $curl=curl_init("http://somewebservice.com/{$PrizeID}"); curl_setopt($curl,CURLOPT_POSTFIELDS,$postvars); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $result=curl_exec($curl); $decodedresult=json_decode($result,true); ?> i haven't gotten to the point where i grab the ConfirmationCode I want because i want to get this fixed first and also because i can't get that to work but will focus on that once i fix this. Thanks. Hi- I am new to php, trying to make a simple form that emails when submitted. It works fine on my own server, but when I try it on my work server I get: Warning: mail() [function.mail]: SMTP server response: 550 Authentication is required for relay in C:\inetpub\wwwroot\OMC\estimate3.php on line 159 here are the headers: $headers = "From: info@combatstocks.com\n"; $headers .= "X-Mailer: PHP4\n"; $headers .= "X-Priority: 3\n"; $headers .= "MIME-Version: 1.0\n"; $headers .= "Content-Type: multipart/alternative; boundary=\"==MIME_BOUNDRY_alt_main_message\"\n\n"; and the mail() function mail($to,$subject,$body,$headers); let me know if you need more code and ill happily supply it. thanks! I have a piece of code that works on one domain but not on another. On the domain running php 5.1 all is ok. On the domain running php 4.4 I get this error: SMTP server response: 501 5.5.4 Invalid Address Hosting service keeps telling me there must be an error in the code. If that's the case why would it work on version 5.1? Here is the code, I don't know what could be wrong. Any help will be greatly appreciated. <?php // set flag to indicate whether mail has been sent $mailSent = false; $sent = false; if (array_key_exists('sendComments', $_POST)) { // mail processing script // remove escape characters from POST array if (get_magic_quotes_gpc()) { function stripslashes_deep($value) { $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); return $value; } $_POST = array_map('stripslashes_deep', $_POST); } // validate the input, beginning with name $name = trim($_POST['name']); if (empty($name)) { $error['name'] = 'Please enter your name'; } $phone = trim($_POST['phone']); $email = $_POST['email']; // check for valid email address $pattern = '/^[^@]+@[^\s\r\n\'";,@%]+$/'; if (!preg_match($pattern, trim($email))) { $error['email'] = 'Please enter a valid email address'; } // check the content of the text area $messageBody = trim($_POST['message']); if (empty($messageBody)) { $error['message'] = 'Please enter your message'; } // initalize variables $to = 'jim@independent-micro.com'; $subject = 'Feedback from PCI-Controls web site'; // build the message $message = "From: $name\n\n"; $message .= "Email: $email\n\n"; $message .= "Phone Number: $phone\n\n"; $message .= "Comments: $messageBody"; // build additional headers $additionalHeaders = "From: PCI Controls Web Site<$email>\r\n"; $additionalHeaders .= "Reply-To: $email"; // send the mail if ther are no errors if (!isset($error)) { $mailSent = mail($to, $subject, $message, $additionalHeaders); // check to see if sent successfully if (!$mailSent) { $error['notSent'] = 'Sorry there is a problem sending your message. Please try later.'; } else { $sent = true; } } } ?> I'm a total noob at PHP, and need to make a simple authentication server-side script for a Java application that is in no way associated with the server. My Java app URL encodes in this format(pretty standard): "key1"="value1" I THINK I have the correct code in PHP to read the HTTP POST data values... Code: [Select] $username = array("1", 2, 3, 4, 5); $match = FALSE; foreach($_POST as $key1 => $value1){ foreach($username as $key2 => $value2){ if ($value1 == $value2){ $match = TRUE; break; } } if ($match = TRUE) break; } After all this I'd like to send a response saying either TRUE or FALSE(in other words, I'd like to send the variable $match). I've looked far and wide for how to do this in PHP, and couldn't find a single helpful page. 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 have created a login page that links to a username/password reset page upon the user's request. Both pages use: Code: [Select] if( $_SERVER[ 'REQUEST_METHOD' ] == "POST" ) The login page works perfectly in every way; however, the reset page does not. The value of the request method echos as GET even before the form is submitted (the value is GET upon loading). The form submission method is POST, but it does not work even after the fields are supplied and the form is submitted. My understanding of the request methods is limited, but I gather the problem relates with the manner that I am linking from the login page to the reset page. Is there a simple explanation for this? Thank you in advance. 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! 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; ?> This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=359184.0 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! 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 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 Hello, 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 Hi, For about a month, I have been trying to figure out why my code will not return anything after posting a wwwForm (I have also tried the newer equivalent of this function but I had no luck with that either.) The nameField and passwordField are taken from text boxes within the game and the code used in my login script is copied and pasted from a Register script but I have changed the file location to the login.php file. The register script works fine and I can add new users to my database but the login script only outputs "Form Sent." and not the "present" that should return when the form is returned and it never gets any further than that point meaning that it lets the user through with no consequence if they use an invalid name because the script never returns an answer. What should I do to fix this? Thanks, Unity Code: using System.Collections; using UnityEngine; using UnityEngine.UI; using UnityEngine.Networking; public class Login : MonoBehaviour { public InputField nameField; public InputField passwordField; public Button acceptSubmissionButton; public void CallLogInCoroutine() { StartCoroutine(LogIn()); } IEnumerator LogIn() { WWWForm form = new WWWForm(); form.AddField("username", nameField.text); form.AddField("password", passwordField.text); WWW www = new WWW("http://localhost/sqlconnect/login.php", form); Debug.Log("Form Sent."); yield return www; Debug.Log("Present"); if (www.text[0] == '0') { Debug.Log("Present2"); DatabaseManager.username = nameField.text; DatabaseManager.score = int.Parse(www.text.Split('\t')[1]); Debug.Log("Log In Success."); } else { Debug.Log("User Login Failed. Error #" + www.text); } } public void Validation() { acceptSubmissionButton.interactable = nameField.text.Length >= 7 && passwordField.text.Length >= 8; } } login.php: <?php echo "Test String2"; $con = mysqli_connect('localhost', 'root', 'root', 'computer science coursework'); // check for successful connection. if (mysqli_connect_errno()) { echo "1: Connection failed"; // Error code #1 - connection failed. exit(); } $username = mysqli_escape_string($con, $_POST["username"]); $usernameClean = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH); $password = $_POST["password"]; if($username != $usernameClean) { echo "7: Illegal Username, Potential SQL Injection Query. Access Denied."; exit(); } // check for if the name already exists. $namecheckquery = "SELECT username, salt, hash, score FROM players WHERE username='" . $usernameClean . "';"; $namecheck = mysqli_query($con, $namecheckquery) or die("2: Name check query failed"); // Error code # 2 - name check query failed. if (mysqli_num_rows($namecheck) != 1) { echo "5: No User With Your Log In Details Were Found Or More Than One User With Your Log In Details Were Found"; // Error code #5 - other than 1 user found with login details exit(); } // get login info from query $existinginfo = mysqli_fetch_assoc($namecheck); $salt = $existinginfo["salt"]; $hash = $existinginfo["hash"]; $loginhash = crypt($password, $salt); if ($hash != $loginhash) { echo "6: Incorrect Password"; // error code #6 - password does not hash to match table exit; } echo "Test String2"; echo"0\t" . $existinginfo["score"]; ?>
$to=sammieave@ave.com,samuel@ave.com; $subject = "New Event Logged"; $message = "Test"; $headers = "From: Samuel<sammieave@ave.com>;\r\n"; $headers .= "Content-Type: text/html"; mail($to,$subject,$message,$headers); I am having the above code but unfortunately the error I am getting is: Warning: mail() [function.mail]: SMTP server response: 550 Requested action not taken: mailbox unavailable or not local in C:\xampp\htdocs\CRM\support\mailer.php on line 139 A HTTP request is made to the server, Slim creates a Request and Response object, content in the Request is sent to another server using cURL via Guzzle, Guzzle returns its own Response, and content from Guzzle's response must be returned by the original Slim response. Would you recommend white-listing or black-listing response headers, and which specific headers? Similarly, would you recommend white-listing or black-listing the request headers sent via cURL, and which specific headers? Thanks <?php use Psr\Http\Message\ResponseInterface as Response; use GuzzleHttp\Psr7\Response as CurlResponse; class ApiResponder { public function delete(Response $httpResponse, CurlResponse $curlResponse) { return $this->proxy($httpResponse, $curlResponse); } //other public methods... private function proxy(Response $httpResponse, CurlResponse $curlResponse) { foreach($this->getResponseHeaders($curlResponse) as $name=>$value) { $httpResponse=$httpResponse->withHeader($name, $value); } return $httpResponse->withBody($curlResponse->getBody())->withStatus($curlResponse->getStatusCode()); } private function getResponseHeaders(Response $httpResponse):array { //Blacklist headers which should be returned to original client. TBD whether I should whitelist headers instead. $blacklist=['Date'=>null, 'Server'=>null, 'X-Powered-By'=>null, 'Access-Control-Allow-Origin'=>null, 'Access-Control-Allow-Methods'=>null, 'Access-Control-Allow-Headers'=>null, 'Set-Cookie'=>null]; return array_diff_key($curlResponse->getHeaders(), $blacklist); } /** * This method doesn't really exist in this class, but is just included to show which headers I am forwarding in the cURL request. */ private function getRequestHeaders($clientRequest):array { $whitelist=['connection'=>null,'accept'=>null,'accept-encoding'=>null,'accept-language'=>null,'content-type'=>null,'content-length'=>null]; return array_intersect_key($clientRequest->getHeaders(), $whitelist); } }
|