The thermal structure of gas inflowing along magnetic field lines of a young stellar object is determined self-consistently. A young low-mass star (e.g., a classical T Tauri star) is assumed to possess a dipole magnetic field which disrupts a geometrically thin accretion disk and channels the incoming gas toward the stellar surface, leading to the formation of an accretion funnel which terminates in a shock at a high stellar latitude. It is shown that the accretion funnel is probably dust-free, and that collisional coupling between the ions and the neutrals is sufficient to ensure that even the neutral gas component follows the magnetic field lines. By solving the heat equation coupled to rate equations for hydrogen, the main physical processes which heat and cool the gas are identified. It is found that the principal heat source is adiabatic compression due to the converging nature of the flow. The main coolants include bremsstrahlung radiation and line emission from the Ca II and Mg II ions. These ions play a major role in determining the gas thermodynamics and behave as a thermostat which regulates the gas temperature. The ionization of the gas is found to be controlled by Balmer continuum photons, with Lyman continuum photons and collisional processes playing a minor role. For a typical T Tauri star, with an inflow rate of 10-7 Msun yr-1, temperatures of ∼6500 K and hydrogen ionization fractions (nH+/nH) of ∼10-3-10-2 can be established in the accretion funnel. Furthermore, for large accretion rates (≥10-6 Msun yr-1) the gas does not heat appreciably, which may be the reason those sources with strong inverse P Cygni line profiles are inferred to have relatively low accretion rates (≤10-7 Msun yr-1). The largest temperatures and ionization fractions in the flow are established close to the stellar surface, where the gas velocity is large. Hence, these calculations may explain the ubiquity of high-velocity redshifted absorption features observed in the upper Balmer lines of classical T Tauri stars. Preliminary calculations of the hydrogen near-infrared Brγ line suggest that the line strength produced in the magneto spheric accretion flow could account for that observed from classical T Tauri stars. However, this line is also likely to be optically thick, which is supported by the observed line profiles.