Solved

Using C# to  Log into a PHP Page

Posted on 2011-03-24
3
755 Views
Last Modified: 2012-06-27
Hi All,

I'm trying to use C# to log into a PHP webpage.  I've got the following code which gets me as far as requesting the HTML and removing problem characters but I don't know how to get username/password into the text boxes (auth_user & auth_pw) and click the submit login button (b_login):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;

namespace WebRippp
{
    public partial class Form1 : Form
    {

        public string source;
        public string url = "http://99.99.99.99/admin/";

        public Form1()
        {
            InitializeComponent();
        }

        private void btnGetSource_Click(object sender, EventArgs e)
        {
            //Create Cookie Container.
            CookieContainer cookies = new CookieContainer();
            
            //Set Proxy Server Info.
            setProxy();
            
            //Request Login Page.
            loginPage();


            string url = txtSource.Text;
        }

        private void loginPage()
        {
            //Request login page source.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader stream = new StreamReader(response.GetResponseStream());
            source = stream.ReadToEnd();
            stream.Close();
            source = source.Replace("\n", "").Replace("\r", "").Replace("\t", "").Replace(" ", "");

            //Post
            [b]?????[/b]
        }

        private string ExtractViewState(string s)
        {
            string viewStateNameDelimiter = "__VIEWSTATE";
            string valueDelimiter = "value=\"";

            int viewStateNamePosition = s.IndexOf(viewStateNameDelimiter);
            int viewStateValuePosition = s.IndexOf(
                  valueDelimiter, viewStateNamePosition
               );

            int viewStateStartPosition = viewStateValuePosition +
                                         valueDelimiter.Length;
            int viewStateEndPosition = s.IndexOf("\"", viewStateStartPosition);
            string viewState = HttpUtility.UrlEncodeUnicode(
                     s.Substring(
                        viewStateStartPosition,
                        viewStateEndPosition - viewStateStartPosition
                     )
                  );
            return viewState;
        }

        private void setProxy()
        {
            System.Net.WebProxy pry = new System.Net.WebProxy("99.99.99.99", 8080);
            //The DefaultCredentials automically get username and password.
            pry.Credentials = CredentialCache.DefaultCredentials;
            GlobalProxySelection.Select = pry;
        }
    }
}

Open in new window



Help & Guidance much appreciated!

Thanks!
0
Comment
Question by:ImaCircularSaw
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 

Accepted Solution

by:
SubsonicDesignOfficial earned 250 total points
ID: 35211455
You should use WebBrowser control automation to do that. It seems that you already know the IDs of TextBox controls and the Button so you only have to write a little code to automatically add the text into textboxes and perform a button click. Please take a look at the following article:

http://www.codeproject.com/KB/cs/mshtml_automation.aspx

I've created something very similar in the past and the article above helped me A LOT!
0
 
LVL 15

Assisted Solution

by:Russell_Venable
Russell_Venable earned 250 total points
ID: 35219528
Using a Webbrowser control is the easiest way, but it does not give you full control over what your doing.

I would suggest that you buy the book: HTTP Programming Recipes for C# Bots. Its the best reference for this kind of work. Gets straight to the point as it becomes really difficult to give small solutions for this.

Besides if you get the book all you have to do is reference it :) Its a plus plus.

It will teach you  how to use get/post requests and parse the information and then display or use however you need it. Including posting to Forms, Multi-posts, etc.

If you dont want to go that route your going to need a few tools to do the job.

Tools:

1. Fiddler: [url="http://www.fiddler2.com/fiddler2/

Fiddler[/url]"]

2. Wireshark: [url="http://www.wireshark.org/

Wireshark[/url]"]

3. or A custom tool to read the Http get/post response



When you submit a form it sends a request like this.
POST /someForm.php?Value=someValue&auth_user=someUser&auth_pw=SomePassword&b_login

Open in new window

You are basically recreating the same method that those tools show you. After that you should be logged in and you can add CookieContainer to store your cookies to stay logged in, etc.
0
 
LVL 10

Author Comment

by:ImaCircularSaw
ID: 35393387
I've not been able to complete this yet, however, both of your options seem good enough to me so I'll split the points fairly.

Thanks!
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

615 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question