Search Results

Search found 242 results on 10 pages for 'urlencode'.

Page 9/10 | < Previous Page | 5 6 7 8 9 10  | Next Page >

  • How do I migrate from a basic plaintext password authentication to an OAuth based system?

    - by different
    Hello, Found out today that Twitter will be discontinuing its basic authentication for its API; the push is now towards OAuth but I don’t have a clue as to how to use it or whether it’s the right path for me. All I want to be able to do is post a tweet linking to the most recently published post when I hit publish. Currently I’m sending the login credentials for my Twitter account as plaintext, which I realise isn’t that secure but as my site is fairly small it isn’t an issue at least for now. I’m using this basic PHP code: $status = urlencode(stripslashes(urldecode("Test tweet"))); $tweetUrl = 'http://www.twitter.com/statuses/update.xml'; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "$tweetUrl"); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, "status=$status"); curl_setopt($curl, CURLOPT_USERPWD, "$username:$password"); $result = curl_exec($curl); $resultArray = curl_getinfo($curl); if ($resultArray['http_code'] == 200) { curl_close($curl); $this->redirect(""); } else { curl_close($curl); echo 'Could not post to Twitter. Please go back and try again.'; } How do I move from this to an OAuth system? Do I need to?

    Read the article

  • twitter streaming api instead of search api

    - by user1711576
    I am using twitters search API to view all the tweets that use a particular hashtag I want to view. However, I want to use the stream function, so, I only get recent ones, and so, I can then store them. <?php global $total, $hashtag; $hashtag = $_POST['hash']; $total = 0; function getTweets($hash_tag, $page) { global $total, $hashtag; $url = 'http://search.twitter.com/search.json?q='.urlencode($hash_tag).'&'; $url .= 'page='.$page; $ch = curl_init($url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE); $json = curl_exec ($ch); curl_close ($ch); echo "<pre>"; $json_decode = json_decode($json); print_r($json_decode->results); $json_decode = json_decode($json); $total += count($json_decode->results); if($json_decode->next_page){ $temp = explode("&",$json_decode->next_page); $p = explode("=",$temp[0]); getTweets($hashtag,$p[1]); } } getTweets($hashtag,1); echo $total; ?> The above code is what I have been using to search for the tweets I want. What do I need to do to change it so I can stream the tweets instead? I know I would have to use the stream url https://api.twitter.com/1.1/search/tweets.json , but what do I need to change after that is where I don't know what to do. Obviously, I know I'll need to write the database sql but I want to just capture the stream first and view it. How would I do this? Is the code I have been using not any good for just capturing the stream?

    Read the article

  • Upload .txt and keep formating

    - by s2xi
    I have been trying to upload a .txt to my server via a simple php script I made. Everything seems to uploaded correctly, if I open the .txt in Dreamweaver I can see all the formatting is still in tact with spaces and paragraph breaks. The problem I have is when I try to open that file with PHP and import the contents onto my site. I'm not using an editor right now, just a simple div where the contents are echoed. I don't have much experience with uploading/downloading using PHP. Am I not using a command to handle the file contents and keep the initial formatting? In the end I want the user to upload a file, and have PHP read the file and extract certain elements from it based on the number of spaces between paragraph breaks and such. I was able to actually echo the .txt using URLENCODE() which kept the formatting and made all my spaces +'s. Thats the closes I got, but the original file isn't uploaded in the format so I can't do a count for +'s and select x characters after the last +. Hmmm, if someone knows of a script already available that can do this or similar to with me just tweaking that would be awesome.

    Read the article

  • Failed to load url in Dom Document?

    - by Lakhan
    im trying to get latitude and longtitude from google map by giving address. But its giving error.when i directly copy url to browser url bar.its giving correct result.If anybody know the answer .Plz reply. Thanx in advance Here is my code. <?php $key = '[AIzaSyAoPgQlfKsBKQcBGB01cl8KmiPee3SmpU0]'; $opt = array ( 'address' => urlencode('Kolkata,India, ON') , 'output' => 'xml' ); $url = 'http://maps.google.com/maps/geo?q='.$opt['address'].'&output='.$opt['output'].'&oe=utf8&key='.$key; $dom = new DOMDocument(); $dom->load($url); $xpath = new DomXPath($dom); $xpath->registerNamespace('ge', 'http://earth.google.com/kml/2.0'); $statusCode = $xpath->query('//ge:Status/ge:code'); if ($statusCode->item(0)->nodeValue == '200') { $pointStr = $xpath->query('//ge:coordinates'); $point = explode(",", $pointStr->item(0)->nodeValue); $lat = $point[1]; $lon = $point[0]; echo '<pre>'; echo 'Lat: '.$lat.', Lon: '.$lon; echo '</pre>'; } ?> Following error has occured: Warning: DOMDocument::load(http://maps.google.com/maps/geo? q=Kolkata%252CIndia%252C%2BON&output=xml&oe=utf8&key=%5BAIzaSyAoPgQlfKsBKQcBGB01cl8KmiPee3SmpU0%5D) [domdocument.load]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in C:\xampp\htdocs\draw\draw.php on line 19 Warning: DOMDocument::load() [domdocument.load]: I/O warning : failed to load external entity "http://maps.google.com/maps/geo?q=Kolkata%252CIndia%252C%2BON&output=xml&oe=utf8&key=%5BAIzaSyAoPgQlfKsBKQcBGB01cl8KmiPee3SmpU0%5D" in C:\xampp\htdocs\draw\draw.php on line 19 Notice: Trying to get property of non-object in C:\xampp\htdocs\draw\draw.php on line 26

    Read the article

  • Problem with RSA-encrypting a string in PHP and passing it to .NET service

    - by jonasaxelsson
    I need to call a web service that requires a login url containing an RSA encrypted, base_64 encoded and url-encoded login data. I don't have a formal php training, but even for me it seems like an easy task, however when calling the service I get an 'Invalid Format' response. What am I doing wrong and is there another way to come up with the encrypted string? Code example below. Thank you for your help! http://www.edsko.net/misc/ for encryption. $message = '?id=112233&param1=hello&[email protected]&name=Name'; $keyLength = '2048'; $exponent = '65537'; $modulus = '837366556729991345239927764652........'; $encryptedData = rsa_encrypt($message, $exponent, $modulus, $keyLength); $data = urlencode(base64_encode($encryptedData)); $loginurl = 'http://www.somedomain.com/LoginWB.aspx?Id=9876&Data='.$data; echo '<iframe src="'.$loginurl.'" width="570px" height="800px">'; echo '</iframe>'; ?

    Read the article

  • Sample twitter App

    - by Jack
    I am now running my code on a web hosting service http://xtreemhost.com/ <?php function updateTwitter($status) { $username = 'xxxxxx'; $password = 'xxxx'; $url = 'http://twitter.com/statuses/update.xml'; $postargs = 'status='.urlencode($status); $responseInfo=array(); $ch = curl_init($url); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_POST, true); // Give CURL the arguments in the POST curl_setopt ($ch, CURLOPT_POSTFIELDS, $postargs); // Set the username and password in the CURL call curl_setopt($ch, CURLOPT_USERPWD, $username.':'.$password); // Set some cur flags (not too important) $response = curl_exec($ch); if($response === false) { echo 'Curl error: ' . curl_error($ch); } else { echo 'Operation completed without any errors<br/>'; } // Get information about the response $responseInfo=curl_getinfo($ch); // Close the CURL connection curl_close($ch); // Make sure we received a response from Twitter if(intval($responseInfo['http_code'])==200){ // Display the response from Twitter echo $response; }else{ // Something went wrong echo "Error: " . $responseInfo['http_code']; } curl_close($ch); } updateTwitter("Just finished a sweet tutorial on http://brandontreb.com"); ?> I get the following error now Curl error: Couldn't resolve host 'api.twitter.com' Error: 0 Please somebody solve my problem

    Read the article

  • How to get my list of rows from database to show while using Zend-Paginator

    - by Matto
    I'm fairly new to the world of Zend-Framework, and have taken over a site that is in zend-framework. There is a bug on one of the pages right now and I can not figure it out. I think it has something to do with Zend Paginator, but not sure. This is the code in the controller for the section I am having a problem with: $currentPage = $this->_getParam('page'); $numWebsitesFullOnline = $websites->getWebsitesFullOnline(); $select = $websites->select(); $select->setIntegrityCheck(false); $select->from(array('w' => 'websites'), array('id', 'online', 'kw_adjective', 'kw_name', 'kw_location', 'url', 'email', 'address', 'ftp_server', 'ftp_username', 'ftp_password', 'ftp_folder', 'phone_number', 'indexed', 'youtube_position', 'twitter_user', 'facebook_id', 'video_made', 'image1_id', 'image2_id', 'image3_id', 'bg_color', 'dark_color', 'light_color', 'links_color', 'text_color', 'google_account', 'ganalytics', 'gmaps_status', 'google_position', 'gmap_position', 'hp1', 'hp2', 'hp3', 'hp4', 'hp5', 'hp6', 'hp7', 'hp8', 'hp9', 'hp10', 'about1_id', 'about2_id', 'about3_id', 'tip1_id', 'tip2_id', 'tip3_id', 'contact_texts_id', 'quote_texts_id', 'demographics_id')) ->join(array('d' => 'demographics'), 'w.demographics_id = d.id', array('total_population')) ->order(array('total_population DESC', 'kw_location')); $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select)); $paginator->setItemCountPerPage(50); $paginator->setCurrentPageNumber($currentPage); $paginator->setPageRange(($paginator->getTotalItemCount() / 50) + 1); $this->view->paginator = $paginator; $numWebsitesOnline = $websites->getWebsitesOnline(); On the php page I have this code to call the websites that are in the database to a list: <p class="red"> Websites online: <?php echo $this->numOnline; ?> </p> <?php print_r(count($this->paginator)); ?> <?php if(count($this->paginator)): ?> <table class="table-list"> <?php foreach($this->paginator as $item): ?> <tr> <?php if($this->userIsAllowedAction('websites', 'reload')): ?> <td class="center noborder w30"> <img class="hidden" src="<?php echo $this->baseUrl() . '/images/loader.gif' ?>" alt="Loading..."/><a class="reload" title="refresh" href="<?php echo $this->baseUrl(); ?>/utils/ui/refresh-website.php" rel="<?php echo urlencode('http://' . $item['url'] . '/install.php'); ?>,<?php echo urlencode($item['ftp_server']); ?>,<?php echo $item['ftp_username']; ?>,<?php echo $item['ftp_password']; ?>,<?php echo $item['ftp_folder']; ?>,<?php echo $this->baseUrl(); ?>,<?php echo $item['id']; ?>"><img src="<?php echo $this->baseUrl(); ?>/images/icon-refresh.png" alt="Refresh"/></a> </td> <?php endif; ?> <td class="center noborder w30"> <?php if($this->userIsAllowedAction('websites', 'edit')): ?><a title="Edit" href="<?php echo $this->url(array('controller' => 'websites', 'action' => 'edit', 'id' => $item['id'])); ?>"><img src="<?php echo $this->baseUrl(); ?>/images/icon-edit.png" alt="Edit"/></a><?php endif; ?> </td> <td class="center noborder w30"> <?php if($this->userIsAllowedAction('websites', 'remove')): ?><a title="Remove" href="<?php echo $this->url(array('controller' => 'websites', 'action' => 'remove', 'id' => $item['id'])); ?>"><img src="<?php echo $this->baseUrl(); ?>/images/icon-delete.png" alt="Remove"/></a><?php endif; ?> </td> <td> <?php if($item['online']): ?> <span class="hidden"><?php echo trim($this->escape($item['kw_adjective'] . $item['kw_name'])); ?></span><a class="goto-website" href="http://<?php echo $item['url']; ?>" target="_blank"><?php echo $this->escape($item['kw_location']); ?></a> <?php else: ?> <?php echo $this->escape($item['kw_location']); ?> <?php endif; ?> </td> <td class="center population"> <?php if($item['total_population'] >= 0) echo $item['total_population']; ?> </td> <td class="center"> <?php if(!empty($item['url'])): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if(!empty($item['email'])): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if($item['demographics_id']): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if($item['hp1'] && $item['hp2'] && $item['hp3'] && $item['hp4'] && $item['hp5'] && $item['hp6'] && $item['hp7'] && $item['hp8'] && $item['hp9'] && $item['hp10'] && $item['about1_id'] && $item['about2_id'] && $item['about3_id'] && $item['tip1_id'] && $item['tip2_id'] && $item['tip3_id'] && $item['contact_texts_id'] && $item['quote_texts_id']): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if(file_exists($_SERVER['DOCUMENT_ROOT'] . $this->baseUrl() . Zend_Registry::get('assets_base_path') . '/' . $item['id'] . '/header.jpg')): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if(($item['bg_color'] != '' && $item['bg_color'] != 'e6e6e6') || ($item['dark_color'] != '' && $item['dark_color'] != '003e75') || ($item['light_color'] != '' && $item['light_color'] != '3073ad') || ($item['links_color'] != '' && $item['links_color'] != '255593') || ($item['text_color'] != '' && $item['text_color'] != '4f4f4f')): ?> <img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/> <?php endif; ?> </td> <td class="center"> <?php if($item['image1_id'] && $item['image2_id'] && $item['image3_id']): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if(!empty($item['twitter_user'])): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if(!empty($item['facebook_id'])): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if(!empty($item['phone_number'])): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if($item['google_account']): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if($item['video_made']): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if($item['youtube_position']) { echo $item['youtube_position']; }; ?> </td> <td class="center"> <?php if(!empty($item['address'])): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if($item['gmaps_status'] == 1): ?><img src="<?php echo $this->baseUrl(); ?>/images/icon-gmapspending.png" alt="Pending"/><?php elseif($item['gmaps_status'] == 2): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if(!empty($item['ganalytics'])): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if($item['online']): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark_red.png" alt="Online!"/><?php endif; ?> </td> <td class="center"> <?php if($item['indexed']): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark_red.png" alt="Online!"/><?php endif; ?> </td> <td class="center"> <?php if($item['gmap_position']) { echo $item['gmap_position']; }; ?> </td> <td class="center"> <?php if($item['google_position']) { echo $item['google_position']; }; ?> </td> </tr> <?php endforeach; ?> </table> <?php endif; ?> The print_r(count($this-paginator)); line is returning "0", and the $this-numOnline; line is returning 1. So it sees that there is one row in the websites table of the database, but it is not returning anything to page and listing out the rows in the websites table. Not sure if this is the paginator that is causing this cause it is returning 0 or something else I don't know about.

    Read the article

  • Building a plug-in for Windows Live Writer

    - by mbcrump
    This tutorial will show you how to build a plug-in for Windows Live Writer. Windows Live Writer is a blogging tool that Microsoft provides for free. It includes an open API for .NET developers to create custom plug-ins. In this tutorial, I will show you how easy it is to build one. Open VS2008 or VS2010 and create a new project. Set the target framework to 2.0, Application Type to Class Library and give it a name. In this tutorial, we are going to create a plug-in that generates a twitter message with your blog post name and a TinyUrl link to the blog post.  It will do all of this automatically after you publish your post. Once, we have a new projected created. We need to setup the references. Add a reference to the WindowsLive.Writer.Api.dll located in the C:\Program Files (x86)\Windows Live\Writer\ folder, if you are using X64 version of Windows. You will also need to add a reference to System.Windows.Forms System.Web from the .NET tab as well. Once that is complete, add your “using” statements so that it looks like whats shown below: Live Writer Plug-In "Using" using System; using System.Collections.Generic; using System.Text; using WindowsLive.Writer.Api; using System.Web; Now, we are going to setup some build events to make it easier to test our custom class. Go into the Properties of your project and select Build Events, click edit the Post-build and copy/paste the following line: XCOPY /D /Y /R "$(TargetPath)" "C:\Program Files (x86)\Windows Live\Writer\Plugins\" Your screen should look like the one pictured below: Next, we are going to launch an external program on debug. Click the debug tab and enter C:\Program Files (x86)\Windows Live\Writer\WindowsLiveWriter.exe Your screen should look like the one pictured below:   Now we have a blank project and we need to add some code. We start with adding the attributes for the Live Writer Plugin. Before we get started creating the Attributes, we need to create a GUID. This GUID will uniquely identity our plug-in. So, to create a GUID follow the steps in VS2008/2010. Click Tools from the VS Menu ->Create GUID It will generate a GUID like the one listed below: GUID <Guid("56ED8A2C-F216-420D-91A1-F7541495DBDA")> We only want what’s inside the quotes, so your final product should be: "56ED8A2C-F216-420D-91A1-F7541495DBDA". Go ahead and paste this snipped into your class just above the public class. Live Writer Plug-In Attributes [WriterPlugin("56ED8A2C-F216-420D-91A1-F7541495DBDA",    "Generate Twitter Message",    Description = "After your new post has been published, this plug-in will attempt to generate a Twitter status messsage with the Title and TinyUrl link.",    HasEditableOptions = false,    Name = "Generate Twitter Message",    PublisherUrl = "http://michaelcrump.net")] [InsertableContentSource("Generate Twitter Message")] So far, it should look like the following: Next, we need to implement the PublishNotifcationHook class and override the OnPostPublish. I’m not going to dive into what the code is doing as you should be able to follow pretty easily. The code below is the entire code used in the project. PublishNotificationHook public class Class1 :  PublishNotificationHook  {      public override void OnPostPublish(System.Windows.Forms.IWin32Window dialogOwner, IProperties properties, IPublishingContext publishingContext, bool publish)      {          if (!publish) return;          if (string.IsNullOrEmpty(publishingContext.PostInfo.Permalink))          {              PluginDiagnostics.LogError("Live Tweet didn't execute, due to blank permalink");          }          else          {                var strBlogName = HttpUtility.UrlEncode("#blogged : " + publishingContext.PostInfo.Title);  //Blog Post Title              var strUrlFinal = getTinyUrl(publishingContext.PostInfo.Permalink); //Blog Permalink URL Converted to TinyURL              System.Diagnostics.Process.Start("http://twitter.com/home?status=" + strBlogName + strUrlFinal);            }      } We are going to go ahead and create a method to create the short url (tinyurl). TinyURL Helper Method private static string getTinyUrl(string url) {     var cmpUrl = System.Globalization.CultureInfo.InvariantCulture.CompareInfo;     if (!cmpUrl.IsPrefix(url, "http://tinyurl.com"))     {         var address = "http://tinyurl.com/api-create.php?url=" + url;         var client = new System.Net.WebClient();         return (client.DownloadString(address));     }     return (url); } Go ahead and build your project, it should have copied the .DLL into the Windows Live Writer Plugin Directory. If it did not, then you will want to check your configuration. Once that is complete, open Windows Live Writer and select Tools-> Options-> Plug-ins and enable your plug-in that you just created. Your screen should look like the one pictured below: Go ahead and click OK and publish your blog post. You should get a pop-up with the following: Hit OK and It should open a Twitter and either ask for a login or fill in your status as shown below:   That should do it, you can do so many other things with the API. I suggest that if you want to build something really useful consult the MSDN pages. This plug-in that I created was perfect for what I needed and I hope someone finds it useful.

    Read the article

  • Handling Errors from HttpWebRequest.GetResponse

    - by Jason
    Hey experts - I'm having a ridiculous time trying to get an SMS API working (ZeepMobile, if you're interested) with .NET... I've been around .NET for a few years, but with all this social networking and API stuff, I need to get into the HttpWebRequest a bit. I'm new at it, but not completely new; I was able to hook up my site to Twitter without too much fuss (ie, I was able to modify someone's code to work for me). Anyways, the way their API works is to send an SMS message, you send them a POST and they respond back to you. I can send it just fine, but every time I do, rather than echo back something helpful to figure out what the error is, I get the Yellow Error Page Of Death (YEPOD) saying something to the effect of "The remote server returned an error: (400) Bad Request." This occurs on my line: '...creation of httpwebrequest here...' Dim myWebResponse As WebResponse myWebResponse = request.GetResponse() '<--- error line Is there any way to simply receive the error from the server rather than have the webserver throw an exception and give me the YEPOD? Or better yet, can anyone post a working example of their Zeep code? :) Thanks! EDIT: Here's my whole code block: Public Shared Function SendTextMessage(ByVal username As String, _ ByVal txt As String) As String Dim content As String = "user_id=" + _ username + "&body=" + Current.Server.UrlEncode(txt) Dim httpDate As String = DateTime.Now.ToString("r") Dim canonicalString As String = API_KEY & httpDate & content Dim encoding As New System.Text.UTF8Encoding Dim hmacSha As New HMACSHA1(encoding.GetBytes(SECRET_ACCESS_KEY)) Dim hash() As Byte = hmacSha.ComputeHash(encoding.GetBytes(canonicalString)) Dim b64 As String = Convert.ToBase64String(hash) 'connect with zeep' Dim request As HttpWebRequest = CType(WebRequest.Create(_ "https://api.zeepmobile.com/messaging/2008-07-14/send_message"), HttpWebRequest) request.Method = "POST" request.ServicePoint.Expect100Continue = False ' set the authorization levels' request.Headers.Add("Authorization", "Zeep " & API_KEY & ":" & b64) request.ContentType = "application/x-www-form-urlencoded" request.ContentLength = content.Length ' set up and write to stream' Dim reqStream As New StreamWriter(request.GetRequestStream()) reqStream.Write(content) reqStream.Close() Dim msg As String = "" msg = reqStream.ToString Dim myWebResponse As WebResponse Dim myResponseStream As Stream Dim myStreamReader As StreamReader myWebResponse = request.GetResponse() myResponseStream = myWebResponse.GetResponseStream() myStreamReader = New StreamReader(myResponseStream) msg = myStreamReader.ReadToEnd() myStreamReader.Close() myResponseStream.Close() ' Close the WebResponse' myWebResponse.Close() Return msg End Function

    Read the article

  • Paypal IPN Handler for Cart

    - by kimmothy16
    Hey everyone! I'm using a Paypal add to cart button for a simple ecommerce website. I had a Paypal IPN handler written in PHP that was successfully working for 'Buy it Now' buttons and purchasing one item at a time. I would run a database query each time to update the store's inventory to reflect the purchase. Now I'm upgrading this store to a 'cart' version so people could check out with multiple items at a time. Would anyone be able to tell me, in general, how my IPN handler would need to be altered to accommodate this? I'm unsure of what a response from Paypal looks like for a cart purchase as opposed to a buy it now purchase. Thanks, any help or examples of working IPN cart scripts would be very appreciated! My current code is below.. // Paypal POSTs HTML FORM variables to this page // we must post all the variables back to paypal exactly unchanged and add an extra parameter cmd with value _notify-validate // initialise a variable with the requried cmd parameter $req = 'cmd=_notify-validate'; // go through each of the POSTed vars and add them to the variable foreach ($_POST as $key => $value) { $value = urlencode(stripslashes($value)); $req .= "&$key=$value"; } // post back to PayPal system to validate $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n"; $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; $header .= "Content-Length: " . strlen($req) . "\r\n\r\n"; // In a live application send it back to www.paypal.com // but during development you will want to uswe the paypal sandbox // comment out one of the following lines $fp = fsockopen ('www.sandbox.paypal.com', 80, $errno, $errstr, 30); //$fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30); // or use port 443 for an SSL connection //$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30); if (!$fp) { // HTTP ERROR } else { fputs ($fp, $header . $req); while (!feof($fp)) { $res = fgets ($fp, 1024); if (strcmp ($res, "VERIFIED") == 0) { $item_name = stripslashes($_POST['item_name']); $item_number = $_POST['item_number']; $item_id = $_POST['custom']; $payment_status = $_POST['payment_status']; $payment_amount = $_POST['mc_gross']; //full amount of payment. payment_gross in US $payment_currency = $_POST['mc_currency']; $txn_id = $_POST['txn_id']; //unique transaction id $receiver_email = $_POST['receiver_email']; $payer_email = $_POST['payer_email']; $size = $_POST['option_selection1']; $item_id = $_POST['item_id']; $business = $_POST['business']; if ($payment_status == 'Completed') { // UPDATE THE DATABASE }

    Read the article

  • Retrieving Data related to a top-level object from parse.com using PHP

    - by Albeert Tw
    I am retrieve related data using parse.com and PHP I get the top-leve object without problems but I can't access related data. ([myRelation] => stdClass Object ( [__type] => Relation [className] => other)) Please refer to my code below: $className = "myClass"; $url = 'https://api.parse.com/1/classes/' . $className; $appId = 'xxxxxx'; $restKey = 'xxxxxxx'; $relatedParams = urlencode('include=people'); $rest = curl_init(); curl_setopt($rest, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($rest, CURLOPT_URL, $url .'/io1GzkzErH/'.$relatedParams); curl_setopt($rest, CURLOPT_HTTPGET, true); curl_setopt($rest, CURLOPT_RETURNTRANSFER, true); curl_setopt($rest, CURLOPT_HTTPHEADER, array("X-Parse-Application-Id: " . $appId, "X-Parse-REST-API-Key: " . $restKey, "Content-Type: application/json")); $response = curl_exec($rest); echo $response; I want to see related objects into myRelation. Current answer is: I get this answer: stdClass Object ( [Altres] => loremipsum. [Cartell] => stdClass Object ( [__type] => File [name] => f29efff4-5db1-451a-ab42-7569fbb955a7-cartell.jpg [url] => loremipsum.jpg ) [CartellURL] => [Categoria] => Comedia [Durada] => 120min [Estat] => Al teatre [Final] => stdClass Object ( [__type] => Date [iso] => 2014-06-18T22:00:00.000Z ) [Inici] => stdClass Object ( [__type] => Date [iso] => 2014-04-25T22:00:00.000Z ) [Nom] => Losers [Prioritat] => 0 [Sala] => loremipsum [Sinopsis] => loremipsum [TrailerURL] => loremipsum.com [URLEntrada] => loremipsum.com [URLProductora] => http://www.loremipsum.com [Visible] => 1 [createdAt] => 2014-05-20T12:01:06.094Z [objectId] => io1GzkzErH [people] => stdClass Object ( [__type] => Relation [className] => persones ) [updatedAt] => 2014-05-20T12:07:22.758Z ) loremipsum But I need to know what are in [people] = stdClass Object ( [__type] = Relation [className] = persones )

    Read the article

  • Uploading on Youtube via HTTP Post

    - by sajid.nizami
    I am following the steps provided on this link [http://code.google.com/apis/youtube/2.0/developers_guide_dotnet.html#Browser_based_Upload][1] Whenever I try to upload anything using this method, I get a HTTP 400 error saying that the next_url is not provided. Code is pretty simple and is a copy of Google's own code. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="BrowserUpload.aspx.cs" Inherits="BrowserUpload" %> <%@ Import Namespace="Google.YouTube" %> <%@ Import Namespace="Google.GData.Extensions.MediaRss" %> <%@ Import Namespace="Google.GData" %> <%@ Import Namespace="Google.GData.YouTube" %> <%@ Import Namespace="Google.GData.Client" %> <!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"> <head runat="server"> <title></title> <script type="text/javascript"> function checkForFile() { if (document.getElementById('file').value) { return true; } document.getElementById('errMsg').style.display = ''; return false; } </script> </head> <body> <% YouTubeRequestSettings settings = new YouTubeRequestSettings("Danat", "API-KEY", "loginid", "password" ); YouTubeRequest request = new YouTubeRequest(settings); Video newVideo = new Video(); newVideo.Title = "My Test Movie"; newVideo.Tags.Add(new MediaCategory("Autos", YouTubeNameTable.CategorySchema)); newVideo.Keywords = "cars, funny"; newVideo.Description = "My description"; newVideo.YouTubeEntry.Private = false; newVideo.Tags.Add(new MediaCategory("mydevtag, anotherdevtag", YouTubeNameTable.DeveloperTagSchema)); FormUploadToken token = request.CreateFormUploadToken(newVideo); %> <form action="<%= token.Url %>?next_url=<%= Server.UrlEncode("http://www.danatev.com") %>" name="PostToYoutube" method="post" enctype="multipart/form-data" onsubmit="return checkForFile();" > <input id="file" type="file" name="file" /> <div id="errMsg" style="display: none; color: red"> You need to specify a file. </div> <input type="hidden" name="token" value="<%= token.Token %>" /> <input type="submit" value="go" /> </form>

    Read the article

  • Create new etherpad using PHP and CURL

    - by Kyle Mathews
    I'm trying to write a simple PHP script which automatically sets up new etherpads (see http://etherpad.com/). They don't have an API (yet) for creating new pads so I'm trying to figure if I can do things another way. After playing around some, I found that if you append a random string to etherpad.com to a not-yet-created pad, it'll come back with a form asking if you want to create a new etherpad at that address. If you submit that form, a new pad will be created at that URL. My thought then was I could just create a PHP script using CURL that would duplicate that form and trick etherpad into creating a new pad at whatever URL I give it. I wrote the script but so far I can't get it working. Can someone tell me what I'm doing wrong? First, here's the HTML form on the etherpad creation page: ` <p><tt id="padurl">http://etherpad.com/lsdjfsljfa-fdj-lsdf</tt></p> <br/> <p>There is no EtherPad document here. Would you like to create one?</p> <input type="hidden" value="lsdjfsljfa-fdj-lsdf" name="padId"/> <input type="submit" value="Create Pad" id="createPad"/> ` Then here's my code which tries to submit the form using CURL $ch = curl_init(); //set POST variables $url = "http://etherpad.com/ep/pad/create?padId=ldjfal-djfa-ldkfjal"; $fields = array( 'padId'=>urlencode("ldjfal-djfa-ldkfjal"), ); $useragent="Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)"; // set user agent curl_setopt($ch, CURLOPT_USERAGENT, $useragent); //url-ify the data for the POST foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value; } print_r($fields_string); //open connection $ch = curl_init(); //set the url, number of POST vars, POST data curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_POST,count($fields)); curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string); //execute post $result = curl_exec($ch); print_r($result); //close connection curl_close($ch); When I run the script, PHP reports back that everything executed correctly but etherpad doesn't create my pad. Any clues what's going on?

    Read the article

  • Connected host failed to respond (internal NAT address)

    - by MostRandom
    I'm writing my first C# web application that connects to an XML based service. It requires that I present a certificate and feed the XML stream. It seems to authenticate properly but then it gives the following error: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 10.1.10.4:3128 The funny thing is that I'm not on a proxy or anything like that. I'm connecting directly to the internet. At one point I we did use a proxy that with internal NAT address. So my question is: Does Visual Studio have some sort of default proxy setting that I need to change? This IP is no longer used for anything, so I know that I don't need to use any proxy authentication code. using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; namespace WebApplication1 { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Uri requestURI = new Uri("*site omitted*"); //Create the Request Object HttpWebRequest pageRequest = (HttpWebRequest)WebRequest.Create(requestURI); //After installing the cert on the server export a client cert to the working directory as Deluxe.cer string certFile = "*certificate omitted*"; X509Certificate cert = X509Certificate.CreateFromCertFile(certFile); //Pull in your Data, if it is from an external xml as below or create an xml string with variables if a dynamic post is required. string xmlPath = "*XML omitted*"; System.Xml.XmlDocument passXML = new System.Xml.XmlDocument(); passXML.Load(xmlPath); //XML String with the data needed to pass string postData = passXML.OuterXml; //Set the Request Object parameters pageRequest.ContentType = "application/x-www-form-urlencoded"; pageRequest.Method = "POST"; pageRequest.AllowWriteStreamBuffering = false; pageRequest.AllowAutoRedirect = false; pageRequest.ClientCertificates.Add(cert); postData = "xml_data=" + Server.UrlEncode(postData); pageRequest.ContentLength = postData.Length; //Create the Post Stream Object System.IO.StreamWriter postStream = new System.IO.StreamWriter(pageRequest.GetRequestStream()); //Write the data to the post stream postStream.Write(postData); postStream.Flush(); postStream.Close(); //Set the Response Object HttpWebResponse postResponse = (HttpWebResponse)pageRequest.GetResponse();

    Read the article

  • Decode the string encoded through php in javascript

    - by Pankaj Khurana
    Hi, I am working on a facebook page in which i have used ajax & response is returned in json format. I have encoded the string in php. Now i want to decode that string in javascript. foreach($feedbackdetails as $feedbackdetail) { $str.= '<div class="tweet"> <img style="cursor:pointer;" id="imgVoteUp" src="http://myserver/facebook/vote_up.gif" alt="Vote Up" title="Vote Up" onclick="saveVote('.$feedbackdetail[pk_feedbackid].',1)" /> : '.$feedbackdetail[upvotecount].' <img style="cursor:pointer;" id="imgVoteDown" src="http://myserver/facebook/vote_down.gif" alt="Vote Down" title="Vote Down" onclick="saveVote('.$feedbackdetail[pk_feedbackid].',0)" /> : '.$feedbackdetail[downvotecount].' <p class="'.$pclass.'">'.$feedbackdetail[title].' by '.$feedbackdetail[name].'<br>'.$feedbackdetail[description].'</p></div>'; } $str=urlencode($str); echo '{"fbml_test":"'.$str.'"}'; Javascript Function: function saveVote(id,type,class) { contentdiv='div_'+id; processdiv='processdiv_'+id; document.getElementById(processdiv).setInnerXHTML('<span id="caric"><center><img src="http://static.ak.fbcdn.net/rsrc.php/z5R48/hash/ejut8v2y.gif" /></center></span>'); posturl='http://myserver/facebook/vote.php'; if(class==0) { class='firstmessage'; } else { class='message'; } var queryString = "?id="+id+"&type="+type+"&pclass="+class; posturl = posturl +queryString; ajax = new Ajax(); ajax.responseType = Ajax.JSON; ajax.requireLogin = true; ajax.ondone = function(data) { document.getElementById('caric').setStyle('display','none'); //new Dialog().showMessage('Dialog',data); if(data.error) { new Dialog().showMessage('Dialog',data.error); } if(data.fbml_test) { document.getElementById(contentdiv).setInnerFBML(data)); } //div_id.setInnerFBML(data); } ajax.post(posturl); } Right now i am getting encoded string how can i change it? Please help me on this Thanks Pankaj

    Read the article

  • Invalid character in a Base-64 string when Concatenating and Url encoding a string

    - by Rob
    I’m trying to write some encryption code that is passed through a Url. For the sake of the issue I’ve excluded the actual encryption of the data and just shown the code causing the problem. I take a salt value, convert it to a byte array and then convert that to a base64 string. This string I concatenate to another base64 string (which was previously a byte array). These two base64 strings are then Url encoded. Here’s my code... using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using System.IO; using System.Web; class RHEncryption { private static readonly Encoding ASCII_ENCODING = new System.Text.ASCIIEncoding(); private static readonly string SECRET_KEY = "akey"; private static string md5(string text) { return BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(ASCII_ENCODING.GetBytes(text))).Replace("-", "").ToLower(); } public string UrlEncodedData; public RHEncryption() { // encryption object RijndaelManaged aes192 = new RijndaelManaged(); aes192.KeySize = 192; aes192.BlockSize = 192; aes192.Mode = CipherMode.CBC; aes192.Key = ASCII_ENCODING.GetBytes(md5(SECRET_KEY)); aes192.GenerateIV(); // convert Ivector to base64 for sending string base64IV = Convert.ToBase64String(aes192.IV); // salt value string s = "maryhadalittlelamb"; string salt = s.Substring(0, 8); // convert to byte array // and base64 for sending byte[] saltBytes = ASCII_ENCODING.GetBytes(salt.TrimEnd('\0')); string base64Salt = Convert.ToBase64String(saltBytes); //url encode concatenated base64 strings UrlEncodedData = HttpUtility.UrlEncode(base64Salt + base64IV, ASCII_ENCODING); } public string UrlDecodedData() { // decode the url encode string string s = HttpUtility.UrlDecode(UrlEncodedData, ASCII_ENCODING); // convert back from base64 byte[] base64DecodedBytes = null; try { base64DecodedBytes = Convert.FromBase64String(s); } catch (FormatException e) { Console.WriteLine(e.Message.ToString()); Console.ReadLine(); } return s; } } If I then call the UrlDecodedData method I get a “Invalid character in a Base-64 string” exception. This is generated because the base64Salt variable contains an invalid character (I’m guessing a line termination) but I can’t seem to strip it off.

    Read the article

  • Need Help on OAuthException Code 2500

    - by Deepak
    I am trying to develop an Facebook application (apps.facebook.com/some_app) using PHP where I need to present some information based on user's music interests. I found that its under "user_likes games". My problems are as follows: To gain access, I have implemented the oauth dialog method as suggested in API in my index page. $auth_url = "http://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($canvas_page) ."&scope=user_likes"; After successful authorization I come back to index page with "code" as parameters. http://MY_CANVAS_PAGE/?code=some base64 encoded letters Firstly I don't know if I need access_token just to read user's music interests but I have tried all the methods suggested. I couldn't move forward from this point I have a code like this (in my index page), which redirects for authorization if code parameters is not set. if(empty($code) && !isset($_REQUEST['error'])) { $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection echo("<script> top.location.href='" . $auth_url . "'</script>"); } Currently I am just trying to get user's public information here but with no success. I have tried the signed_request method as suggested but no success $signed_request = $_REQUEST["signed_request"]; list($encoded_sig, $payload) = explode('.', $signed_request, 2); $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true); echo ("Welcome User: " . $data["user_id"]); Also tried the code found in http://developers.facebook.com/blog/post/500/ but I am getting error when trying to get the debug info using print_r($decoded_response); stdClass Object ( [error] => stdClass Object ( [message] => An active access token must be used to query information about the current user. [type] => OAuthException [code] => 2500 ) ) To get user's public info, I have tried also the suggested example in PHP SDK $facebook = new Facebook(array( 'appId' => MY_APP_ID, //registered facebook APP ID 'secret' => MY_SECRET, //secret key for APP )); $fb_user = $facebook->getUser(); if($fb_user){ try { $user_profile = $facebook->api('/me'); echo $user_profile['email']; } catch(FacebookApiException $e) { $fb_user = null; } } But no success. Can somebody explain me why I am getting this error and how to access the user's music interest properly. Probably I misunderstood the API. Thanks Deepak

    Read the article

  • php paypal ipn membership error

    - by aleksander haugas
    hello I integrated the membership subscription in the website, but I fail to insert data to the database. checking out all the function I make a txt file with php with data and generates me correctly. but I can not verify any data and less insert. <?php // read the post from PayPal system and add 'cmd' $req = 'cmd=_notify-validate'; foreach ($_POST as $key => $value) { $value = urlencode(stripslashes($value)); $req .= "&$key=$value"; } // Post back to PayPal system to validate $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n"; $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; $header .= "Content-Length: " . strlen($req) . "\r\n\r\n"; $fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30); // Assign posted variables to local variables $item_name = $_POST['item_name']; $item_number = $_POST['item_number']; $payment_status = $_POST['payment_status']; $payment_amount = $_POST['mc_gross']; $payment_currency = $_POST['mc_currency']; $txn_id = $_POST['txn_id']; $receiver_email = $_POST['receiver_email']; $payer_email = $_POST['payer_email']; $user_id = $_POST['custom']; //Here i make the txt file and it works correctly //but after this does not work or make a txt file //Insert and update data if (!$fp) { // HTTP ERROR } else { fputs ($fp, $header . $req); while (!feof($fp)) { $res = fgets ($fp, 1024); if (strcmp ($res, "VERIFIED") == 0) { //Verificamos el estado del pedido if ($payment_status == 'Completed') { $txn_id_check = mysql_query("SELECT Transaction_ID FROM ".$db_table_prefix."Users_Payments WHERE Transaction_ID='".$txn_id."'"); if (mysql_num_rows($txn_id_check) !=1) { //Si el pago se ha realizado al dueño especificado y coincide con el dueño if ($receiver_email == $website_Payment_Email) { //Tipo de cuenta segun pagado if ($payment_amount == '10.00' && $payment_currency == 'EUR') { //add txn_id to database $log_query = mysql_query("INSERT INTO `".$db_table_prefix."Users_Payments` VALUES ('','".$txn_id."','".$payer_email."')"); //update premium to 3 $update_premium = mysql_query("UPDATE ".$db_table_prefix."Users SET Group_ID='3' WHERE User_ID='".$user_id."'"); } } } } } else if (strcmp ($res, "INVALID") == 0) { // log for manual investigation } } fclose ($fp); } ?> I call this file with require_once () with the connection to the database any ideas? thanks

    Read the article

  • Stored procedure error when use computed column for ID

    - by Hari
    I got the error: Procedure or function usp_User_Info3 has too many arguments specified When I run the program. I don't know the error in SP or in C# code. I have to display the Vendor_ID after the user clicks the submit button. Where the thing going wrong here ? Table structure : CREATE TABLE User_Info3 ( SNo int Identity (2000,1) , Vendor_ID AS 'VEN' + CAST(SNo as varchar(16)) PERSISTED PRIMARY KEY, UserName VARCHAR(16) NOT NULL, User_Password VARCHAR(12) NOT NULL, User_ConPassword VARCHAR(12) NOT NULL, User_FirstName VARCHAR(25) NOT NULL, User_LastName VARCHAR(25) SPARSE NULL, User_Title VARCHAR(35) NOT NULL, User_EMail VARCHAR(35) NOT NULL, User_PhoneNo VARCHAR(14) NOT NULL, User_MobileNo VARCHAR(14)NOT NULL, User_FaxNo VARCHAR(14)NOT NULL, UserReg_Date DATE DEFAULT GETDATE() ) Stored Procedure : ALTER PROCEDURE [dbo].[usp_User_Info3] @SNo INT OUTPUT, @Vendor_ID VARCHAR(10) OUTPUT, @UserName VARCHAR(30), @User_Password VARCHAR(12), @User_ConPassword VARCHAR(12), @User_FirstName VARCHAR(25), @User_LastName VARCHAR(25), @User_Title VARCHAR(35), @User_OtherEmail VARCHAR(30), @User_PhoneNo VARCHAR(14), @User_MobileNo VARCHAR(14), @User_FaxNo VARCHAR(14) AS BEGIN SET NOCOUNT ON; INSERT INTO User_Info3 (UserName,User_Password,User_ConPassword,User_FirstName, User_LastName,User_Title,User_OtherEmail,User_PhoneNo,User_MobileNo,User_FaxNo) VALUES (@UserName,@User_Password,@User_ConPassword,@User_FirstName,@User_LastName, @User_Title,@User_OtherEmail,@User_PhoneNo,@User_MobileNo,@User_FaxNo) SET @SNo = Scope_Identity() SELECT Vendor_ID From User_Info3 WHERE SNo = @SNo END C# Code : protected void BtnUserNext_Click(object sender, EventArgs e) { cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "usp_User_Info3"; System.Data.SqlClient.SqlParameter SNo=cmd.Parameters.Add("@SNo",System.Data.SqlDbType.Int); System.Data.SqlClient.SqlParameter Vendor_ID=cmd.Parameters.Add("@Vendor_ID", System.Data.SqlDbType.VarChar,10); cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = txtUserName.Text; cmd.Parameters.Add("@User_Password", SqlDbType.VarChar).Value = txtRegPassword.Text; cmd.Parameters.Add("@User_ConPassword", SqlDbType.VarChar).Value = txtRegConPassword.Text; cmd.Parameters.Add("@User_FirstName", SqlDbType.VarChar).Value = txtRegFName.Text; cmd.Parameters.Add("@User_LastName", SqlDbType.VarChar).Value = txtRegLName.Text; cmd.Parameters.Add("@User_Title", SqlDbType.VarChar).Value = txtRegTitle.Text; cmd.Parameters.Add("@User_OtherEmail", SqlDbType.VarChar).Value = txtOtherEmail.Text; cmd.Parameters.Add("@User_PhoneNo", SqlDbType.VarChar).Value =txtRegTelephone.Text; cmd.Parameters.Add("@User_MobileNo", SqlDbType.VarChar).Value =txtRegMobile.Text; cmd.Parameters.Add("@User_FaxNo", SqlDbType.VarChar).Value =txtRegFax.Text; cmd.Connection = SqlCon; try { Vendor_ID.Direction = System.Data.ParameterDirection.Output; SqlCon.Open(); cmd.ExecuteNonQuery(); string VendorID = cmd.ExecuteScalar() as string; } catch (Exception ex) { throw new Exception(ex.Message); } finally { string url = "../CompanyBasicInfo.aspx?Parameter=" + Server.UrlEncode(" + VendorID + "); SqlCon.Close(); } }

    Read the article

  • Cross-site request forgery protections: Where do I put all these lines?

    - by brilliant
    Hello, I was looking for a python code that would be able to log in from "Google App Engine" to some of my accounts on some websites (like yahoo or eBay) and was given this code: import urllib, urllib2, cookielib url = "https://login.yahoo.com/config/login?" form_data = {'login' : 'my-login-here', 'passwd' : 'my-password-here'} jar = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar)) form_data = urllib.urlencode(form_data) # data returned from this pages contains redirection resp = opener.open(url, form_data) # yahoo redirects to http://my.yahoo.com, so lets go there instead resp = opener.open('http://mail.yahoo.com') print resp.read() Unfortunately, this code didn't work, so I asked another question here and one supporter among other things said this: "You send MD5 hash and not plain password. Also you'd have to play along with all kinds of CSRF protections etc. that they're implementing. Look: <input type="hidden" name=".tries" value="1"> <input type="hidden" name=".src" value="ym"> <input type="hidden" name=".md5" value=""> <input type="hidden" name=".hash" value=""> <input type="hidden" name=".js" value=""> <input type="hidden" name=".last" value=""> <input type="hidden" name="promo" value=""> <input type="hidden" name=".intl" value="us"> <input type="hidden" name=".bypass" value=""> <input type="hidden" name=".partner" value=""> <input type="hidden" name=".u" value="bd5tdpd5rf2pg"> <input type="hidden" name=".v" value="0"> <input type="hidden" name=".challenge" value="5qUiIPGVFzRZ2BHhvtdGXoehfiOj"> <input type="hidden" name=".yplus" value=""> <input type="hidden" name=".emailCode" value=""> <input type="hidden" name="pkg" value=""> <input type="hidden" name="stepid" value=""> <input type="hidden" name=".ev" value=""> <input type="hidden" name="hasMsgr" value="0"> <input type="hidden" name=".chkP" value="Y"> <input type="hidden" name=".done" value="http://mail.yahoo.com"> <input type="hidden" name=".pd" value="ym_ver=0&c=&ivt=&sg="> I am not quite sure where he got all these lines from and where in my code I am supposed to add them. Do You have any idea? I know I was supposed to ask him this question first, and I did, but he never returned, so I decided to ask a separate question here.

    Read the article

  • How can I create a Searchstring for a Google AJAX Search API?

    - by elmaso
    Hello, i have this code to get the search resutls from the api: querygoogle.php: <?php session_start(); // Here's the Google AJAX Search API url for curl. It uses Google Search's site:www.yourdomain.com syntax to search in a specific site. I used $_SERVER['HTTP_HOST'] to find my domain automatically. Change $_POST['searchquery'] to your posted search query $url = 'http://ajax.googleapis.com/ajax/services/search/web?rsz=large&v=1.0&start=20&q=' . urlencode('' . $_POST['searchquery']); // use fopen and fread to pull Google's search results $handle = fopen($url, 'rb'); $body = ''; while (!feof($handle)) { $body .= fread($handle, 8192); } fclose($handle); // now $body is the JSON encoded results. We need to decode them. $json = json_decode($body); // now $json is an object of Google's search results and we need to iterate through it. foreach($json->responseData->results as $searchresult) { if($searchresult->GsearchResultClass == 'GwebSearch') { $formattedresults .= ' <div class="searchresult"> <h3><a href="' . $searchresult->unescapedUrl . '">' . $searchresult->titleNoFormatting . '</a></h3> <p class="resultdesc">' . $searchresult->content . '</p> <p class="resulturl">' . $searchresult->visibleUrl . '</p> </div>'; } } $_SESSION['googleresults'] = $formattedresults; header('Location: ' . $_SERVER['HTTP_REFERER']); exit; ?> search.php <?php session_start(); ?> <form method="post" action="querygoogle.php"> <label for="searchquery"><span class="caption">Search this site</span> <input type="text" size="20" maxlength="255" title="Enter your keywords and click the search button" name="searchquery" /></label> <input type="submit" value="Search" /> </form> <?php if(!empty($_SESSION['googleresults'])) { echo $_SESSION['googleresults']; unset($_SESSION['googleresults']); } ?> but with this code, I cant add a searchstring.. how can i add a search string like search.php?search=keyword ? thanks

    Read the article

  • Paypal IPN: how get the POSTs from this class?

    - by sineverba
    I'm using this Class <?php class paypalIPN { //sandbox: private $paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; //live site: //private $paypal_url = 'https://www.paypal.com/cgi-bin/webscr'; private $data = null; public function __construct() { $this->data = new stdClass; } public function isa_dispute() { //is it some sort of dispute. return $this->data->txn_type == "new_case"; } public function validate() { // parse the paypal URL $response = ""; $url_parsed = parse_url($this->paypal_url); // generate the post string from the _POST vars aswell as load the // _POST vars into an arry so we can play with them from the calling // script. $post_string = ''; foreach ($_POST as $field=>$value) { $this->data->$field = $value; $post_string .= $field.'='.urlencode(stripslashes($value)).'&'; } $post_string.="cmd=_notify-validate"; // append ipn command $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->paypal_url); //curl_setopt($ch, CURLOPT_VERBOSE, 1); //keep the peer and server verification on, recommended //(can switch off if getting errors, turn to false) curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string); $response = curl_exec($ch); if (curl_errno($ch)) { die("Curl Error: " . curl_errno($ch) . ": " . curl_error($ch)); } curl_close($ch); return $response; if (preg_match("/VERIFIED/", $response)) { // Valid IPN transaction. return $this->data; } else { return false; } } } ANd i recall in this mode: public function get_ipn() { $ipn = new paypalIPN(); $result = $ipn->validate(); $logger = new Log('/error.log'); $logger->write(print_r($result)); } But I obtain only "VERIFIED" or "1" (whitout or with the print_r function). I just tried also to return directly the raw curl response with return $response; or return $this->response; or also return $this->parse_string; but everytime I receive only "1" or "VERIFIED"....... Thank you very much

    Read the article

  • How to save POST&GET headers of a web page with "Wireshark"?

    - by brilliant
    Hello everybody, I've been trying to find a python code that would log in to my mail box on yahoo.com from "Google App Engine". I was given this code: import urllib, urllib2, cookielib url = "https://login.yahoo.com/config/login?" form_data = {'login' : 'my-login-here', 'passwd' : 'my-password-here'} jar = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar)) form_data = urllib.urlencode(form_data) # data returned from this pages contains redirection resp = opener.open(url, form_data) # yahoo redirects to http://my.yahoo.com, so lets go there instead resp = opener.open('http://mail.yahoo.com') print resp.read() The author of this script looked into HTML script of yahoo log-in form and came up with this script. That log-in form contains two fields, one for users' Yahoo! ID and another one is for users' password. However, when I tried this code out (substituting mu real Yahoo login for 'my-login-here' and my real password for 'my-password-here'), it just return the log-in form back to me, which means that something didn't work right. Another supporter suggested that I should send an MD5 hash of my password, rather than a plain password. He also noted that in that log-in form there are a lot other hidden fields besides login and password fields (he called them "CSRF protections") that I would also have to deal with: <input type="hidden" name=".tries" value="1"> <input type="hidden" name=".src" value="ym"> <input type="hidden" name=".md5" value=""> <input type="hidden" name=".hash" value=""> <input type="hidden" name=".js" value=""> <input type="hidden" name=".last" value=""> <input type="hidden" name="promo" value=""> <input type="hidden" name=".intl" value="us"> <input type="hidden" name=".bypass" value=""> <input type="hidden" name=".partner" value=""> <input type="hidden" name=".u" value="bd5tdpd5rf2pg"> <input type="hidden" name=".v" value="0"> <input type="hidden" name=".challenge" value="5qUiIPGVFzRZ2BHhvtdGXoehfiOj"> <input type="hidden" name=".yplus" value=""> <input type="hidden" name=".emailCode" value=""> <input type="hidden" name="pkg" value=""> <input type="hidden" name="stepid" value=""> <input type="hidden" name=".ev" value=""> <input type="hidden" name="hasMsgr" value="0"> <input type="hidden" name=".chkP" value="Y"> <input type="hidden" name=".done" value="http://mail.yahoo.com"> He said that I should do the following: Simulate normal login and save login page that I get; Save POST&GET headers with "Wireshark"; Compare login page with those headers and see what fields I need to include with my request; I really don't know how to carry out the first two of these three steps. I have just downloaded "Wireshark" and have tried capturing some packets there. However, I don't know how to "simulate normal login and save the login page". Also, I don't how to save POST$GET headers with "Wireshark". Can anyone, please, guide me through these two steps in "Wireshark"? Or at least tell me what I should start with. Thank You.

    Read the article

  • Routing Issue in ASP.NET MVC 3 RC 2

    - by imran_ku07
         Introduction:             Two weeks ago, ASP.NET MVC team shipped the ASP.NET MVC 3 RC 2 release. This release includes some new features and some performance optimization. This release also fixes most of the bugs but still some minor issues are present in this release. Some of these issues are already discussed by Scott Guthrie at Update on ASP.NET MVC 3 RC2 (and a workaround for a bug in it). In addition to these issues, I have found another issue in this release regarding routing. In this article, I will show you the issue regarding routing and a simple workaround for this issue.       Description:             The easiest way to understand an issue is to reproduce it in the application. So create a MVC 2 application and a MVC 3 RC 2 application. Then in both applications, just open global.asax file and update the default route as below,     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id1}/{id2}", // URL with parameters new { controller = "Home", action = "Index", id1 = UrlParameter.Optional, id2 = UrlParameter.Optional } // Parameter defaults );              Then just open Index View and add the following lines,    <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Home Page </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <% Html.RenderAction("About"); %> </asp:Content>             The above view will issue a child request to About action method. Now run both applications. ASP.NET MVC 2 application will run just fine. But ASP.NET MVC 3 RC 2 application will throw an exception as shown below,                  You may think that this is a routing issue but this is not the case here as both ASP.NET MVC 2 and ASP.NET MVC  3 RC 2 applications(created above) are built with .NET Framework 4.0 and both will use the same routing defined in System.Web. Something is wrong in ASP.NET MVC 3 RC 2. So after digging into ASP.NET MVC source code, I have found that the UrlParameter class in ASP.NET MVC 3 RC 2 overrides the ToString method which simply return an empty string.     public sealed class UrlParameter { public static readonly UrlParameter Optional = new UrlParameter(); private UrlParameter() { } public override string ToString() { return string.Empty; } }             In MVC 2 the ToString method was not overridden. So to quickly fix the above problem just replace UrlParameter.Optional default value with a different value other than null or empty(for example, a single white space) or replace UrlParameter.Optional default value with a new class object containing the same code as UrlParameter class have except the ToString method is not overridden (or with a overridden ToString method that return a string value other than null or empty). But by doing this you will loose the benefit of ASP.NET MVC 2 Optional URL Parameters. There may be many different ways to fix the above problem and not loose the benefit of optional parameters. Here I will create a new class MyUrlParameter with the same code as UrlParameter class have except the ToString method is not overridden. Then I will create a base controller class which contains a constructor to remove all MyUrlParameter route data parameters, same like ASP.NET MVC doing with UrlParameter route data parameters early in the request.     public class BaseController : Controller { public BaseController() { if (System.Web.HttpContext.Current.CurrentHandler is MvcHandler) { RouteValueDictionary rvd = ((MvcHandler)System.Web.HttpContext.Current.CurrentHandler).RequestContext.RouteData.Values; string[] matchingKeys = (from entry in rvd where entry.Value == MyUrlParameter.Optional select entry.Key).ToArray(); foreach (string key in matchingKeys) { rvd.Remove(key); } } } } public class HomeController : BaseController { public ActionResult Index(string id1) { ViewBag.Message = "Welcome to ASP.NET MVC!"; return View(); } public ActionResult About() { return Content("Child Request Contents"); } }     public sealed class MyUrlParameter { public static readonly MyUrlParameter Optional = new MyUrlParameter(); private MyUrlParameter() { } }     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id1}/{id2}", // URL with parameters new { controller = "Home", action = "Index", id1 = MyUrlParameter.Optional, id2 = MyUrlParameter.Optional } // Parameter defaults );             MyUrlParameter class is a copy of UrlParameter class except that MyUrlParameter class not overrides the ToString method. Note that the default route is modified to use MyUrlParameter.Optional instead of UrlParameter.Optional. Also note that BaseController class constructor is removing MyUrlParameter parameters from the current request route data so that the model binder will not bind these parameters with action method parameters. Now just run the ASP.NET MVC 3 RC 2 application again, you will find that it runs just fine.             In case if you are curious to know that why ASP.NET MVC 3 RC 2 application throws an exception if UrlParameter class contains a ToString method which returns an empty string, then you need to know something about a feature of routing for url generation. During url generation, routing will call the ParsedRoute.Bind method internally. This method includes a logic to match the route and build the url. During building the url, ParsedRoute.Bind method will call the ToString method of the route values(in our case this will call the UrlParameter.ToString method) and then append the returned value into url. This method includes a logic after appending the returned value into url that if two continuous returned values are empty then don't match the current route otherwise an incorrect url will be generated. Here is the snippet from ParsedRoute.Bind method which will prove this statement.       if ((builder2.Length > 0) && (builder2[builder2.Length - 1] == '/')) { return null; } builder2.Append("/"); ........................................................... ........................................................... ........................................................... ........................................................... if (RoutePartsEqual(obj3, obj4)) { builder2.Append(UrlEncode(Convert.ToString(obj3, CultureInfo.InvariantCulture))); continue; }             In the above example, both id1 and id2 parameters default values are set to UrlParameter object and UrlParameter class include a ToString method that returns an empty string. That's why this route will not matched.            Summary:             In this article I showed you the issue regarding routing and also showed you how to workaround this problem. I explained this issue with an example by creating a ASP.NET MVC 2 and a ASP.NET MVC 3 RC 2 application. Finally I also explained the reason for this issue. Hopefully you will enjoy this article too.   SyntaxHighlighter.all()

    Read the article

  • Curl, twitter oauth problem

    - by Darxval
    Does anyone see a problem with the following Curl call / how the Oauth request is built? (i am trying to get a correctly setup request so i can finish my app) So i am calling the following CURL call: C:\>curl -v -k --data-urlencode "status=Testing2" -H "Authorization: OAuth realm='', oauth_nonce=1276107867blah, oauth_timestamp=1276107867, oauth_consumer_key=yJDLH7BDdVi1OKIINSV7Q, oauth_signature_method=HMAC-SHA1, oauth_version=1.0, oauth_signature=NWU4MDdlNjk0OGIxYWQ1YTkyNmU5YjU1NGYyOTczMmU5ZDg5 YWNkNA==, staus=Testing2 " http://twitter.com/statuses/update.xml?status=Testing2 and i recieve this: * About to connect() to twitter.com port 80 (#0) * Trying 168.143.162.68... connected * Connected to twitter.com (168.143.162.68) port 80 (#0) > POST /statuses/update.xml?status=Testing2 HTTP/1.1 > User-Agent: curl/7.20.1 (i386-pc-win32) libcurl/7.20.1 OpenSSL/0.9.8n zlib/1.2.5 libidn/1.18 libssh2/1.2.5 > Host: twitter.com > Accept: */* > Authorization: OAuth realm='', oauth_nonce=1276106370blah, oauth_timestamp=1276106370, oauth_consumer_key=yJDLH7BDdVi1OKIINSV7Q, oauth_signature_method=HMAC-SHA1, oauth_version=1.0, oauth_signature=MjQzNDA1MGU4NGRmMWVjMzUwZmQ4YzE5NzMzY2I1ZDJlOTRkNmQ2Zg==, staus=Testing2 > Content-Length: 15 > Content-Type: application/x-www-form-urlencoded > < HTTP/1.1 401 Unauthorized < Date: Wed, 09 Jun 2010 18:00:22 GMT < Server: hi < Status: 401 Unauthorized < WWW-Authenticate: Basic realm="Twitter API" < X-Runtime: 0.00548 < Content-Type: application/xml; charset=utf-8 < Content-Length: 164 < Cache-Control: no-cache, max-age=1800 < Set-Cookie: k=209.234.229.21.1276106420885412; path=/; expires=Wed, 16-Jun-10 18:00:20 GMT; domain=.twitter.com < Set-Cookie: guest_id=127610642214871948; path=/; expires=Fri, 09 Jul 2010 18:00:22 GMT < Set-Cookie: _twitter_sess=BAh7CDoPY3JlYXRlZF9hdGwrCIm33h0pAToHaWQiJTkyMjllODE0NTdiYWE1%250AMWU1MzBmNjgwMTFiMDhkYjdlIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVy%250AOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--8ebb3c62d461d28f8fda7b8adab642af66969f7e; domain=.twitter.com; path=/ < Expires: Wed, 09 Jun 2010 18:30:20 GMT < Vary: Accept-Encoding < Connection: close < <?xml version="1.0" encoding="UTF-8"?> <hash> <request>/statuses/update.xml?status=Testing2</request> <error>Could not authenticate with OAuth.</error> </hash> * Closing connection #0 my Parameters are setup like so: var parameters = [encodeURIComponent("status="+status),encodeURIComponent("oauth_token="+ac_token),encodeURIComponent("oauth_consumer_key="+"yJDLH7BDdVi1OKIINSV7Q"),encodeURIComponent("oauth_nonce="+nonce,"oauth_signature_method=HMAC-SHA1"),encodeURIComponent("oauth_timestamp="+timestamp),encodeURIComponent("oauth_version=1.0")] var join = parameters.join("&"); var eparamjoin =encodeURIComponent(join); The key is like so: var key=con_secret+"&"+ac_secret; Signature base string is: var signaturebs = "POST&"+encodeURIComponent(url)+"&"+eparamjoin; giving this: POST&http%3A%2F%2Ftwitter.com%2Fstatuses%2Fupdate.xml&status%253DTesting2%26oauth_token%253D142715285-yi2ch324S3zfyKyJby6WDUZOhCsiQuKNUtc3nAGe%26oauth_consumer_key%253DyJDLH7BDdVi1OKIINSV7Q%26oauth_nonce%253D1276107867blah%26oauth_timestamp%253D1276107867%26oauth_version%253D1.0 and signature built like so: var hmac = Crypto.HMAC(Crypto.SHA1, signaturebs,key ); var signature=Base64.encode(hmac); making the signature: NWU4MDdlNjk0OGIxYWQ1YTkyNmU5YjU1NGYyOTczMmU5ZDg5YWNkNA== Any help would be appreciated thank you!

    Read the article

< Previous Page | 5 6 7 8 9 10  | Next Page >