PHP - Basic Http Post Not Working
Hi,
I'm trying to get HTTP post to work on my server but even the most basic script does not work. Can anyone help me? PHP script: <?php echo 'Hello ' . htmlspecialchars($_POST["name"]) . '!'; ?> I try and POST data to the script using: http://www.czoryk.co.uk/post_test.php?name=Chris But when I try and do that only ' Hello ! ' is displayed. I'm sure this is just a simple error but I can't figure out what's wrong. Thanks, Chris Similar TutorialsSome background we are creating a system that collects rain data from multiple sensors and then every 15 mins sends a packet to the main server. I have been ingesting this data fine and storing the info into my database and storing a local .txt file of the packet. To forward this packet to our back up server I have been using: shell_exec("nc backup_server_address < ".$my_p); Where $my_p is the location of the .txt file. However, I have been requested to not use nc as it creates its own process every time it is called and for scalability issues we would like to forward the packet using PHP and not require a new process every time we receive a packet. I tried do some redirect stuff using headers("Location: backup_server_address"). If anyone can help that would be greatly appreciated. I have been using curl and curl_multi, but it takes about 500ms between each query. I am sending for example https://www.apidomain.com/user=test&pass=test It then should return an output of successful or unsuccessful. How can I do this to run the url in a loop of 10 iterations, without curl, but with the speed of a millisecond or less? Thanks! I'm new to PHP, XML, and web development in general, so please bear with me... I'm working in a PHP environment and need to send user credentials $username and $password in XML via a HTTP post. Does that even make sense? Let me explain: I have already successfully used a method of capturing credentials, and they can be called by the use of $username and $password. I need to pass these on to an XML web service on another domain, but they need to be included in a larger piece of XML. To top it all off, I need this process to occur only when an image in a page is clicked. Here is the XML that needs to be sent (except that $username and $password are my strings from above): <xml-fragment xmlns:vp="http://my.host.com/somedirectory"> <vp:vprequest> <query>authenticateUser</query> </vp:vprequest> <vp:vpuser> <username>$username</username> <password>$password</password> <userid/> <firstname/> <lastname/> <useremail/> <assignedRoles> <roleDef/> </assignedRoles> </vp:vpuser> <vportal> <vportal_id>1</vportal_id> </vportal> </xml-fragment> I need to send it to: https://my.host.com/xmlwebapp Anything sending to the XML Web App must pass their XML data with the content type set to application/xml. I'm confused with how I should be sending this. I believe that the XML APP can receive HTTP POST, but I don't know how to write that code into PHP and then have it send it all as XML. Any help would be appreciated! Thank you! 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; ?>
Hello, I am a newbie regarding PHP and have done mostly only front-end web design for a couple of years and recently started querying DB's and displaying the data, but now this is a new project.
I've tested code snippets as the ones below, but fail to incorporate them in the bigger picture of what I'm trying to achieve. <?php // https://gist.github.com/magnetikonline/650e30e485c0f91f2f40 class DumpHTTPRequestToFile { public function execute($targetFile) { $data = sprintf( "%s %s %s\n\nHTTP headers:\n", $_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL'] ); foreach ($this->getHeaderList() as $name => $value) { $data .= $name . ': ' . $value . "\n"; } $data .= "\nRequest body:\n"; file_put_contents( $targetFile, $data . file_get_contents('php://input') . "\n" ); echo("Done!\n\n"); } private function getHeaderList() { $headerList = []; foreach ($_SERVER as $name => $value) { if (preg_match('/^HTTP_/',$name)) { // convert HTTP_HEADER_NAME to Header-Name $name = strtr(substr($name,5),'_',' '); $name = ucwords(strtolower($name)); $name = strtr($name,' ','-'); // add to list $headerList[$name] = $value; } } return $headerList; } } (new DumpHTTPRequestToFile)->execute('./dumprequest.csv'); This snippet also seems to return the headers and their values but I don't know how to efficiently write and append it to a TXT or CSV, or preferably, directly into a MySQL database. <?php foreach (getallheaders() as $name => $value) { echo "$name: $value"; echo "<br>"; } ?>
Any help towards storing the header values of HTTP POST requests into a database would be greatly appreciated! Hello there,
I am coding Arduino micro controller, and intended to GET the data from server MySQL db through php to turn ON/OFF LED. I could able to GET the data from manually updated MySQL db value, even I could able to successfully change the data of MySQL db from micro controller POST method. But I am getting error when trying to change the MySQL db value from browser using online POST tool, Following is PHP code at server 8 $api_key_value ="XXXXXXXXX";//Sample 9 $api_key =""; 10 $status = ""; 11 $id =""; 12 13 if ($_SERVER["REQUEST_METHOD"] == "POST") { 14 $api_key = test_input($_POST["api_key"]); 15 if($api_key == $api_key_value) { $id = test_input($_POST["id"]); $status = test_input($_POST["status"]); // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } //$sql = "INSERT INTO led (status) //VALUES ('" . $status . "')"; $sql = "UPDATE led SET status='$status' WHERE id='$id'"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); } else { echo "Wrong API Key provided."; } } else { echo "No data posted with HTTP POST."; } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } Post Command: http://url/MySQL_POST.php?api_key=XXXXXXXXX&id=1&status=on Response/Error: Notice: Undefined index: api_key in <PATH>/MySQL_POST.php on line 14 Wrong API Key provided. Could be a basic issue, but I am very new to php coding and cannot solve this problem yet. Could someone please help? Thanks. Hi there, Any help is greatly appreciated. I've commented out the code giving me trouble. Error = <br /> <b>Warning</b>: curl_setopt(): supplied argument is not a valid cURL handle resource in <b>/###.php</b> on line <b>34</b><br /> <br /> <b>Warning</b>: curl_setopt(): supplied argument is not a valid cURL handle resource in <b>/###.php</b> on line <b>35</b><br /> <?php $ch = curl_init(); $timeout = 30; $userAgent = $_SERVER['HTTP_USER_AGENT']; if ($_REQUEST['update']) { curl_setopt($ch, CURLOPT_URL, $_REQUEST['url']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_USERPWD, $_REQUEST['username'] . ':' . $_REQUEST['password']); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); //curl_setopt($c, CURLOPT_POST, true); //curl_setopt($c, CURLOPT_POSTFIELDS, $_REQUEST['update']); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); $response = curl_exec($ch); if (curl_errno($ch)) { echo curl_error($ch); } else { curl_close($ch); echo $response; } } Hey y'all, I'm trying to write a PHP script for a login function. There are three elements, two text fields (username and password) and a button which calls the script. Segment from index.php file: <form action = "login.php" method = "POST"> Admin Login: <br> Username: <input type = "text" name = "usernameField"/><br> <!-- Password field--> Password: <input type = "password" name = "passwordField"/><br> <!-- Username field --> <input type = "button" value = "Login" name = "submitButton"/> <!-- Login button --> </form> Segment from login.php file: <?php $connect = mysql_connect("localhost", "root", "root"); if(!$connect){//If user can't connect to database die('Could not connect: ' . mysql_error()); //Throw an error } mysql_select_db("colin_db", $connect); //Get given username and password from username field and password field $givenUsername = $_POST["usernameField"]; $givenPassword = $_POST["passwordField"]; $myQuery = "SELECT * FROM ADMINS WHERE USERNAME = '$givenUsername' AND PASSWORD = '$givenPassword'"; $queryResult = mysql_query($myQuery); $numRows = mysql_num_rows($queryResult); if($numRows == 1){ //If the details are correct... //Reload the page and login echo "<script type = 'text/javascript'> window.location.reload() </script>"; } elseif($numRows == 0){ //Else if the details are not found //Display error accordingly echo "Details not correct!"; } mysql_close($connect); ?> The problem is, when I click the login button, it doesn't do anything. What am I missing? (The information in the database is correct) Thanks, Jake Hi there,
I've built a form that should generate an e-mail, but it's not working properly. At first the page wouldn't display at all due to a problem with the EOD tags, that's fixed and I can now see a page, but when I type something in and hit submit, it's just not doing what it's supposed to do. Like I said it's supposed to e-mail me the data and leave the form filled with the data just submitted; it's doing neither. It is however posting the info into the address bar, so something is happening at least.
here's a link to the page: http://www.remembert...hp/testform.php
here's the code:
<?php
if ($_POST['parse_var'] == "testform"){ <?php //user name and Password for authentication $username = 'username'; $password = 'password'; if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || ($_SERVER['PHP_AUTH_USER'] != $username) || ($_SERVER['PHP_AUTH_PW'] != $password)) { //The username/password are incorrect or haven't been entered so send the authentication headers header ('HTTP/1.1 401 Unauthorized'); header ('WWW-Authenticate: Basic realm= "Gator Boats" '); exit ('<h2>Gator Boats Admin</h2> Sorry, You ust enter a valid username and password ' . 'access this page.'); } ?> Every time I enter the User Name: username and Password: password it just resends the headers. Can you see what I am doing wrong? I'm trying to redirect visitors that contain broadly matched URLs. For example, redirect the visitor if their url contains: "/welcome" or "order.php" or "login.mysite/" At the same time I also want to redirect the user if they a particular User Agent. Here's what I have, but doesn't seem to be entirely working... Code: [Select] <?php //detect referrer $ref = $_SERVER['HTTP_REFERER']; $find = "order.php"; $find = "login.mysite/"; //setting the variables $linux = stripos($_SERVER['HTTP_USER_AGENT'],"Linux"); $aol = stripos($_SERVER['HTTP_USER_AGENT'],"AOL"); //detecting user agent device, os, browser, etc. if ($linux == true || $aol == true) $redirect = 1; //detect referrer elseif (preg_match($ref, $find)) $redirect = 1; //set redirects if ($redirect) { $url = "http://www.google.com"; } else { $url = "http://www.yahoo.com"; } header("Location: $url"); ?> Any help you can offer is appreciated. Thanks! Trying to run a simple program that, when submitted, stores the username and password as cookies. When clicking Submit, I get the error "HTTP Error 405 - The HTTP verb used to access this page is not allowed". If the username and password fields are left blank when submitting it's suppose to give a message to enter a username and password, but, I still get that error message. HTML form: Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Week 1 Project--Cookies</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> </head> <body> <form action="cookie1.php" method="post"> <h2 align="center">Cookies</h2> <br /> <div> <p>Enter your username and password and click "Submit":</p><br /> <p>Username:<input type="text" name="username" size="20"></p> <p>Password:<input type="text" name="password" size="20"></p> </div> <br /> <div><input type="submit" name="submit" value="Submit" /></div> <br /> <div> <input type="reset" name="Reset" value="Start Over" /> </div> </form> </body> </html> PHP file: Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Cookie File</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> </head> <body> <div> <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { setcookie('username', $_POST['username'], time() + 2592000); setcookie('password', $_POST['password'], time() + 2592000); } if(($_POST['username'] == "") || ($_POST['password'] == "")) { print "You must enter both a username and password. Press the Back button on your browser and try again."; } else if (isset($_COOKIE['username'])) { print "Welcome, " .$_COOKIE['username']; } ?> </div> </body> </html> Hello, I have this PHP and HTML code and i recently figured out, it doesn't even enter the PHP function to execute and i have no idea whats wrong
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="trashy"> <table id="RemoveItem"> <tr> <b><label for="Itemid">Enter the item ID you want to delete : </label></b> <input type="number" name="Iid"><br><br> </tr> <tr> <td></td> <td></td> <td></td> <td> <!-- <button type="button" class="button1" name="remove" type="submit" href="AdministratorPanel.php?click=1">Remove</button> --> <input id="btn-login" class="btn btn-success" style="right: 50px;" type="submit" name="remove" value="remove"> </td> </tr> </table> </form> <?php if($_SERVER["REQUEST_METHOD"] == "POST") { if(isset($_POST['remove'])) { $ido = $_GET['Iid']; $result = mysqli_query($conn, "DELETE FROM productinfo WHERE ID = '$ido'") or die ("error"); if($del) { echo "success deleting record"; } else { echo "Error deleting record"; // display error message if not delete } } } ?>
Ive tried everything and cannot get this POST to work, page comes up blank. The output of curlgetinfo() shows: Code: [Select] Array ( [url] => http://app.alliedinsurance.com/find_agent/calcpage4_1_popup.cfm?RequestTimeout=180 [content_type] => text/html; charset=UTF-8 [http_code] => 200 [header_size] => 329 [request_size] => 450 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.172622 [namelookup_time] => 0.02064 [connect_time] => 0.092116 [pretransfer_time] => 0.092244 [size_upload] => 0 [size_download] => 509 [speed_download] => 2948 [speed_upload] => 0 [download_content_length] => 0 [upload_content_length] => 0 [starttransfer_time] => 0.172563 [redirect_time] => 0 ) The whole code Im using: Code: [Select] <h2>Please Enter Zip Code</h2> <p> <form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>"> <input type="text" size="10" maxlength="10" name="zipcode" tabindex="1" value="<?php echo $_POST['zipcode'];?>" /> <input type="submit" value="Search" name="submit" tabindex="2" /> </form> <br /> <?php if(isset($_POST['submit'])) { $zipcode = $_POST['zipcode']; $userAgent = 'Mozilla/5.0 (Windows NT 6.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1'; $mercurl = "http://app.alliedinsurance.com/find_agent/calcpage4_1_popup.cfm?RequestTimeout=180"; $postcom = "City=&State=AR&ZipCode=" . urlencode($zipcode) . "&Miles=" . urlencode('20') . "&SubmitThis=Submit"; $ch = curl_init(); curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); curl_setopt($ch, CURLOPT_URL,$mercurl); curl_setopt($ch, CURLOPT_FAILONERROR, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); curl_setopt($ch, CURLOPT_TIMEOUT, 100); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_HEADER_OUT, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt'); curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt'); curl_setopt($ch, CURLOP_REFERRER, "http://app.alliedinsurance.com/find_agent/find_an_agent_popup.cfm"); curl_setopt($ch,CURLOPT_POST, 1); curl_setopt($ch,CURLOPT_POSTFIELDS,$postcom); $html = curl_exec($ch); print_r(curl_getinfo($ch)); $html = @mb_convert_encoding($html, 'HTML-ENTITIES', 'utf-8'); curl_close( $ch ); echo $html; ?> Users make entries into a form on my site which are then sent to a remote server which generates a variable length page of results for the users perusal. I want the results to be displayed on my site but I discover that iframe height is a problem so I am trying PHP in a separate file to avoid an iframe. Then maybe I can cache the result pages and display them without any height difficulties and not having to fiddle with javascript. The first PHP code I try is prevented from working and I discover that the apparent cause is the issue of fopen and fsockopen etc. being set to off by the host that I use because of security concerns: $url="http://remote_server.cgi"; foreach($_POST as $key => $value) {$url .="$key=" . urlencode($value) . "&";} $array = file($url);] The host has cURL so I try that but the form entries are not being accepted as they are with a direct post from the form: $URL="http://remote_server.cgi"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $URL); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST); curl_exec ($ch); curl_close ($ch); In case useragent is a problem at the remote server, I added: curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13'); I know all entries are received by the separate file by using: print_r($_POST); But the remote server still says "Error in form found. You are not authorized etc. etc... " Apparently the post data is not being sent like the form sends it. Any suggestions? As the title says session, post and get are not working. This is what i use to initialize them. For get just switch session with get. Code: [Select] foreach ($row as $val) { $_SESSION[$rowcount] = $val; // echo "<td>$val</td>\n"; $rowcount=$rowcount+1; } when i was using session i would check to make sure that they were working with a couple of these lines in the same php document. Code: [Select] echo "Session row 1 = ".$_SESSION[0]."<br />"; echo "Session row 2 = ".$_SESSION[1]."<br />"; then on the next page where I was trying to receive the variables i was using this just to start off with and make sure i was getting the variables. Code: [Select] session_start(); if(!isset($_SESSION[1])){ echo "help1";}else{$var=$_SESSION[1]; } echo $_SESSION[1]; echo $var; if i switch to post and get i get the same results. if there is an easier way to pass variables between pages id love to hear them Its just keep saying error on line 1 if($_POST["pass"] == $_POST["repass"]){ arepasssame = $_POST[pass]; } Hey guys! I have a site in flash that talks to a PHP file... the flash site has some forms and those variables are sent to php. I am having some trouble with this security code I implemented on php: // Host name from where the form is authorized // to be posted from: $authHosts = array("mysite.com"); // Where have we been posted from? $fromArray = parse_url(strtolower($_SERVER['HTTP_REFERER'])); // Test to see if the $fromArray used www to get here. $wwwUsed = strpos($fromArray['host'], "www."); // Make sure the form was posted from an approved host name. if(!in_array(($wwwUsed === false ? $fromArray['host'] : substr(stristr($fromArray['host'], '.'), 1)), $authHosts)){ //logBadRequest(); header("HTTP/1.0 403 Forbidden"); exit; } On IE and Google Chrome the site works fine! but on FireFox Flash pops up an error message telling me that the php file has a sequence error. Any ideas or suggestions on how to fix this? Thanks in advance! Cheers. How do I only redirect the page when index.php is present? |