Creating your own Model User

by on Aug.19, 2014, under Kohana, PHP

If you are trying to create your own Model User and you receive the message bellow:

ErrorException [ Fatal Error ]: Call to undefined method Model_User::unique_key()ErrorException [ Fatal Error ]: Call to undefined method Model_User::unique_key()

then you are probably extending ORM. When you are extending Model User make sure that it extends Model_Auth_User and not Model_ORM.

Comments Off more...

Generate password hashes for user registration on Kohana

by on Aug.12, 2014, under Kohana, PHP

echo Auth::instance()->hash_password('new password')
Comments Off more...

How to avoid repeating code to check if a user is logged in

by on Aug.12, 2014, under Kohana, PHP

First of all create your own Controller that all other controllers will inherit from.

Name it Mycontroller, for example:

<?php defined('SYSPATH') or die('No direct script access.');
 
class Controller_Mycontroller extends Controller {
 
    public function before()
    {
        parent::before();
        //....
    }
 
} // End

Create another Cotroller “Authenticated”. This Controller must be inherited from all other controllers that should be accessed only by authenticated users.

<?php defined('SYSPATH') or die('No direct script access.');
 
class Controller_Authenticated extends Controller_Mycontroller {
 
	public function before()
        {		
	    parent::before();
 
            if ( !Auth::instance()->logged_in('user'))
            {
                HTTP::redirect('home/index');
            }
        }
}

for example Customers page that should be accessed only from authenticated members:

<?php defined('SYSPATH') or die('No direct script access.');
 
class Controller_Customers extends Controller_Authenticated {
    //your code
    //that's it!!
}
Comments Off more...

FTP Uploading with C#

by on Aug.09, 2014, under C#

void ftpUpload(String filename, String ftpserver, String username, String password)
{
	try
	{
		FileInfo file = new FileInfo(filename);
		FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(ftpserver));
 
		request.Method = WebRequestMethods.Ftp.UploadFile;
		request.UseBinary = true;
		request.UsePassive = true;
		request.KeepAlive = true;
		request.Credentials = new NetworkCredential(username, password);
		request.ContentLength = file.Length;
		int buffer_length = 16 * 1024;
		byte[] buffer = new byte[file.Length];
		FileStream fstream = file.OpenRead();
		Stream stream = request.GetRequestStream();
		int len = 0;
 
		while ((len = fstream.Read(buffer, 0, buffer_length)) != 0)
			stream.Write(buffer, 0, len);
 
		stream.Close();
		fstream.Close();
 
		FtpWebResponse response = (FtpWebResponse)request.GetResponse();
 
		response.Close();
	}
	catch
	{
	}
}
Comments Off more...

Split a char array by delimiter in C++

by on Mar.01, 2014, under C++

There are a few ways to accomplish this.

//..
char* buffer = "this*is*a*simple*test";
string delimiter = "*";
string s(buffer);
size_t pos = 0;
string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
	token = s.substr(0, pos);
	cout<<token<<endl;
	s.erase(0, pos + delimiter.length());
}
cout<<s<<endl;
//..

Prints

this
is
a
simple
test

 

//..
char* buffer = "this*is*a*simple*test";
char* s;
s = strtok (buffer ,"*");
while (s != NULL)
{
	printf ("%s\n",s);
	s = strtok (NULL, "*");
}
//..

Prints

this
is
a
simple
test

 

Comments Off more...

HTTP POST and GET Requests with WinInet and C++

by on Feb.27, 2014, under C++

InternetOpenA
InternetConnectA
HttpOpenRequestA
HttpSendRequestA
InternetCloseHandle

Method to make POST or GET requests:

void Request(int Method, LPCSTR Host, LPCSTR url, LPCSTR header, LPSTR data)
{
try{
	//Retrieve default http user agent
	char httpUseragent[512];
	DWORD szhttpUserAgent = sizeof(httpUseragent);
	ObtainUserAgentString( 0, httpUseragent, &szhttpUserAgent );
 
	char m[5];
 
	if(Method == GET)
		strcpy(m, "GET\0");
	else 
		strcpy(m, "POST\0");
 
	//http://msdn.microsoft.com/en-us/library/windows/desktop/aa385096%28v=vs.85%29.aspx
	HINTERNET internet = InternetOpenA(httpUseragent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if(internet != NULL)
	{
		//http://msdn.microsoft.com/en-us/library/windows/desktop/aa384363%28v=vs.85%29.aspx
		HINTERNET connect = InternetConnectA(internet, Host, INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
		if(connect != NULL)
		{
			//http://msdn.microsoft.com/en-us/library/windows/desktop/aa384233%28v=vs.85%29.aspx
			HINTERNET request = HttpOpenRequestA(connect, m, url, "HTTP/1.1", NULL, NULL, 
				INTERNET_FLAG_HYPERLINK | INTERNET_FLAG_IGNORE_CERT_CN_INVALID |
					INTERNET_FLAG_IGNORE_CERT_DATE_INVALID |
					INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP  |
					INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS |
					INTERNET_FLAG_NO_AUTH |
					INTERNET_FLAG_NO_CACHE_WRITE |
					INTERNET_FLAG_NO_UI |
					INTERNET_FLAG_PRAGMA_NOCACHE |
					INTERNET_FLAG_RELOAD, NULL);
 
			if(request != NULL)
			{
				int datalen = 0;
				if(data != NULL) datalen = strlen(data);
				int headerlen = 0;
				if(header != NULL) headerlen = strlen(header);
 
				//http://msdn.microsoft.com/en-us/library/windows/desktop/aa384247%28v=vs.85%29.aspx
				HttpSendRequestA(request, header, headerlen, data, datalen);
 
				//http://msdn.microsoft.com/en-us/library/windows/desktop/aa384350%28v=vs.85%29.aspx
				InternetCloseHandle(request);
			}
		}
		InternetCloseHandle(connect);
	}
	InternetCloseHandle(internet);
}
catch(...) {}
}

Usage:

//POST Request
char user[64] = "test123";
char pass[64] = "f4g5h6j7k8";
char data[1024];
char* posturi = "user=%s&pass=%s";
wsprintfA( data, posturi,  user, pass);
Request(POST, "localhost", "/testing/index.php", "Content-Type: application/x-www-form-urlencoded", data);
 
//---------------------------
 
//GET Request
char URL[1024];
char* geturi = "/testing/index.php?user=%s&pass=%s";
wsprintfA( URL, geturi, user, pass );
Request(GET, "localhost", URL, NULL, NULL);

Includes/Definitions:

//..
#include <Windows.h>
#include <WinInet.h>
#pragma comment (lib, "Wininet.lib")
#pragma comment (lib, "urlmon.lib")
#define POST 1
#define GET 0
Comments Off more...

Retrieve the User-Agent HTTP

by on Feb.26, 2014, under C++

ObtainUserAgentString retrieves the User-Agent HTTP request header string that is currently being used.

//..
#pragma comment (lib, "urlmon.lib")
//..
char httpUseragent[512];
DWORD szhttpUserAgent = sizeof(httpUseragent);
ObtainUserAgentString( 0, httpUseragent, &szhttpUserAgent );
printf("%s\n", httpUseragent);
//..
Comments Off more...

How to force page not to be cached in PHP

by on Feb.22, 2014, under PHP

header function

header('Expires: Fri, 01 Jan 1990 00:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0, pre-check=0, post-check=0');
header('Pragma: no-cache');
//...
Comments Off more...

Search Google Programmatically with Java

by on Feb.10, 2014, under Java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class Google_Search {
    private final String _url;
    private URL _url_obj;
    private HttpURLConnection _connection;
    private final String _userAgent;
    private int _responseCode;
    private StringBuffer _totalResults;
    private final int _quantity;
    private final int _start;
    private final String _searchTerm;
 
    public Google_Search(String SearchTerm){
        _url = "http://www.google.com";
        _userAgent = "(Mozilla/5.0 (Windows; U; Windows NT 6.0;en-US; rv:1.9.2)" + 
                " Gecko/20100115 Firefox/3.6)";
        _quantity = 100;
        _start = 0;
        _searchTerm = SearchTerm;
    }
 
 
    public int ResponseCode(){
        return _responseCode;
    }
 
    public StringBuffer GetResults(){
        return _totalResults;
    }
 
    public void Search(){
        try {
            _url_obj = new URL(_url + "/search?num="+_quantity+"&start=" + 
                    _start + "&hl=en&meta=&q=%40\"" + _searchTerm + "\"");
            _connection = (HttpURLConnection) _url_obj.openConnection();
            _connection.setRequestMethod("GET");
            _connection.setRequestProperty("User-Agent", _userAgent);
            _responseCode = _connection.getResponseCode();
            BufferedReader in;
            in = new BufferedReader(new InputStreamReader(
                    _connection.getInputStream()));
            _totalResults = new StringBuffer();
            String inputLine;
            while ((inputLine = in.readLine()) != null){
                _totalResults.append(inputLine);
            }
            in.close();                
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
        }
    }
}
Comments Off more...

Call Google Search API in Java

by on Jan.28, 2014, under Java

We will need gogole-gson, a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

package google_search;
 
import com.google.gson.Gson;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
 
public class Google_Search { 
 
    public static void main ( String[] args ) throws Exception { 
        GetGoogleResults("programming");
    }
 
    private static void GetGoogleResults(String term) throws Exception { 
        String google; String charset = "UTF-8"; 
        URL url; Reader reader; 
        Google results;
 
        google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=8&q=";
 
        url = new URL(google + URLEncoder.encode(term, charset));
        reader = new InputStreamReader(url.openStream(), charset);
        results = new Gson().fromJson(reader, Google.class);
 
        if(results.getResponseData()!=null)
        {
            for(int i=0;i<results.getResponseData().getResults().size();i++)
            {
                System.out.println("Title: " + results.getResponseData().getResults().get(i).getTitle());
                System.out.println("Url: " + URLDecoder.decode(results.getResponseData().getResults().get(i).getUrl(), "UTF-8"));
                System.out.println("Content: " + results.getResponseData().getResults().get(i).getContent());
                System.out.println();
            }
        }
    }
}
 
class Google 
{
    private ResponseData responseData;
    public ResponseData getResponseData() { return responseData; }
    public void setResponseData(ResponseData responseData) { this.responseData = responseData; }
 
    static class ResponseData 
    {
        private List<Result> results;
        public List<Result> getResults() { return results; }
        public void setResults(List<Result> results) { this.results = results; }
    }
 
    static class Result 
    {
        private String url;
        private String titleNoFormatting;
        private String content;
        public String getUrl() { return url; }
        public String getTitle() { return titleNoFormatting; }
        public String getContent() { return content; }
        public void setUrl(String url) { this.url = url; }
        public void setTitle(String title) { this.titleNoFormatting = title; }
        public void setContent(String content) { this.content = content; }
    }
}
Comments Off more...

%d bloggers like this: