This is a trick in Fourier analysis that can look confusing at first, but not too bad once you get the hang of it.
Start with
\begin{equation}
\phi(x,t) = c_0 + \sum_{n=1}^\infty c_n e^{-\alpha n^2t} \cos(nx)
\end{equation}
Then,
\begin{equation}
\phi(x,0) = g(x) = c_0 + \sum_{n=1}^\infty c_n\cos(nx)
\end{equation}
Note that
\begin{equation}
\int_{0}^{\pi} \cos(mx)\cos(nx)dx =
\
\begin{cases}
0 & \text{if $n \neq m$} \\
\frac{\pi}{2} & \text{if $n=m$} \\
\end{cases}
\
\end{equation}
Now, to exploit this orthogonality property, we multiply both sides by $\cos(mx)$ and integrate from $0$ to $\pi$.
We get,
\begin{equation}
\
\int_{0}^\pi g(x) \cos(mx) dx = \int_{0}^\pi (c_0\cos(mx) + c_n\sum_{n=1}^{\infty}\cos(nx)\cos(mx) ) dx
\
\end{equation}
The first integral is $0$ because $\sin(m\pi) = 0$,
\begin{equation}
\
\int_{0}^\pi g(x) \cos(mx) dx = c_n \int_{0}^\pi \sum_{n=1}^{\infty}\cos(nx)\cos(mx) dx
\
\end{equation}
The tricky step here is to switch the integral and the sum. This is justified by the Fubini-Tonelli theorems and require an understanding of real analysis so I won't go over the full justification here. If you're interested, here's a reference to read for a full justification: When can a sum and integral be interchanged?.
Interchanging the sum and the integral, we get:
\begin{equation}
\
\int_{0}^\pi g(x) \cos(mx) dx = c_n \sum_{n=1}^{\infty} \int_{0}^\pi \cos(nx)\cos(mx) dx
\
\end{equation}
Now, we can finally exploit the orthogonality of the cosine function. When $n=m$, the integral is $\pi/2$, and when $n \neq m$, the integral is $0$. Therefore, the only non-zero term in the summation is $\pi/2$ when $n$ and $m$ happen to align.
Finally, this leads us to the formula for the coefficients:
(Note that since n was just a summation index, once it's out of the summation, we can give the coefficients any name so we can easily change it to m to fit the sines)
\begin{equation}
\
c_m = \frac{2}{\pi} \int_{0}^\pi g(x) \cos(mx) dx
\
\end{equation}
However, this is a definite integral so as Hans Lundmark pointed out, this only works for some functions $g(x)$, specifically those that are "nice enough" for this integral to converge.
In addition, $g(x) = \phi(x,0)$ so it must satisfy the boundary conditions, which forces $g(x)$ to be able to be approximated with cosines just like $\phi(x,t)$.