Control Flow Obfuscation for FJ Using Continuation Passing Conference’17, July 2017, Washington, DC, USA

Total Page:16

File Type:pdf, Size:1020Kb

Control Flow Obfuscation for FJ Using Continuation Passing Conference’17, July 2017, Washington, DC, USA Control Flow Obfuscation for FJ using Continuation Passing Extended Version Kenny Zhuo Ming Lu School of Information Technology Nanyang Polytechnic [email protected] Information Systems Technology and Design Singapore University of Technology and Design [email protected] Abstract of the major security threat to Java applications. Code obfus- Control flow obfuscation deters software reverse engineer- cation is one of the effective mechanism to deter malicious ing attempts by altering the program’s control flow transfer. attack through decompilation. There are many obfuscation The alternation should not affect the software’s run-time be- techniques operating on the level of byte-codes [5, 17, 20]. haviour. In this paper, we propose a control flow obfuscation In the domain of source code obfuscation, we find solutions approach for FJ with exception handling. The approach is such as [9] applying layout obfuscation. We put our inter- based on a source to source transformation using continua- est in control flow obfuscation techniques, which include tion passing style (CPS). We argue that the proposed CPS control flow flattening [3, 11, 21] and continuation passing transformation causes malicious attacks using context in- [12]. Note that the difference between bytecode obfuscation sensitive static analysis and context sensitive analysis with and source code obfuscation is insignificant, because of the fixed call string to lose precision. strong correlation between the Java bytecodes and source codes. In this paper, we propose an extension to the con- CCS Concepts • Software and its engineering → Se- tinuation passing approach to obfuscate FJ with exception mantics; • Security and privacy → Software and applica- handling. tion security. We assume the attackers gain access to the byte-codes Keywords Control flow obfuscation, program transforma- to which layout obfuscation has been applied. The attack- tion, continuation passing style ers decompile the byte-codes into source codes and attempt to extract secret information by running control flow anal- ACM Reference Format: ysis on the decompiled code. Our goal here is to cause the Kenny Zhuo Ming Lu. 2021. Control Flow Obfuscation for FJ using control flow analysis become imprecise or more costly in Continuation Passing: Extended Version. In Proceedings of ACM computation. Conference (Conference’17). ACM, New York, NY, USA, 13 pages. hps://doi.org/10.1145/nnnnnnn.nnnnnnn 2 Motivating Example 1 Introduction Example 1. To motivate the main idea, let’s consider the Java applications are ubiquitous thanks to the wide adoption following Java code snippet arXiv:2012.06340v2 [cs.CR] 26 Feb 2021 of android devices. Since Java byte-codes are close to their source codes, it is easy to decompile Java byte-codes back to class FibGen { source codes with tools. For example, javap shipped with int f1, f2, lpos; JVM [15] can be used to decompile Java class files back to FibGen() { Java source. This makes the Man-At-The-End attack as one f1 = 0; f2 = 1; lpos = 1; } Permission to make digital or hard copies of all or part of this work for int get( int x ) { personal or classroom use is granted without fee provided that copies are int i = lpos; // (1) not made or distributed for profit or commercial advantage and that copies int r = −1; bear this notice and the full citation on the first page. Copyrights for compo- try { // (2) nents of this work owned by others than ACM must be honored. Abstract- ing with credit is permitted. To copy otherwise, or republish, to post on if (x< i) { // (3) servers or to redistribute to lists, requires prior specific permission and/or throw new Exception() ; // (4) a fee. Request permissions from [email protected]. } else { Conference’17, July 2017, Washington, DC, USA while (i <x) { // (5) © 2021 Association for Computing Machinery. int t = f1 + f2; // (6) ACM ISBN 978-x-xxxx-xxxx-x/YY/MM...$15.00 f1 = f2; f2 = t; i++; hps://doi.org/10.1145/nnnnnnn.nnnnnnn } Conference’17, July 2017, Washington, DC, USA Kenny Zhuo Ming Lu 1 an anonymous function whose input is of type void and the body returns a boolean value. For brevity, we omit the type annotations of the formal arguments where there is no con- 2 fusion. The return key word is omitted when there is only one statement in the function body. We omit curly brackets in curried expressions, e.g. x -> raise -> k -> { ... } 3 t is the same as x -> { raise -> { k -> { ... } } }, f where x, raise and k are formal arguments for the lambda 4 5 abstractions. For convenience, we treat method declaration f and lambda declaration as interchangeable. For instance, the t 7 8 lambda declaration 6 int => int => int f =x −> y −>{x+y} 9 is equivalent to the following method declaration int f ( int x, int y ) { return x + y;} Figure 1. CFG of get In the last section, we mentioned that the layout obfusca- tion such as identifier renaming should have been applied to } the obfuscated code; however in this paper we keep all the lpos = i; // (7) identifiers in the obfuscated code unchanged for the ease of r = f2; reasoning. For the sake of assessing the obfuscation potency, } catch (Exception e) { // (8) we “flatten” the nested function calls into sequences of as- println("the input should be greater than " signment statements. For example, let x and y be variables + i + "."); of type int, let f be a function of type int => int => int } and g be a function of type int => int; instead of int r = return r; // (9) f(x)(g(y)); , we write: } } int => int f_x = f(x); int g_y = g(y); In the above we define a Fibonacci number generator in int r = f_x(g_y); class FibGen. In the method get, we compute the Fibonacci number given the position as the input. Note that the gener- As we observe in Figure 2, all the building blocks are contin- ator maintains a state, in which we record the last two com- uation functions with type CpsFunc.The simple codeblocks puted Fibonacci numbers, namely, f1 and f2 and the last (1), (6), (7) and (8) from the original source code, which con- computed position lpos. In method get lines 10 and 11, we tain no control flow branching statements, are translated raise an exception if the given input is smaller than i which into nested CPS functions get1, get6, get7 and get8. Block has been initialized to lpos. Towards the end of the method, (4) containing a throw statement is translated into get4 which we catch the exception and print out the error message. applies the exception object to the exception handling con- The number comment on the right of each statement in- tinuation raise of type ExCont.Block(9)hasa return state- dicates the code block to which the statement belongs. In ment, which is translated into a function in which we assign Figure 1, we represent the function get’s control flow as a the variable being returned r to the res variable and call graph. Each circle denotes a code block from the source pro- the normal continuation k of type NmCont.Block (2) is a try gram. ✷ catch statement which is encoded as a call to the trycatch combinator in line 24. Similarly block (3) the if-else state- Inspired by the approach [12], our main idea is to trans- ment is encoded as a call to the ifelse combinator and late control flow constructs, such as sequence, if-else, loop block(5) the while loopis encodedas a call to the loop com- into CPS combinators. In the context of FJ with exception binator. handling, we translate try-catch statements into CPS com- In Figure 3, we present the definitions of the CPS combi- binators as well. nators used in the obfuscation. Combinator loop accepts a In Figure 2 we find the obfuscated code snippet of get condition test cond, a continuation executor visitor to be method in CPS style. The obfuscated code is in a variant executed when the condition is satisfied, a continuation ex- of FJ, named FJ_, which is FJ with higher order functions, ecutor exit to be activated when the condition is not satis- nested function declaration and mutable variables in func- fied. Combinator seq takes two continuation executors and tion closures. void => void denotes a function type whose executes them in sequence. Combinator trycatch takes a values accept no argument and return no result. Exception continuation executor tr and an exception handling contin- => void denotes a function type that accepts an exception uation hdl. It executes tr by replacing the current excep- and returns no result. type NmCont = void => void de- tion continuation with ex_hdl. Combinator ifelse accepts fines a type alias. (void n) -> {return i < x}; defines a condition test cond, a continuation for the then-branch th Control Flow Obfuscation for FJ using Continuation Passing Conference’17, July 2017, Washington, DC, USA type ExCont = Exception => void ; CpsFunc loop( void => Boolean cond, type NmCont = void => void ; CpsFunc visitor , CpsFunc exit) { type CpsFunc = ExCont => NmCont => void ; return raise −> k −> { int get( int x ) { if (cond()) { int i, t, r, res; Exception ex; NmCont => void visitor_raise = visitor(raise int => ExCont => ( int => void ) => void get_cps = ) ; x −> raise −> k −> { NmCont nloop = n −> { void => bool cond5 = n−> { i <x}; CpsFunc ploop = loop(cond, visitor , exit); void => bool cond3 = n −> {x < i}; NmCont => void = ploop_raise = ploop(raise CpsFunc get5 = loop(cond5, get6 , get7) ) ; CpsFunc get3 = ifelse(cond3,get4 ,get5); return ploop_raise (k) ; CpsFunc get1_2 = seq(get2 , get9); }; CpsFunc pseq = seq(get1 , get1_2); return visitor_raise (nloop); NmCont => void pseq_raise = pseq(raise); } else { NmCont nk_res = n−>k(res);
Recommended publications
  • Chapter 4 Programming in Perl
    Chapter 4 Programming in Perl 4.1 More on built-in functions in Perl There are many built-in functions in Perl, and even more are available as modules (see section 4.4) that can be downloaded from various Internet places. Some built-in functions have already been used in chapter 3.1 and some of these and some others will be described in more detail here. 4.1.1 split and join (+ qw, x operator, \here docs", .=) 1 #!/usr/bin/perl 2 3 $sequence = ">|SP:Q62671|RATTUS NORVEGICUS|"; 4 5 @parts = split '\|', $sequence; 6 for ( $i = 0; $i < @parts; $i++ ) { 7 print "Substring $i: $parts[$i]\n"; 8 } • split is used to split a string into an array of substrings. The program above will write out Substring 0: > Substring 1: SP:Q62671 Substring 2: RATTUS NORVEGICUS • The first argument of split specifies a regular expression, while the second is the string to be split. • The string is scanned for occurrences of the regexp which are taken to be the boundaries between the sub-strings. 57 58 CHAPTER 4. PROGRAMMING IN PERL • The parts of the string which are matched with the regexp are not included in the substrings. • Also empty substrings are extracted. Note, however that trailing empty strings are removed by default. • Note that the | character needs to be escaped in the example above, since it is a special character in a regexp. • split returns an array and since an array can be assigned to a list we can write: splitfasta.ply 1 #!/usr/bin/perl 2 3 $sequence=">|SP:Q62671|RATTUS NORVEGICUS|"; 4 5 ($marker, $code, $species) = split '\|', $sequence; 6 ($dummy, $acc) = split ':', $code; 7 print "This FastA sequence comes from the species $species\n"; 8 print "and has accession number $acc.\n"; splitfasta.ply • It is not uncommon that we want to write out long pieces of text using many print statements.
    [Show full text]
  • Declare Function Inside a Function Python
    Declare Function Inside A Function Python Transisthmian and praetorian Wye never ensphere helter-skelter when Shawn lord his nightshade. Larboard Hal rumors her dizziesacapnia very so encouragingly actinally. that Colbert aurifies very inferentially. Kenyan Tad reframes her botts so irefully that Etienne Closures prove to it efficient way something we took few functions in our code. Hope you have any mutable object. Calling Functions from Other Files Problem Solving with Python. What embassy your website look like? Then you can declare any result of a million developers have been loaded? The coach who asked this gas has marked it as solved. We focus group functions together can a Python module see modules and it this way lead our. What are Lambda Functions and How to Use Them? It working so art the result variable is only accessible inside the function in. Variables inside python node, learn more detail, regardless of instances of a program demonstrates it. The python function inside another, which start here, and beginners start out. Get code examples like python define a function within a function instantly right anytime your google search results with the Grepper Chrome. The function by replacing it contains one function start here are discussed: how do not provide extremely cost efficient as their name? How to the page helpful for case it requires you can declare python data science. Each item from the python function has arbitrary length arguments must first, but are only the output is simply the function to. We declare their perfomance varies with the gathered arguments using a wrapped the arguments does the computed fahrenheit to declare function inside a function python? List of python can declare a function inside a million other functions we declare function inside a function python.
    [Show full text]
  • 1. Introduction to Structured Programming 2. Functions
    UNIT -3Syllabus: Introduction to structured programming, Functions – basics, user defined functions, inter functions communication, Standard functions, Storage classes- auto, register, static, extern,scope rules, arrays to functions, recursive functions, example C programs. String – Basic concepts, String Input / Output functions, arrays of strings, string handling functions, strings to functions, C programming examples. 1. Introduction to structured programming Software engineering is a discipline that is concerned with the construction of robust and reliable computer programs. Just as civil engineers use tried and tested methods for the construction of buildings, software engineers use accepted methods for analyzing a problem to be solved, a blueprint or plan for the design of the solution and a construction method that minimizes the risk of error. The structured programming approach to program design was based on the following method. i. To solve a large problem, break the problem into several pieces and work on each piece separately. ii. To solve each piece, treat it as a new problem that can itself be broken down into smaller problems; iii. Repeat the process with each new piece until each can be solved directly, without further decomposition. 2. Functions - Basics In programming, a function is a segment that groups code to perform a specific task. A C program has at least one function main().Without main() function, there is technically no C program. Types of C functions There are two types of functions in C programming: 1. Library functions 2. User defined functions 1 Library functions Library functions are the in-built function in C programming system. For example: main() - The execution of every C program starts form this main() function.
    [Show full text]
  • Eloquent Javascript © 2011 by Marijn Haverbeke Here, Square Is the Name of the Function
    2 FUNCTIONS We have already used several functions in the previous chapter—things such as alert and print—to order the machine to perform a specific operation. In this chap- ter, we will start creating our own functions, making it possible to extend the vocabulary that we have avail- able. In a way, this resembles defining our own words inside a story we are writing to increase our expressive- ness. Although such a thing is considered rather bad style in prose, in programming it is indispensable. The Anatomy of a Function Definition In its most basic form, a function definition looks like this: function square(x) { return x * x; } square(12); ! 144 Eloquent JavaScript © 2011 by Marijn Haverbeke Here, square is the name of the function. x is the name of its (first and only) argument. return x * x; is the body of the function. The keyword function is always used when creating a new function. When it is followed by a variable name, the new function will be stored under this name. After the name comes a list of argument names and finally the body of the function. Unlike those around the body of while loops or if state- ments, the braces around a function body are obligatory. The keyword return, followed by an expression, is used to determine the value the function returns. When control comes across a return statement, it immediately jumps out of the current function and gives the returned value to the code that called the function. A return statement without an expres- sion after it will cause the function to return undefined.
    [Show full text]
  • Control Flow, Functions
    UNIT III CONTROL FLOW, FUNCTIONS 9 Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained conditional (if-elif-else); Iteration: state, while, for, break, continue, pass; Fruitful functions: return values, parameters, local and global scope, function composition, recursion; Strings: string slices, immutability, string functions and methods, string module; Lists as arrays. Illustrative programs: square root, gcd, exponentiation, sum an array of numbers, linear search, binary search. UNIT 3 Conditionals: Boolean values: Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. A string in Python can be tested for truth value. The return type will be in Boolean value (True or False) To see what the return value (True or False) will be, simply print it out. str="Hello World" print str.isalnum() #False #check if all char are numbers print str.isalpha() #False #check if all char in the string are alphabetic print str.isdigit() #False #test if string contains digits print str.istitle() #True #test if string contains title words print str.isupper() #False #test if string contains upper case print str.islower() #False #test if string contains lower case print str.isspace() #False #test if string contains spaces print str.endswith('d') #True #test if string endswith a d print str.startswith('H') #True #test if string startswith H The if statement Conditional statements give us this ability to check the conditions.
    [Show full text]
  • The Return Statement a More Complex Example
    We Write Programs to Do Things Anatomy of a Function Definition • Functions are the key doers name parameters Function Call Function Definition def plus(n): Function Header """Returns the number n+1 Docstring • Command to do the function • Defines what function does Specification >>> plus(23) Function def plus(n): Parameter n: number to add to 24 Header return n+1 Function Precondition: n is a number""" Body >>> (indented) x = n+1 Statements to execute when called return x • Parameter: variable that is listed within the parentheses of a method header. The vertical line Use vertical lines when you write Python indicates indentation on exams so we can see indentation • Argument: a value to assign to the method parameter when it is called The return Statement A More Complex Example • Format: return <expression> Function Definition Function Call § Used to evaluate function call (as an expression) def foo(a,b): >>> x = 2 § Also stops executing the function! x ? """Return something >>> foo(3,4) § Any statements after a return are ignored Param a: number • Example: temperature converter function What is in the box? Param b: number""" def to_centigrade(x): x = a A: 2 """Returns: x converted to centigrade""" B: 3 y = b C: 16 return 5*(x-32)/9.0 return x*y+y D: Nothing! E: I do not know Understanding How Functions Work Text (Section 3.10) vs. Class • Function Frame: Representation of function call Textbook This Class • A conceptual model of Python to_centigrade 1 Draw parameters • Number of statement in the as variables function body to execute next to_centigrade x –> 50.0 (named boxes) • Starts with 1 x 50.0 function name instruction counter parameters Definition: Call: to_centigrade(50.0) local variables (later in lecture) def to_centigrade(x): return 5*(x-32)/9.0 1 Example: to_centigrade(50.0) Example: to_centigrade(50.0) 1.
    [Show full text]
  • Subroutines – Get Efficient
    Subroutines – get efficient So far: The code we have looked at so far has been sequential: Subroutines – getting efficient with Perl do this; do that; now do something; finish; Problem Bela Tiwari You need something to be done over and over, perhaps slightly [email protected] differently depending on the context Solution Environmental Genomics Thematic Programme Put the code in a subroutine and call the subroutine whenever needed. Data Centre http://envgen.nox.ac.uk Syntax: There are a number of correct ways you can define and use Subroutines – get efficient subroutines. One is: A subroutine is a named block of code that can be executed as many times #!/usr/bin/perl as you wish. some code here; some more here; An artificial example: lalala(); #declare and call the subroutine Instead of: a bit more code here; print “Hello everyone!”; exit(); #explicitly exit the program ############ You could use: sub lalala { #define the subroutine sub hello_sub { print "Hello everyone!\n“; } #subroutine definition code to define what lalala does; #code defining the functionality of lalala more defining lalala; &hello_sub; #call the subroutine return(); #end of subroutine – return to the program } Syntax: Outline review of previous slide: Subroutines – get efficient Syntax: #!/usr/bin/perl Permutations on the theme: lalala(); #call the subroutine Defining the whole subroutine within the script when it is first needed: sub hello_sub {print “Hello everyone\n”;} ########### sub lalala { #define the subroutine The use of an ampersand to call the subroutine: &hello_sub; return(); #end of subroutine – return to the program } Note: There are subtle differences in the syntax allowed and required by Perl depending on how you declare/define/call your subroutines.
    [Show full text]
  • Explain Function Declaration Prototype and Definition
    Explain Function Declaration Prototype And Definition ligatedreprobated,Sidearm feminizes and but road-hoggish Weylin vengefully. phonemic Roderich nose-dived never reckons her acetones. his carat! Unfabled Dubitative Dewey and ill-equippedclangour, his Jerzy stringer See an example of passing control passes to function declaration and definition containing its prototype Once which is declared in definition precedes its definition of declaring a body of. Check out to explain basic elements must be explained below. They gain in this browser for types to carry out into parts of functions return statement of your pdf request that same things within your program? Arguments and definitions are explained below for this causes an operator. What it into two. In definition and declare a great; control is declared in this parameter names as declaring extern are explained in expressions and ms student at runtime error. Classes and definition was tested in a, and never executed but it will be called formal parameters are expanded at later. There are definitions to prototype definition tells the value method of an example are a function based on the warnings have had been declared. Please enter valid prototype definition looks a function definitions affects compilation. In this method is fixed words, but unlike references or rethrow errors or constants stand out its argument is only if more code by subclasses. How do is the variable of the three basic behavior of variable num to explain actual values of yours i desired. Also when a function num_multiplication function and definition example. By value of the definitions are explained in the nested function, the program passes to.
    [Show full text]
  • Fast Functional Simulation with a Dynamic Language
    Fast Functional Simulation with a Dynamic Language Craig S. Steele and JP Bonn Exogi LLC Las Vegas, Nevada, USA [email protected] Abstract—Simulation of large computational systems-on-a-chip runtime, rather than requiring mastery of a simulator-specific (SoCs) is increasing challenging as the number and complexity of domain-specific language (DSL) describing the binary-code components is scaled up. With the ubiquity of programmable translation task. components in computational SoCs, fast functional instruction- set simulation (ISS) is increasingly important. Much ISS has been done with straightforward functional models of a non-pipelined II. RELATED WORK fetch-decode-execute iteration written in a low-to-mid-level C- Interpretative instruction-set simulators (ISS) abound, with family static language, delivering mid-level efficiency. Some ISS various levels of detail in the processor model. The sim-fast programs, such as QEMU, perform dynamic binary translation simulator from SimpleScalar LLC is a well-known to allow software emulation to reach more usable speeds. This representative of a straightforward C-based fetch-decode- relatively complex methodology has not been widely adopted for execute iterative ISS interpreter, achieving more than 10 MIPS system modeling. for basic functional instruction-set-architecture (ISA) simulation [1]. This naïve approach is a software analog of a We demonstrate a fresh approach to ISS that achieves non-pipelined hardware processor implementation, simple but performance comparable to a fast dynamic binary translator by slow. exploiting recent advances in just-in-time (JIT) compilers for dynamic languages, such as JavaScript and Lua, together with a Many variations of binary translation for ISS exist, specific programming idiom inspired by pipelined processor translating instructions in the simulated ISA into code design.
    [Show full text]
  • Python Scope 3
    Class XII Computer Science : Python (Code: 083) Chapter: Functions Chapter : Functions Topics Covered: 1. Functions: scope Learning Outcomes: In this tutorial, we’ll learn: 1. What scopes are and how they work in Python 2. Why it’s important to know about Python scope 3. What is the LEGB rule 4. Using Python global statement and nonlocal statement Youtube Video Tutorial: 1. https://www.youtube.com/watch?v=07w3KkQqgi0 2. https://www.youtube.com/watch?v=R5uLNhRaGD0 3. https://www.youtube.com/watch?v=NdlWHlEgTn8 Python Scope Scope of a name (variables, functions etc) is the area of code where the name is created and can be used or accessed. A variable is only available from inside the region it is created. This is called scope. The scope of a name or variable depends on the place in our code where we create that variable. The Python scope concept is generally presented using a rule known as the LEGB rule. LEGB stand for Local, Enclosing, Global, and Built-in scopes. These are the names of Python scopes and also the sequence of steps that Python follows when accessing names in a program. Therefore in python there are 4 scopes 1. Local scope 2. Enclosing scope 3. Global scope 4. Built in scope 1 By Rajesh Singh ([email protected]) Class XII Computer Science : Python (Code: 083) Chapter: Functions Local Scope A variable created inside a function belongs to the local scope of that function, and can only be used inside that function. Example A variable created inside a function is available inside that function only: def myfunc(): x= 300 print(x) myfunc() print(x) # error, because x is created inside myfunc(), so it is available inside that function only Enclosing Scope (Function Inside a Function) A variable is available inside that function only in which it is created.
    [Show full text]
  • 210 CHAPTER 7. NAMES and BINDING Chapter 8
    210 CHAPTER 7. NAMES AND BINDING Chapter 8 Expressions and Evaluation Overview This chapter introduces the concept of the programming environment and the role of expressions in a program. Programs are executed in an environment which is provided by the operating system or the translator. An editor, linker, file system, and compiler form the environment in which the programmer can enter and run programs. Interac- tive language systems, such as APL, FORTH, Prolog, and Smalltalk among others, are embedded in subsystems which replace the operating system in forming the program- development environment. The top-level control structure for these subsystems is the Read-Evaluate-Write cycle. The order of computation within a program is controlled in one of three basic ways: nesting, sequencing, or signaling other processes through the shared environment or streams which are managed by the operating system. Within a program, an expression is a nest of function calls or operators that returns a value. Binary operators written between their arguments are used in infix syntax. Unary and binary operators written before a single argument or a pair of arguments are used in prefix syntax. In postfix syntax, operators (unary or binary) follow their arguments. Parse trees can be developed from expressions that include infix, prefix and postfix operators. Rules for precedence, associativity, and parenthesization determine which operands belong to which operators. The rules that define order of evaluation for elements of a function call are as follows: • Inside-out: Evaluate every argument before beginning to evaluate the function. 211 212 CHAPTER 8. EXPRESSIONS AND EVALUATION • Outside-in: Start evaluating the function body.
    [Show full text]
  • PHP: Constructs and Variables Introduction This Document Describes: 1
    PHP: Constructs and Variables Introduction This document describes: 1. the syntax and types of variables, 2. PHP control structures (i.e., conditionals and loops), 3. mixed-mode processing, 4. how to use one script from within another, 5. how to define and use functions, 6. global variables in PHP, 7. special cases for variable types, 8. variable variables, 9. global variables unique to PHP, 10. constants in PHP, 11. arrays (indexed and associative), Brief overview of variables The syntax for PHP variables is similar to C and most other programming languages. There are three primary differences: 1. Variable names must be preceded by a dollar sign ($). 2. Variables do not need to be declared before being used. 3. Variables are dynamically typed, so you do not need to specify the type (e.g., int, float, etc.). Here are the fundamental variable types, which will be covered in more detail later in this document: • Numeric 31 o integer. Integers (±2 ); values outside this range are converted to floating-point. o float. Floating-point numbers. o boolean. true or false; PHP internally resolves these to 1 (one) and 0 (zero) respectively. Also as in C, 0 (zero) is false and anything else is true. • string. String of characters. • array. An array of values, possibly other arrays. Arrays can be indexed or associative (i.e., a hash map). • object. Similar to a class in C++ or Java. (NOTE: Object-oriented PHP programming will not be covered in this course.) • resource. A handle to something that is not PHP data (e.g., image data, database query result).
    [Show full text]