Place this code in your DOCUMENT_ROOT/.htaccess
file:
RewriteEngine On
RewriteCond %{THE_REQUEST} \s/+p\.php\?id=([0-9]+) [NC]
RewriteRule ^ /p/%1? [R=301,L]
RewriteRule ^p/([0-9]+)/?$ /p.php?id=$1 [L,QSA,NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ /$1.php [L]