PHP - How To Send Http Get Request To The Webservice End Point?
Hello,
If i am not posting this question at right location then i apologize for it. My problem is: I need to send HTTP get request to the webservice end point which must include the following http headers: GET / HTTP/1.1 Host: apis.live.net Accept: application/json Content-Type: application/json Authorization: WRAP access_token=AuthToken (here AuthToken is the Access Token String) Note: I am using OAuth for getting an access Token but for getting contents I need to send an HTTP get request. Any kind of help will be appreciated. Thanks Similar TutorialsHi, I don't know very much about php. I don't know any at all, actually. I play a game called Roblox where you get to use the programming languange, "Lua" to script your own games. What I am requesting has been done before on this game, but I only know Lua. I was also told PHP cURL is needed. Anyways, let me get to the point. I am essentially trying to create a system on my webserver (You can send HTTP Requests to external sites in this game via script) that will essentially log into an account on Roblox, to perform a task. My current idea would be to have the Lua script send a request to my webserver with an generated code that would access the username and password of my roblox account (Which would be on the webserver). It would then perform a task. Is this a good way to go about this? If not, I am open to suggestions. If you can find the time to actually help me set this up on my webserver, I would greatly appreciate it! I'm also sorry if this is the wrong place for this post, I'm new here. I'm trying to integrate w/ a few APIs, and getting started is causing me fits. I'm using PHP locally to add common headers and as a contact form, and those are working fine. The Code: <?php require('HTTP/Request.php'); $url = "http://example.com"; $request =& new HTTP_Request($url); $request->sendRequest(); $response = $request->getResponseBody(); ?> The Result: Warning: require(HTTP/Request.php) [function.require]: failed to open stream: No such file or directory in /home/stodgy5/public_html/trackstart/start.php on line 3 Warning: require(HTTP/Request.php) [function.require]: failed to open stream: No such file or directory in /home/stodgy5/public_html/trackstart/start.php on line 3 Fatal error: require() [function.require]: Failed opening required 'HTTP/Request.php' (include_path='.:/usr/lib/php:/usr/local/lib/php:/home/stodgy5/php') in /home/stodgy5/public_html/trackstart/start.php on line 3 I'm assuming this is a directory issue, as my cPanel says Pear is installed. Any advice? Hi Guys,
Total PHP Noob here. I’ve run into a brick-wall and would appreciate some words of wisdom. I can do this with a browser: http://86.60.161.24 // will echo hello World I can’t do this with my server: <?php $url = 'http://86.60.161.24'; $contents = file_get_contents($url); echo ($contents); ?> It looks like the server-side HTTP -request never “touches” my Arduino-chip. No network activity detected. Obviously there is going to be a lot more data transfer happening but I need to solve this issue first. Is there anything I can do to make this work? Any and all input greatly appreciated. Cheers!!
It seems to me that this should be easy, but I can't find it in the manual or the on the web, and the values in $_SERVER don't suggest anything. Context: script A loads script B using HTTPS. Now script B has to load resources (images, style sheets, etc). Browsers often object to HTTP references from a script run by an HTTPS request, so script B should generate URLs that use HTTPS. Thus it has to know that it was loaded with HTTPS. I can do this by brute force if I have to (defining a "protocol" constant in the script itself), but I'd rather make the test automatic. 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 total beginner and don't know first thing about php, but still trying to figure this out. So what I am trying to achieve is, send a http request from a software to my website with a ticket number, is it possible in php to receive that request and show it on a different webpage of the same site? It would be helpful if you can point me to some related articles. Hey guys, every now and then some of my scripts that consistently access headers seem to fail to open the stream. I'm running about 1-50 of these shell scripts at once, but it doesn't seem to make a difference weather I have 1 or 50 scripts open at once. I was wondering if there was a way to tell PHP: Alright, so it failed to open the http stream, I want you to try again until it works. I just want it to try again until it works, because when it doesn't load certain headers, things go very wrong. Thanks. Here's an example of the code where the problem occurs: $Attack = file_get_contents($MobLink."attack?user_id=".$UserID."&target_id=".$TargetID."&auth_key=".$AuthKey); xml_parse_into_struct($iP=xml_parser_create(), $Attack, $iS, $iX);xml_parser_free($iP); echo "$i :.:.: ".strip_tags($iS[$iX['MESSAGE'][0]]['value'])." :.:.:\n\n"; First thanks for any help that you can provide. I am somewhat new to PHP and this is the first "Web Service" I have had to create. THE GOAL: I need to pull XML data from another server. This company's API is setup so that you must give an IP and so you can only pull data from server to server instead of client to server. The data is pulled from the API using HTTP requests...very similar to YQL. (in essence the structured query is located in the URL). This API also requires that my server only ping's their server every 10-15 mins, in order to cut down on server requests. The logical thought in my head was to setup: a cron job to run a PHP script every 10 mins. The PHP scripts would then do the following: 1. Make the HTTP request 2. Open an existing file or create one (on my server) 3. Take the returned XML data from the API and write to the newly opened file. 4. Convert that XML to JSON. 5. Save the JSON 6. Cache the JSON file 7. STOP My thought was to use curl and fopen for the first 3 steps. I found a basic script that will do this on PHP.net (as shown below). After that I am pretty much lost on how to proceed. Code: [Select] <?php $ch = curl_init("http://www.example.com/"); $fp = fopen("example_homepage.txt", "w"); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_exec($ch); curl_close($ch); fclose($fp); ?> I would REALLY appreciate any help on this. Also, if you have the time to please comment and explain what you are doing in any code examples and why....that would HELP out a lot. I truly want to learn not just grab a snippet and run. So, your comments are vital for me. thank!!! Quick question for you guys. I am collecting payment data for a product. Is it possible to send data from my form via http directly into another payment form via the post http headers? So say if i had all the details payment info and address info and i matched my form exactly to theirs. Is it possible to write a php script to send the data from my form directly to another websites form to make an order, say amazon or a big site like this? ?first_name=samuel&last_name=east&action=Submit Any Help? Thanks hi everyone, can you please kindly check my code for error Code: [Select] $xmltosend = "<?xml version='1.0'?>\r\n". "<soap:Envelope xmlns:soap='http://www.w3.org/2001/12/soap-envelope' soap:encodingStyle='http://www.w3.org/2001/12/soap-encoding'>\r\n". "<soap:Body xmlns:m='https://www.trustwave.com/'>\r\n". "<request>\n". "<authentication>\n". "<username>username</username>\n". "<password>password</password>\n". "</authentication>\n". "<operation>getResellerProducts</operation>\n". "<params>\n". "<int>12345</int>\n". "</params>\n". "</request>\n". "</soap:Envelope>\n"; $reqheader = "POST /index.php HTTP/1.1\r\n". "Host:www.trustwave.com\r\n". "Content-Type: application/soap+xml; charset=utf-8\r\n". "Content-Length: ".strlen($xmltosend) ."\r\n\r\n"; $url = 'https://testapi.ssl.trustwave.com/3.0/'; // fake - obviosly! $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POSTFIELDS, $xmltosend); curl_setopt($ch, CURLOPT_POST, true); // what to post curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $reqheader); curl_setopt($ch, CURLOPT_USERPWD, "username:password"); $result = curl_exec($ch); curl_close($ch); print $result; im getting this error Code: [Select] Authorization Required This server could not verify that you are authorized to access the document requested. Either you supplied the wrong credentials (e.g., bad password), or your browser doesn't understand how to supply the credentials required. anyone pleeeaassseee...!!! tia I want to be able to send a GET request to another website for example i want to be able to run this http://www.mywebsite.com/blog.php?clear_cache= using curl but when i use curl the website is loaded into my own heres my code Code: [Select] $curl = curl_init(); $json_url = $_SESSION['blog_base'] . 'blog.php?empty_cache='; curl_setopt ($curl, CURLOPT_URL, "$json_url"); $ANSWER=curl_exec ($curl); curl_close ($curl); hi there - first attempt at programming in PHP so please bear with my novice attempts (not much programming experience in any languege really) i am building a site which hosts mp3s. I have MySQL database with one of the fields contating descriptive keywords for the tracks (such as slow, chilled, intense etc) i have created an html page with search form that send data to php file which runs a query of the keywords field - and all works fine now i want that in addition to the search form (with an input text box for the search criteria and the submit button) i will have a 'cloud' of key words - clickable links - that will send the data to the PHP query file (clicking on slow will search for tracks described with 'slow' and so on) - any ideas how do send data by clicking on a link? my html form is: Code: [Select] <body bgcolor="white"> <form action="test3.php" target="main" method="post"> <input type="text" name="searchkeywords" size=100><br> <input type="submit" value="Search"> <input name="searchkeywords" value="slow" type="submit"> </form> <DIV align="center" style="left : 240px; position : absolute; top : 100px;"><iframe src ="test3.php" width="1000" height="800" name="main" frameborder="2" scrolling="no"> <p>Your browser does not support iframes.</p> </iframe></DIV> </body> my php query file is: Code: [Select] <?php $con = mysql_connect("localhost","root","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("test", $con); $result = mysql_query("SELECT * FROM music WHERE keywords LIKE '%$_POST[searchkeywords]%'"); $txt1='<A HREF="/audioplayer-standalone/'; $txt2='" ><IMG src="images/misc_23.png" width="32" height="32" align="left" border="0"></A>'; $txt3='<script language="JavaScript" src="/audioplayer-standalone/audio-player.js"></script><object type="application/x-shockwave-flash" data="/audioplayer-standalone/player.swf" id="audioplayer'; $txt4='" height="24" width="290"><param name="movie" value="/audioplayer-standalone/player.swf"><param name="FlashVars" value="playerID=audioplayer'; $txt5='&soundFile=/audioplayer-standalone/'; $txt6='"><param name="quality" value="high"><param name="menu" value="false"><param name="wmode" value="transparent"> </object>'; echo "<table border='1'> <tr> <th width='220' align='left'>Track Name</th> <th width='220' align='left'>Artist</th> <th width='220' align='left'>Description</th> <th></th> <th></th> </tr>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['track'] . "</td>"; echo "<td>" . $row['artist'] . "</td>"; echo "<td>" . $row['description'] . "</td>"; echo "<td>" . $txt1.$row['filename'].$txt2 . "</td>"; echo "<td>" . $txt3.$row['id'].$txt4.$row['id'].$txt5.$row['filename'].$txt6 ."</td>"; echo "</tr>"; } echo "</table>"; // some code mysql_close($con); ?> 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, I would like to send a value in a link and request it back in ajax and set it as a variable in php in the same page, can anyone help me here? thanks Hey! I am trying to get a database table of users but am running into the error: Warning: file_get_contents(http://protege-ontology-editor-knowledge-acquisition-system.136.n4.nabble.com/template/NamlServlet.jtp?macro=user_nodes&user=68583) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 500 in get_user_from_parameter(nabble:utilities.naml:890) - <n.get_user_from_parameter.as_user_page.do/> - public v in C:\xampp\htdocs\website4js\stanford\loadUsernames.php on line 32 I have looked it up and it may be a security thing...The urls I am getting are http://protege-ontology-editor-knowledge-acquisition-system.136.n4.nabble.com/template/NamlServlet.jtp?macro=user_nodes&user=68583 but the error adds an nodes& part that screws it up. Any way around this? Code: [Select] <?PHP $maxPage = 0; $mainPage = "http://protege-ontology-editor-knowledge-acquisition-system.136.n4.nabble.com/template/NamlServlet.jtp?macro=app_people&node=136"; $mainContent = file_get_contents($mainPage); $pattern = "/(?<=\"Page )\d\d+/"; preg_match_all($pattern, $mainContent, $pageNumb); //find the max page for($i=0;$i<sizeof($pageNumb[0]);$i++) { if($pageNumb[0][$i] > $maxPage) { $maxPage = $pageNumb[0][$i]; } } //echo('Max page is: '.$maxPage.'\n'); //Get an array of all the pages $pages = array(); for($i=1;$i<$maxPage;$i++) { $pages[$i] = "http://protege-ontology-editor-knowledge-acquisition-system.136.n4.nabble.com/template/NamlServlet.jtp?macro=app_people&node=136&i=".($i*20); } //print_r($userPages); //Get personal page urls and add to MySQL mysql_connect("localhost" , "root") or die("Cant connect"); mysql_select_db("protegeusers") or die("Cant find database"); foreach($pages as $url) { $urlContents = file_get_contents($url); $pattern = "/http:\/\/protege-ontology-editor-knowledge-acquisition-system\.136\.n4\.nabble\.com\/template\/NamlServlet\.jtp\?macro=.+;user=\d+/"; preg_match_all($pattern, $urlContents, $personalPage); foreach($personalPage as $user) { for($i=0; $i<sizeof($user);$i++) { [color=green]$userContents = file_get_contents($user[$i]);[/color] $pattern1 = "/user\/SendEmail\.jtp\?type=user.+;user=\d+/"; $pattern2 = "/(?<=\">Send Email to ).+(?=<)/"; preg_match_all($pattern1, $userContents, $userEmail); preg_match_all($pattern2, $userContents, $username); [color=green]print_r($username); print_r($email);[/color] //$query = "INSERT INTO users (username, userurl) values ('$userName','$userUrl')"; //mysql_query($query); } } } ?> I am trying to figure how to code around this. I have a DOM scraper function that pulls urls from my database, opens the page, scrapes the data, and then moves onto the next URL to scrape. my issue is that if the page fails to load the script bombs and I have to restart it again. Trying to figure out how if the Code: [Select] $html->find('div[class="itemHeader address"]') as $div fails to open the page it just skips the DOM inspection. Here is my error... Failed to open stream: HTTP Request failed. Here is where I am at with my script.... Code: [Select] mysql_select_db("scraped") or die(mysql_error()); $result = mysql_query("SELECT PKEY, URL, HASSCRAPED, SHOULDSCRAPE FROM CRAWLED WHERE SHOULDSCRAPE ='1' AND HASSCRAPED = '0'") or die(mysql_error()); while($row = mysql_fetch_array( $result )) { mysql_query("UPDATE CRAWLED SET CRAWLED.HASSCRAPED = '1' WHERE CRAWLED.URL = '" . $row['URL'] . "'"); $html = file_get_html($row['URL']); foreach($html->find('div[class="itemHeader address"]') as $div) { foreach($div->find('a') as $element){ $CleanData = CleanData($element->innertext); if (strlen($CleanData[0]) > 5){ mysql_query("INSERT INTO SCRAPED (ADDR1, CITY, STATE, ZIP, URL, DATE) VALUES ('" . $CleanData[0] . "','" . $CleanData[1] . "','" . $CleanData[2] . "','" . $CleanData[3] . "','". $row['URL'] . "','". date( 'Y-m-d H:i:s ' ) ."')"); } } } $html->clear(); unset($html); unset($CleanData); } function CleanData($data) { $NewData = trim($data); $NewData = str_replace("<em>", "", $NewData); $AddrCityStateZip = explode("</em>",$NewData); $CityStateZip = explode(",",$AddrCityStateZip[1]); $StateZip = explode(' ',$CityStateZip[1]); $NewDataArray = array ($AddrCityStateZip[0], $CityStateZip[0], $StateZip[1], $StateZip[2]); return $NewDataArray; unset($NewData); unset($AddrCityStateZip); unset($CityStateZip); unset($StateZip); } mysql_close($link); echo 'Scraping has compleated without error'; 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"]; ?>
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> 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> |