File upload handling scripts

Here you can download scripts which are able to handle file uploads to a webserver, and save some data into MySQL database.
The following script introduces the server side of uploading recorded calls to a webserver, which are recorded by the Call Recorder.


<?php

	$upload_directory = 'files/';

	if (is_uploaded_file($_FILES['file']['tmp_name']))
	{
		$upload_file = $upload_directory . basename($_FILES['file']['name']);
		move_uploaded_file($_FILES['file']['tmp_name'], $upload_file);
	}
	
	function LogError($error)
	{
		$fp = fopen('file_upload_error.txt', 'a');
		fwrite($fp, $error);
		fclose($fp);
	}

	function ExecuteQuery($sql, $link)
	{
		$result = $link->query($sql);
		if (!$result) LogError('Invalid query: ' . mysql_error());
	} 

	// Save some data into MySQL database
	$link = mysqli_connect("127.0.0.1", "root", "") or LogError("Error " . mysqli_error($link));

	$headers = apache_request_headers();
	$session_id = $link->real_escape_string($headers["SessionID"]);
	$dialed_number = $link->real_escape_string($headers["DialedNumber"]);
	$caller = $link->real_escape_string($headers["Caller"]);
	$duration_in_seconds = $link->real_escape_string($headers["DurationInSeconds"]);
	$filename = $link->real_escape_string($headers["Filename"]);
	$start_time = $link->real_escape_string($headers["StartTime"]);

	ExecuteQuery("CREATE DATABASE IF NOT EXISTS Ozeki_CallSessionRecordings;", $link);
	ExecuteQuery("CREATE TABLE IF NOT EXISTS Ozeki_CallSessionRecordings.CallSessions (session_id VARCHAR(10), dialed_number VARCHAR(20), caller VARCHAR(20), duration_in_seconds INT, filename VARCHAR(250), start_time VARCHAR(20));", $link);
	ExecuteQuery("INSERT INTO Ozeki_CallSessionRecordings.CallSessions (session_id, dialed_number, caller, duration_in_seconds, filename, start_time) VALUES ('" . $session_id . "', '" . $dialed_number .
				"', '" . $caller . "', " . $duration_in_seconds . ", '" . $filename . "', '" . $start_time . "');", $link);

	mysqli_close($link);
?>
class FileuploadController < ApplicationController

  protect_from_forgery except: :index

  require 'logger'
  require 'mysql2'
  
  # http://localhost:3000/fileupload/index
  def index
    
    query = ""
    begin
      
      file = params[:file]
      name = file.original_filename
      directory = "public/files"
      path = File.join(directory, name)
      File.open(path, "wb") { |f| f.write(file.read) }
    
      config = YAML::load_file("config/database.yml")["development"]
      config["host"] = config["hostname"]
      con = Mysql2::Client.new(config)
      con.query("CREATE DATABASE IF NOT EXISTS Ozeki_CallSessionRecordings;")
      con.query("CREATE TABLE IF NOT EXISTS Ozeki_CallSessionRecordings.CallSessions (session_id VARCHAR(10), dialed_number VARCHAR(20), caller VARCHAR(20), duration_in_seconds INT, filename VARCHAR(250), start_time VARCHAR(20));")
      
      session_id = Mysql2::Client.escape(request.headers[:SessionID])
      dialed_number = Mysql2::Client.escape(request.headers[:DialedNumber])
      caller = Mysql2::Client.escape(request.headers[:Caller])
      duration_in_seconds = Mysql2::Client.escape(request.headers[:DurationInSeconds])
      filename = Mysql2::Client.escape(request.headers[:Filename])
      start_time = Mysql2::Client.escape(request.headers[:StartTime])

      query ="INSERT INTO Ozeki_CallSessionRecordings.CallSessions (session_id, dialed_number, caller, duration_in_seconds, filename, start_time) VALUES ('" + session_id + "', '" + dialed_number + "', '" + caller + "', " + duration_in_seconds.to_s + ", '" + filename + "', '" + start_time + "');" 
      con.query(query)

    rescue => e
      
      log = Logger.new('public/file_upload_error.txt')
      log.error e

    ensure
      con.close if con
    end

  end
  
end
using System;
using System.Data.SqlClient;
using System.IO;
using System.Web.Mvc;

namespace FileUploadHandler.Controllers
{
    public class HomeController : Controller
    {
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Index()
		{
			try
			{
				var file = Request.Files[0];
				var directory = @"C:\CallRecordings";
				if (!Directory.Exists(directory))
					Directory.CreateDirectory(directory);

				file.SaveAs(Path.Combine(directory, Path.GetFileName(file.FileName)));

				const string connection_string = @"Server=.\SQLExpress;Database=;User ID=sa;Password=pass";
				using (var connection = new SqlConnection(connection_string))
				{
					connection.Open();
					var command = new SqlCommand("SELECT COUNT(*) FROM master.dbo.sysdatabases WHERE (name = 'Ozeki_CallSessionRecordings');", connection);
					if ((int)command.ExecuteScalar() == 0)
					{
						var create_db_command = "CREATE DATABASE Ozeki_CallSessionRecordings ON PRIMARY (NAME = Ozeki_CallSessionRecordings, " +
							   "FILENAME = 'C:\\SQL\\Ozeki_CallSessionRecordings.mdf', SIZE = 10MB, MAXSIZE = 1024MB, FILEGROWTH = 10%) " +
							   "LOG ON (NAME = Ozeki_CallSessionRecordings_Log, FILENAME = 'C:\\SQL\\Ozeki_CallSessionRecordings.ldf', " +
							   "SIZE = 10MB, MAXSIZE = 100MB, FILEGROWTH = 10%)";

						command = new SqlCommand(create_db_command, connection);
						command.ExecuteNonQuery();
					}
				}

				using (var connection = new SqlConnection(String.Concat(connection_string, ";Database=Ozeki_CallSessionRecordings")))
				{
					connection.Open();

					var command = new SqlCommand("SELECT COUNT(*) FROM information_schema.tables WHERE table_name = 'CallSessions';", connection);
					if ((int)command.ExecuteScalar() == 0)
					{
						command = new SqlCommand("CREATE TABLE CallSessions (session_id VARCHAR(10), dialed_number VARCHAR(20), caller VARCHAR(20), duration_in_seconds INT, filename VARCHAR(250), start_time DATETIMEOFFSET);", connection);
						command.ExecuteNonQuery();
					}
					
					var session_id = Request.Headers["SessionID"];
					var dialed_number = Request.Headers["DialedNumber"];
					var caller = Request.Headers["Caller"];
					var duration_in_seconds = Request.Headers["DurationInSeconds"];
					var filename = Request.Headers["Filename"];
					var start_time = Convert.ToDateTime(Request.Headers["StartTime"]);

					command = new SqlCommand("INSERT INTO CallSessions (session_id, dialed_number, caller, duration_in_seconds, filename, start_time) VALUES (@session_id, @dialed_number, @caller, @duration_in_seconds, @filename, @start_time);", connection);

					command.Parameters.Add(new SqlParameter("session_id", session_id));
					command.Parameters.Add(new SqlParameter("dialed_number", dialed_number));
					command.Parameters.Add(new SqlParameter("caller", caller));
					command.Parameters.Add(new SqlParameter("duration_in_seconds", duration_in_seconds));
					command.Parameters.Add(new SqlParameter("filename", filename));
					command.Parameters.Add(new SqlParameter("start_time", start_time));
					command.ExecuteNonQuery();
				}

				return Json(new { Result = "Complete" });
			}
			catch (Exception ex)
			{
				return Json(new { Result = ex.Message });
			}
		}

    }
}
import os, cgi
import sys, traceback
import MySQLdb

def application(environ, start_response):
    
    saveFile(environ)
    saveRecordInfoToDatabase()

    status = '200 OK'
    result = "OK"
    response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(result)))]
    start_response(status, response_headers)

    return [result]

def saveFile(environ):
    fields = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ, keep_blank_values=1)
    fileitem = fields['file']
    fn = os.path.basename(fileitem.filename) 
    open('uploads/' + fn, 'wb').write(fileitem.file.read())

def saveRecordInfoToDatabase(environ):
    db = MySQLdb.connect("localhost","testuser","test123","TESTDB")
    cursor = db.cursor()
    cursor.execute("CREATE DATABASE IF NOT EXISTS Ozeki_CallSessionRecordings;")
    cursor.execute("CREATE TABLE IF NOT EXISTS Ozeki_CallSessionRecordings.CallSessions (session_id VARCHAR(10), dialed_number VARCHAR(20), caller VARCHAR(20), duration_in_seconds INT, filename VARCHAR(250), start_time VARCHAR(20));")
    cursor.execute("INSERT INTO Ozeki_CallSessionRecordings.CallSessions (session_id, dialed_number, caller, duration_in_seconds, filename, start_time) VALUES ('{}', '{}', '{}', '{}', '{}', '{}');".format(environ['HTTP_SESSIONID'], environ['HTTP_DIALEDNUMBER'], environ['HTTP_CALLER'],  environ['HTTP_DURATIONINSECONDS'], environ['HTTP_FILENAME'], environ['HTTP_STARTTIME']))
    db.close()

You can use these scripts (written in PHP, Ruby, ASP .NET and Python) to handle your files which you want to upload to a web server. In this description you will find example codes in different programming languages to store your file in your web server and create a new item in your database with the received informations.

When the Ozeki Phone System sends the selected file to the given URL (your web server) via HTTP POST, it will operate with the following parameters:

  • SessionID: the identification of this session
  • Caller: the phone number of the caller who started the call
  • DialedNumber: the dialed phone number
  • DurationInSeconds: the duration of the call given in seconds
  • Filename: the name of the recorded call file
  • StartTime: the time when the call has started


If your selected file is uploaded, the script will move this file to the selected destination. It will connect to the database with default values(address of the server, username and password), than it will get the session id, the dialed number, the caller, the duration, the filename and the start time values from the headers. After that it uses MySQL queries to create database called Ozeki_CallSessionRecordings if it doesn't exist, and create a table in this database named CallSession. It will contain columns like session id, dialed number, caller, the duration of the call in seconds, the filename and the start time.

Then these values will be inserted into the table.

If there is an error with the connection or during the execution of the query, the error will be copied into the "file_upload_error.txt" file.

This was an example to manage file uploading to your web server and create new items in database.