Diagnosing SELinux-related Network Service Issues

The final Troubleshooting and System Maintenance item in the
RHCE part of the Exam Prep guide is the ability to diagnose
and correct networking services problems
where SELinux
contexts are interfering with proper operation
.



In most cases, this is simpler than it looks. SELinux log
messages are stored in /var/log/messages with an avc label.
But even better, the Setroubleshoot browser can identify SELinux issues,
describe causes, and even suggest solutions. Watch it for suggested commands
such as chcon to change SELinux contexts and sesetbool to set SELinux booleans. All you need to do is open the
browser in a GUI with the sealert -b command, and browse the
most recent errors.

Network Service Issues

The Red Hat Exam Prep guide says that you may have to diagnose and correct problems with network services during the Troubleshooting and System Maintenance portion of the RHCE exam. These are the same network services that you may need to configure during the Installation and Configuration portion of the same exam. Example scenarios and solutions are shown as follows. Needless to say, the solutions are far from complete: for example, firewalls and network configuration issues can prevent communication to any network service

Filesystem Corruption and Checking

Although there are potentially many things that will prevent a system from booting, these problems can be generally categorized as either hardware problems or software and configuration problems. The most common hardware-related problem you will probably encounter is a bad hard drive; like all mechanical devices with moving parts, these have a finite lifetime and will eventually fail. Fortunately, the Red Hat exams do not require you to address hardware failures.

Software and configuration problems, however, can be a little more difficult. At first glance, they can look just like regular hardware problems.

In addition to knowing how to mount disk partitions, edit files, and manipulate files, you will need to know how to use several other commands to fix problems from rescue mode or single-user mode. The most useful of these are the df, fdisk, and the fsck commands. To diagnose a problem, you need to know how these commands work at least at a rudimentary level.

df
The Linux df command was covered briefly in Chapter 4. When you use df, you can find mounted directories, the capacity of each partition, and the percentage of each partition that's filled with files. The result shown back in Figure 16-8 illustrates the result in kilobytes. There are a couple of simple variations; the following commands provide output in megabytes and inodes:

# df -m
# df -i

fdisk and parted
The Linux fdisk and parted utilities were covered briefly in Chapter 4. When you use fdisk or parted, you can find the partitions you have available for mounting. For example, the fdisk -l /dev/hda (or parted /dev/hda print) command lists available partitions on the first IDE hard disk:

# fdisk -l /dev/hda

Disk /dev/hda: 15.0GB, 15020457984 bytes
240 heads, 63 sectors/track, 1940 cylinders
Units = cylinders of 15120 * 512 = 7741440 bytes
   Device    Boot   Start     End     Blocks    Id  System
/dev/hda1    *      1         949    7174408+   b   Win95 FAT32
/dev/hda2           950       963    105840     83  Linux
/dev/hda3           964       1871   6864480    83  Linux
/dev/hda4           1872      1940   521640     f   Win95 Ext'd (LBA)
/dev/hda5           1872      1940   521608+    82  Linux swap

Looking at the output from fdisk, it's easy to identify the partitions configured with a Linux format, /dev/hda2, /dev/hda3, and /dev/hda5. Given the size of each partition, it is reasonable to conclude that /dev/hda2 is associated with /boot, and /dev/hda3 is associated with root (/). Here's a fairly complex output from parted:

# parted /dev/sda print

Model: ATA HDS728080PLA380 (scsi)
Disk /dev/sda: 82.3GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number Start   End     Size    Type     File system  Flags
 1     32.3kB  197MB   197MB   primary  ext3         boot
 2     197MB   15.2GB  15.0GB  primary  ext3
 3     15.2GB  16.2GB  1003MB  primary  linux-swap
 4     16.2GB  82.3GB  66.1GB  extended
 5     16.2GB  16.3GB  107MB   logical  ext3
 6     16.3GB  26.8GB  10.5GB  logical  ext3
 7     26.8GB  41.8GB  15.0GB  logical  fat32        lba
 8     41.8GB  51.8GB  10.0GB  logical  ext3
 9     51.8GB  82.3GB  30.5GB  logical  ext3

Information: Don't forget to update /etc/fstab, if necessary.


In this example, it's easy to identify the Linux swap partition. Since /boot partitions are small and normally configured toward the front of a drive (with a boot flag), it's reasonable to associate it with /dev/sda1.

For simple partitioning schemes, this is easy. It gets far more complicated when you have lots of partitions. You should always have some documentation available that clearly identifies your partition layout within your filesystem:

# fdisk -l /dev/hda
Disk /dev/hda: 26.8 GB, 26843545600
255 heads, 63 sectors/track, 3263 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

   Device   Boot   Start      End     Blocks     Id  System
/dev/hda1   *      1          13      104391     83  Linux
/dev/hda2          14         268     2048287+   b   Win95 FAT32
/dev/hda3          269        396     1028160    83  Linux
/dev/hda4          397        3263    23029177+  f   Win95 Ext'd (LBA)
/dev/hda5          397        1097    5630751    83  Linux
/dev/hda6          1098       1734    5116671    83  Linux
/dev/hda7          1735       1989    2048256    83  Linux
/dev/hda8          1990       2244    2048256    83  Linux
/dev/hda9          2245       2372    1028218+   83  Linux
/dev/hda10         2373       2499    1020096    82  Linux swap
/dev/hda11         2500       2626    1020096    83  Linux
/dev/hda12         2627       2753    1020096    83  Linux
/dev/hda13         2754       2880    1020096    83  Linux
/dev/hda14         2881       3007    1020096    83  Linux
/dev/hda15         3008       3134    1020096    83  Linux
/dev/hda16         3135       3236    1020096    83  Linux

In this example, it's easy to identify the Linux swap partition. Since /boot partitions are small and normally configured toward the front of a drive, it's reasonable to associate it with /dev/hda1.

However, that is just a guess; some trial and error may be required. For example, after mounting /dev/hda2 on an empty directory, you would want to check the contents of that directory for the typical contents of /boot.

e2label
Based on the previous output from fdisk -l, you could probably use a little help to identify the filesystems associated with the other partitions. The e2label command can help. When you set up a new filesystem, the associated partition is normally marked with a label. For example, the following command tells you that the /usr filesystem is normally mounted on /dev/hda5.

# e2label
Usage: e2label device [newlabel]

# e2label /dev/hda5
/usr

dumpe2fs
You can get a lot more information on each partition with the dumpe2fs command, as shown in Figure 16-9.

 
Figure 16-9: The dumpe2fs command provides a lot of information.
The dumpe2fs command not only does the job of e2label but also tells you about the format, whether it has a journal, and the block size. Proceed further through the output, and you'll find the locations for backup superblocks, which can help you use the fsck or e2fsck command to select the appropriate superblock for your Linux partition.

 On the Job  fsck is a "front end" for e2fsck, which is used to check partitions formatted to the ext2 and ext3 filesystems.
 

Filesystem Check-fsck
You should also know how to use the fsck command. This command is a front end for most of the filesystem formats available in Linux, such as ext2, ext3, reiserfs, vfat, and more. This command is used to check the filesystem on a partition for consistency. In order to use the fsck command effectively, you need to understand something about how filesystems are laid out on disk partitions.

When you format a disk partition under Linux using the mkfs command, it sets aside a certain portion of the disk to use for storing inodes, which are data structures that contain the actual disk block addresses that point to file data on a disk. The mkfs command also stores information about the size of the filesystem, the filesystem label, and the number of inodes in a special location at the start of the partition called the superblock. If the superblock is corrupted or destroyed, the remaining information on the disk is unreadable. Because the superblock is so vital to the integrity of the data on a partition, the mkfs command makes duplicate copies of the superblock at fixed intervals on the partition, which you can find with the dumpe2fs command described earlier.

The fsck command checks for and corrects problems with filesystem consistency by looking for things such as disk blocks that are marked as free but are actually in use (and vice versa), inodes that don't have a corresponding directory entry, inodes with incorrect link counts, and a number of other problems. The fsck command will also fix a corrupted superblock. If fsck fails due to a corrupt superblock, you can use the fsck command with the -b option to specify an alternative superblock. For example, the following command performs a consistency check on the filesystem on disk partition /dev/hda5, using the superblock located at disk block 8193:

# fsck -b 8193 /dev/hda5


Troubleshooting the Boot Loader

The boot loader associated with Red Hat Enterprise Linux 5 is GRUB. For an extensive discussion, see Chapter 3. It can help you to know how to:

Associate the root directive with the partition with the /boot directory.

Boot into the desired, non-default runlevel.

Access the GRUB command line.

Test different GRUB commands.

Use command completion to find and use the exact names of your kernel and initial RAM disk.

For this exercise, you'll need a partner. Have your partner make changes to your system. As your partner works to create a network problem for you to solve on your computer, look away until the computer is rebooting.

It's most helpful if you have a VMware snapshot of your RHEL system. Problems like those created in this exercise have caused administrators to mess up their systems in other ways. You'll also need the first RHEL installation CD.

Back up the configuration file associated with the boot loader, /boot/grub/grub.conf. Make sure to back up this file to a non-standard location, in case your partner also backs up any files before changing them.

Open the /boot/grub/grub.conf configuration file in a text editor. Focus on the kernel command line, which might look like one of the following:

kernel /vmlinuz-2.6.18-8.el5 ro root=/dev/VolGroup00/LogVol00

or

kernel /vmlinuz-2.6.18-8.el5 ro root=LABEL=/

Introduce a typographical error in the root directive in the kernel command line.

Reboot the system, and let your partner back at the computer. Tell him or her to address the error message shown. Give your partner the first RHEL 5 installation CD.

Make sure to tell your partner to back up any files that he or she might change to the appropriate home directory.

Whatever happens, restore the original /boot/grub/grub.conf configuration file when your partner is finished with this exercise. (Alternatively, you can restore the configuration from a VMware snapshot.)

Module Errors

Most kernels are compiled with loadable modules. Current Linux distributions, including RHEL, configure modules in the initial RAM disk, which is compiled into a initrd-* file in the /boot directory. As you can see in the GRUB configuration file, the initial RAM disk is normally associated with the last line in a GRUB configuration stanza. As described in topic 8, you can create a new initial RAM disk configuration file with the mkinitrd command. But errors are also possible, as you'll see in the following exercise.

For this exercise, you'll need a partner. Have your partner make changes to your system. As your partner works to create a network problem for you to solve on your computer, look away until the computer is rebooting.

It's most helpful if you have a VMware snapshot of your RHEL system. Problems like those created in this exercise have caused administrators to mess up their systems in other ways. You'll also need the first RHEL installation CD.

  1. Back up the configuration file associated with the boot loader, /boot/grub/grub.conf. Make sure to back up this file to a non-standard location, in case your partner also backs up any files before changing them.

  2. Open the /boot/grub/grub.conf configuration file in a text editor. Focus on the initrd command line, which might look like the following:

    initrd /initrd-2.6.18-8.el5.img
  3. Misspell both initrd words in this line.

  4. Reboot the system, and let your partner back at the computer. Tell him or her to address the error message shown. Give your partner the first RHEL 5 installation CD.

  5. Make sure to tell your partner to back up any files that he or she might change to the appropriate home directory.

  6. Whatever happens, restore the original /boot/grub/grub.conf configuration file when your partner is finished with this exercise. (Alternatively, you can restore the configuration from a VMware snapshot.)

Adding New Partitions, Filesystems, and Swap

Reading the Red Hat Exam Prep guide carefully, this skill states that RHCTs should be able to add new partitions, filesystems, and swap to existing systems (I've added the boldface to provide emphasis on this particular Exam Prep requirement). This implies that space is available on the hard drive(s) that you are using during your exam.

You need to know how to add new partitions, which suggests that you need to know how to use the fdisc and parted utilities described in chapter 4. When you create a new partition, make sure the partition type is associated with what you're creating; there are different partition types for standard Linux and swap partitions.

This is one exercise that does not require a partner. However, it assumes that you've installed RHEL with extra available space on any existing hard drives. If you don't have any additional space, you can substitute a spare USB key.

This exercise assumes you'll be creating a partition on a second SATA or SCSI hard drive. If you're using a different drive and partition, substitute device file names accordingly.

  1. If you've configured a VMware machine to practice for the Red Hat exam, take a snapshot of your current configuration (unless you're willing to keep the changes made during this exercise).

  2. Run the fdisk -l command to display configured partitions. The cylinders will tell you if space is available. For example, the following output suggests that 5000 cylinders are free:

    Disk /dev/sdb: 160.0 GB, 160041885696 bytes
    255 heads, 63 sectors/track, 19457 cylinders
    Units = cylinders of 16065 * 512 = 8225280 bytes

    Device Boot Start End Blocks Id System
    /dev/sdb1 * 1 9205 73939131 83 Linux
    /dev/sdb2 9206 14457 42349190 83 Linux
  3. Add a new partition of 500MB. It doesn't have to be exact. Make sure that the partition type is associated with Linux. I don't specify exact steps, as you can use either fdisc or parted to create the new partition.

  4. Write the changes to disk, and use the partprobe command or reboot the system.

  5. Format the new partition. For example, if the new partition device is /dev/sdb3, you can do so with the mkfs.ext3 /dev/sdb3 command.

  6. Assign the partition to user michael's home directory in /etc/fstab. (Create user michael if needed.) For example, if the partition device is /dev/sdb3, you can do so with the following directive in that file:

    /dev/sdb3    /home/michael     ext3     defaults     1 2
  7. Mount /dev/sdb3 on the /home/michael directory. Reboot your system to make sure your system recognizes the changes and mounts the new partition.

  8. Run the fdisk -l, mount, and df commands to verify the new partition.

  9. If you took a VMware snapshot, press the Revert button in the VMware window to revert to the snapshot.

Configuring a Desktop Environment

Configuring a desktop environment is a slightly different process than configuring the X Window. As discussed in chapter 14, the default login manager is configured in /etc/X11/prefdm. The default desktop environment can be changed with the switchdesk command. Standard applications can be started with the desktop environment using settings in /etc/X11/xinit/xinitrc and files in the /etc/X11/xinit/xinitrc.d directory.

You can also customize a desktop environment based on hidden files in each user's home directory. These files are read first by the key scripts that start the X Window.

For this exercise, you'll need a partner. Have your partner make changes to your system. As your partner works to create a network problem for you to solve on your computer, look away until the computer is rebooting.

  1. Back up the configuration file associated with the display manager, /etc/X11/prefdm. Make sure to back up this file to a non-standard location, in case your partner also backs up any files before changing them.

  2. Open the /etc/X11/prefdm configuration file in a text editor. Near the beginning of the file, you'll see the following directive:

    # Run preferred X display manager
    preferred=
  3. Change the directive to:

    preferred=kdm
  4. Make sure the default runlevel in /etc/inittab is set to 5.

  5. Reboot the system, and let your partner back at the computer. Tell him or her to configure the system to boot into the GNOME Display Manager.

  6. Make sure to tell your partner to back up any files that he or she might change to the appropriate home directory.

  7. Whatever happens, restore the original /etc/X11/prefdm configuration file when your partner is finished with this exercise.

  8. Image from book

Configuring the X Window System

There are a number of issues associated with the smooth operation of the X Window System. If there are problems with the X configuration file, you may be able to fix it directly using a text editor, create a new file using the Red Hat Display tool (system-config-display), or use a command line tool such as Xorg -configure.

And as discussed in chapter 14, the X Window may not work under certain conditions. Naturally, Linux doesn't boot into an X login window unless the default runlevel in /etc/inittab is set to 5. The X Window can't run without the X Font Server. And it can't start if the partitions associated with certain directories are full or have inappropriate permissions.

For this exercise, you'll need a partner. Have your partner make changes to your system. As your partner works to create a network problem for you to solve on your computer, look away until the computer is rebooting.

  1. Back up the configuration file associated with the X Window System, /etc/X11/xorg.conf. Make sure to back up this file to a non-standard location, in case your partner also backs up any files before changing them.

  2. Open the /etc/X11/xorg.conf configuration file in a text editor. Near the end of the file, you'll see the following directive:

    Section "Screen"
  3. Change the directive to:

    Section "Scree"
  4. Configure the system to start in runlevel 3, in /etc/inittab.

  5. Reboot the system, and let your partner back at the computer. Tell him or her to try starting the GUI.

  6. Make sure to tell your partner to back up any files that he or she might change to the appropriate home directory.

  7. If your partner gives up, restore the original /etc/X11/xorg.conf configuration file.

Image from book

Diagnosing and Correcting Hostname Resolution Problems

Hostname resolution is based on the relationship between hostnames such as enterprise5a.example.org and IP addresses such as 192.168.44.66. First, the default hostname is defined in /etc/sysconfig/network, based on the HOSTNAME directive. Hostnames are associated with IP addresses in /etc/hosts. If you use a DNS service, you need to make sure that the DNS server's IP address is identified in /etc/resolv.conf. If you use DHCP to get your IP address, it overwrites the DNS server addresses /etc/ resolv.conf, unless PEERDNS=no before the BOOTPROTO=dhcp directive in /etc/ sysconfig/network-scripts/ifcfg-eth0. Then a command like dhclient eth0 will acquire the DNS server address(es) from the DHCP server and place them in /etc/resolv.conf.

When there's appropriate routing information, as shown by the route command, along with DNS information in /etc/resolv.conf, you can apply the ping command to confirm connectivity to the external host of your choice.

For this exercise, you'll need a partner. Have your partner make changes to your system. As your partner works to create a network problem for you to solve on your computer, look away until the computer is rebooting.

  1. Back up the configuration file associated with the DNS server, /etc/resolv .conf. Back up the /etc/hosts configuration file. Back up the /etc/host.conf configuration file. Make sure to back up these files to a non-standard location, in case your partner also backs up any files before changing them.

  2. Open the /etc/host.conf configuration file in a text editor. If it isn't already as shown, change the directive in this file to:

    order hosts,bind
  3. Open the /etc/hosts configuration file. Set the name of another computer on your network (which supports SSH access) to an incorrect IP address.

  4. Reboot your system, and let your partner back at the computer. Tell him or her to try connecting to another system on your network (the one you've set to the wrong IP address).

  5. Make sure to tell your partner to back up any files that he or she might change to the appropriate home directory.

  6. If your partner gives up, restore the original /etc/hosts configuration file (and anything else your partner might have changed).

    Image from book

Diagnosing and Correcting Network Problems

To diagnose misconfigured networking, you need to use the commands and analyze the files described in topic 7. To check your current network settings, you'll want to run commands such as:

  • ifconfig to find the settings of your network card(s)

  • ping to confirm connectivity to other systems

  • route to confirm the current routing table

You'll also want to check key files, such as:

  • /etc/sysconfig/network to confirm that NETWORKING=yes

  • /etc/sysconfig/network-scripts/ifcfg-eth0 to confirm defaults for your network card (assuming the default eth0 device for the network card)

  • /etc/resolv.conf to confirm connections to DNS servers (which is associated with PEERDNS=yes in the aforementioned ifcfg-eth0 configuration file)

Refer to topic 7 more information on these commands and files. There are a lot of details; if you forget something, it may be easier to use a Red Hat utility such as the GUI-based Network Configuration tool.

For this exercise, you'll need a partner. Have that partner make changes to your system. Let that partner work privately on your system, until told that the computer is rebooting. Don't look at this lab, until you've solved the problem as created by your partner.

  1. Run the ifconfig command and review your current network settings.

  2. Back up the configuration file associated with the network card, usually ifcfg-eth0 in the /etc/sysconfig/network-scripts directory. Make sure to back up this file to a non-standard location, in case your partner also backs up any files before changing them.

  3. Open up the ifcfg-eth0 file in a text editor.

  4. Set BOOTPROTO=none if it isn't already done.

  5. Set or add an IPADDR directive. Make it just a little different from the IP Address setting you saw in the output from ifconfig. Make sure the new address is on a different network; for example, if the original IP Address and network mask was 192.168.0.50 and 255.255.255.0, set IPADDR=192.168.1.50 and NETMASK=255.255.255.0.

  6. Reboot your system, and let your partner back at the computer. Tell him or her to try connecting to another system on your network.

  7. Tell your partner to back up any files that he or she might change to the home directory.

  8. If your partner gives up, restore the original ifcfg-eth0 configuration file to the /etc/sysconfig/network-scripts directory.

Image from book

The linux rescue Environment

In brief, you can boot even an unbootable system using the linux rescue environment. Using the first RHEL installation CD, type linux rescue at the boot: prompt. The first couple of steps are the same as those for installing RHEL 5. If the linux rescue environment detects your system, it may mount the standard directories in /mnt/ sysimage subdirectories in read-write or in read-only mode. If your filesystems are not mountable, you can open a command prompt and continue with your troubleshooting.

When you type linux rescue at the installation boot prompt and go through the steps, the installation discs install a compact version of a root filesystem. To boot into linux rescue mode, first boot your system using the first installation CD in a bootable CD-ROM drive,

Now take the following steps:

  1. Boot your system from the first RHEL 5 installation CD.

  2. Type linux rescue at the boot: prompt . Your system boots a basic Linux system from the first installation CD.

  3. Select an appropriate language when prompted.

  4. Select an appropriate keyboard type when prompted.

  5. You'll see the following message, briefly:

    Running anaconda, the Red Hat Enterprise Linux rescue mode - please wait...
  6. You'll be asked whether you want to set up the network interfaces on the local system. Select Yes if you need to connect to a network installation source to install other packages; otherwise, select No and skip to step 8.

  7. You'll see a network configuration window for the local network card, similar to what's . If directed by your instructor or exam proctor to set up a static IP address, follow the instructions carefully; otherwise, try to configure this interface using a local network DHCP server. If you set up a static IP address, you'll see another screen where you're prompted to enter a gateway, a primary DNS, and a secondary DNS IP address.

  8. Select one of the three options for the rescue environment, . Generally, you should try the Continue option first, followed by Read-Only. Continue mounts your RHEL filesystems in read-write mode. Read-Only mounts RHEL file systems in read-only mode. Skip does not mount any of your RHEL filesystems. I address each of these three options in detail in the following sections.

  9. When successful, you'll see a message to the effect that your system has been mounted under /mnt/sysimage. When you select OK (the only option), you'll see the following prompt, where you have root privileges.

Standard linux rescue Environment

When you select Continue from the screen

, you're taken through the standard linux rescue environment. The rescue files search for your root directory (/) filesystem. If found, your standard root directory (/) is mounted on /mnt/sysimage. All of your other regular filesystems are subdirectories of root; for example, your /boot directory will be found on /mnt/sysimage/boot.

Not all of your filesystems may mount properly. You may see error messages such as:

An error occurred trying to mount some or all of your filesystem

This suggests that at least one of the filesystems listed in /etc/fstab isn't mounting properly for some reason. If the linux rescue environment has no problems, you'll see a message noting that your system has been mounted,

Select OK. You should see the following prompt messages:

Your system is mounted under the /mnt/sysimage directory.
When finished please exit from the shell and your system will reboot.
You'll use the chroot /mnt/sysimage command shortly. Now you
can work on repairing any files or filesystems that might be damaged. First,
check for unmounted filesystems. Run a df command.
Compare the result to the /mnt/sysimage/etc/fstab configuration file. If some filesystem is not mounted, it may be configured incorrectly in the fstab file. Alternatively, the label associated with a partition may not match the filesystem shown in your fstab file. For example, to find the label associated with /dev/sda1, run the following command:

# e2label /dev/sda1

This should return the name of a filesystem to be mounted on that partition such as /boot.

Sometimes an unmounted filesystem just needs a little cleaning; remember, a command such as the following cleans the /dev/sdb1 partition:

# fsck /dev/sdb1

The fsck command works only on an unmounted filesystem. For example, if you get a message such as:

WARNING!!! Running e2fsck on a mounted filesystem may cause
SEVERE filesystem damage.

unmount the subject filesystem with a command such as umount /mnt/sysimage/boot. If that doesn't work, restart the rescue process. When you get to the screen select Skip and read the "No Mount linux rescue Environment" section later in this topic

Alternatively, you may see a message like:

fsck.ext2: Device or resource busy while trying to open /dev/hda2
filesystem mounted or opened exclusively by another program?

This is presented when the partition, in this case /dev/hda2, is part of a Logical Volume Manager (LVM) array as described in topic 8. In that case, you'll need to review your /mnt/sysimage/etc/fstab file for the appropriate logical volume (and unmount it), before trying to apply the fsck

Read-Only linux rescue Environment

When you select the Read-Only option , you'll get the same basic prompt. There is little difference between regular and read-only rescue mode. The rescue system attempts to do everything that it would under regular mode, except all partitions associated with your standard system are mounted read-only. (Some of the rescue system filesystems are still mounted as read-write.)

This is appropriate if you have a large number of mounted filesystems; it can help you cull through what is and isn't working with less risk of overwriting key configuration files.

No Mount linux rescue Environment

When you select the Skip option shown in Figure 16-6, the rescue environment doesn't even search for a Linux installation. A minimal root image is loaded into a RAM disk created by the kernel, and you're taken to a root shell prompt (#), as shown:

When finished, please exit from the shell and your system will reboot.

At this point, you have access to a basic set of commands. You can mount filesystems, create directories, move files, and use editors such as vi. As nothing from your physical drives is mounted, you can apply the fdisc and fsck commands to various hard disks and partitions. A few other basic commands are also available.

The great difficulty in operating from the rescue environment is that you are working with a minimal version of the Linux operating system. Many of the commands you are accustomed to having at your disposal are not available at this level. If your root partition has not been completely destroyed, you may be able to mount this partition to your temporary root directory in memory and access commands from there.

But you may need a little help identifying the partitions on your system. As I'll show you shortly, the fdisk -l /dev/hda command lists the configured partitions on the first IDE hard drive. You can create a new directory such as /mnt/sysimage, mount a partition such as /dev/hda2 on that directory, and check the result with the following commands:

# mkdir /mnt/sysimage
# mount /dev/hda2 /mnt/sysimage
# ls /mnt/sysimage

If you can verify that you've mounted the standard root directory (/) filesystem on the /mnt/sysimage directory, you can run the chroot /mnt/sysimage command. You can then have full access to the commands and configuration files available under that mounted partition.




Troubleshooting

Overview


While you've read about many troubleshooting scenarios throughout this book, it's the troubleshooting part of the Red Hat exams that I believe causes the most "fear and loathing" among Red Hat certification candidates.

Troubleshooting is a mindset based on experience and a systematic way of thinking. Troubleshooting strategies on the Red Hat exams are based on the simplest problems that you can check quickly, moving to more complex problems.

Red Hat has done excellent work addressing some problems that formerly led to unbootable systems. For example, flaws in the /etc/fstab file used to lead to an unbootable system. Now most users would hardly know the difference if this file is missing.

The most important troubleshooting tool is the linux rescue environment, which can bypass boot problems, from a missing GRUB boot loader to a missing kernel. In most cases, the first installation CD, booted into the linux rescue environment, can detect and mount even damaged installations of RHEL.

This topic focuses on the Troubleshooting and System Maintenance section of the RHCT and RHCE exams, as defined in the Inside the Exam sidebar. It further focuses on troubleshooting skills, as they evoke more concern than regular system maintenance.

This chapter includes a number of exercises for which you'll need the help of a partner. When you start an exercise, let your partner have your computer and wait until your system begins to reboot. This chapter includes enough exercises to allow you and your partner to take turns working with the system.


Troubleshooting and System Maintenance

  1. Define the question.

    Understand what happened. Take the error messages you see. If possible, analyze log files for other messages. If you've read this book and run the labs, you may recognize the problem and cause immediately.

  2. Gather information and resources.

    Analyze your system. This may require that you check the relevant configuration files to make sure that appropriate services are running and that security or other characteristics of your system are working as they should. If you have experience, you'll often recognize the problem and cause when you see something wrong in these areas.

  3. Form a hypothesis.

    If you're still not sure what's wrong, make your best guess. Remember that time is severely limited during the Red Hat exams, so if you can afford it, consider skipping a problem. (To qualify for either the RHCT or RHCE, you're required to solve all RHCT-level Troubleshooting and System Maintenance issues.)

  4. Perform experiments and collect data.

    Before performing any experiments, back up anything you might change. For example, if you think the problem is with your Samba configuration file, back up your /etc/samba/smb.conf file, in case your hypothesis makes things worse.

  5. Analyze data.

    This is essentially identical to step 1. If what you do doesn't solve the problem, you'll need to analyze what went wrong, using error messages and log files as appropriate.

  6. Interpret data and draw conclusions that serve as a starting point for new hypotheses.

    In many cases, you'll want to restore what you did from the backup in step 4, repeat steps 2 through 4, and try again.

  7. Publish the results.

    Once you've solved the problem, you'll want to make sure the problem remains solved after rebooting your system. For example, if you've addressed a Samba problem, you'll want to "publish" by making sure the Samba daemon starts the next time your Linux system boots.

Two places where you are likely to make errors that result in an unbootable system are in the boot loader and init configuration files, /boot/grub/grub.conf and /etc/ inittab. For example, identifying the wrong partition as the root partition (/) can lead to a kernel panic. Other configuration errors in /boot/grub/grub.conf can also cause a kernel panic when you boot Linux. Whenever you make changes to these files, the only way to fully test them out is to reboot Linux.

The following scenarios and solutions list some possible problems and solutions that you can have during the boot process, and possible associated solutions. It is far from comprehensive. The solutions that I've listed work on my computer, as I've configured it. There may be (and often is) more than one possible cause. These solutions may not work for you on your computer or on the Red Hat exams. To know what else to try, use your experience.

To get the equivalent of more experience, try additional scenarios (remember: never do these things on a production computer). Once you're familiar with the linux rescue environment, test these scenarios. These scenarios worked as shown when I tested them on RHEL 5. However, they lead to different errors on RHEL 4 and RHEL 3.

For the first scenario shown, change the name of the grub.conf file so it can't be loaded. Reboot and see what it does on your system. Use the linux rescue environment to boot into RHEL and use the noted solution to fix your system.

For the second scenario shown, overwrite the MBR; on a SATA/SCSI drive, you can do so with the following command (substitute hda for sda if your system uses an IDE/PATA drive):

# dd if=/dev/zero of=/dev/sda bs=446 count=1

The third scenario is misleading; it's what happened when I overwrote my /bin/ mount with /sbin/mount.nfs and rebooted.

The fourth scenario is what happened when I overwrote my /bin/init command.

The fifth scenario is based on a missing /etc/inittab; I suspect it's much more likely that you'll see some major error (such as a key command, commented out) in that file.

The sixth scenario results in the messages , which happened when I set the default runlevel to 3 and commented out the commands with the mingetty directives in /etc/inittab.



The seventh scenario is based on a typo in the root directive in /boot/grub/grub. conf.

Sometimes, you may run into a problem with the default runlevel. But you're not stuck. There are two ways to boot into different runlevels. You can boot directly from the GRUB configuration menu, or you can boot into the linux rescue environment from the first RHEL installation CD.

SCENARIO & SOLUTION

When you boot, you see a grub> prompt.

You may have a problem that prevents the boot loader from reading the GRUB configuration file, grub.conf. The file may be missing or corrupt. For hints on creating a new grub.conf, see menu.1st in the /usr/share/doc/grub-versionnum directory.

When you boot your computer, you see a message such as "Missing operating system" or "Operating System Not Found."

Your master boot record (MBR) has been erased, and you'll need to reload GRUB on the MBR using grub-install. (It's possible that everything has been erased, which I believe is beyond the scope of this part of the exam.)

During the boot process, you see the "Could not start the X server (graphical environment) due to some internal error" message.

You could have problems with a full or unmounted /tmp or /home directory. If these directories are not mounted, the mount command may be corrupt. In that case, you'll need to reload it from the mount RPM.

You see an "exec of init (/sbin/init) failed!!!" error.

Your init command may be corrupt. Try reloading it from the SysVinit RPM.

You see the "INIT: No inittab file found" message.

This is straightforward-there is something wrong with your /etc/inittab file. RHEL 5 prompts you to "Enter runlevel"; as of this writing, if /etc/inittab is missing, enter s to see a bash prompt.

You see a message

You may not have anything starting a text or GUI console in the active runlevel; trace it starting with /etc/inittab.

You see a message . Take careful note of the last file cited in the message.

RHEL has encountered some problems when reading the grub.conf configuration file. Start the linux rescue environment and check this file as well as the referenced files in the /boot directory.

Booting Into Different Runlevels

In brief, you can boot into the runlevel of your choice from the GRUB configuration menu. This is one of the RHCT Troubleshooting and System Maintenance skills and also an essential skill for all Linux administrators.

Table 16-1: Linux Runlevels

Runlevel

Description

0

Halts the system

1

Activates SELinux; runs /etc/rc.sysinit, which checks and mounts filesystems; executes all scripts in the /etc/rc1.d directory

s or single

Single-user mode; activates SELinux; runs /etc/rc.sysinit, which checks and mounts filesystems

emergency

Emergency boot mode; activates SELinux; mounts only the root (/) filesystem

init=/bin/sh

Emergency boot mode; mounts only the root (/) filesystem

2

Multiuser mode with some networking; does not include some NFS functions, the automounter, or CUPS

3

Multiuser mode with networking; boots into a text login console

4

Generally unused; however, the defaults support near-identical settings to runlevel 3

5

Multiuser mode with the X Window; boots into an X-based login screen

6

Reboots the system

The Red Hat Exam Prep guide states that "RHCTs should be able to boot systems into different run levels for troubleshooting and system maintenance." This is straightforward; at the boot loader prompt, you can start Linux at a different runlevel. This may be useful for two purposes. If your default runlevel in /etc/inittab is 5, your system normally boots into the GUI. If you're having problems booting into the GUI, you can start RHEL into the standard text mode, runlevel 3.

One other option to help rescue a damaged Linux system is is appropriate if your system can find at least the root filesystem (/). Your system may not have problems finding its root partition and starting the boot process, but it may encounter problems such as damaged configuration files or an inability to boot into one of the higher runlevels. When you boot into single-user mode, options are similar to those of the standard linux rescue environment described later in this topic.

To boot into a different runlevel, first assume that you're using the default RHEL boot loader, GRUB. In that case, press (lowercase) p to enter the GRUB password if required. Type (lowercase) a to modify the kernel arguments. When you see a line similar to

grub append> ro root=LABEL=/ rhgb quiet

add one of the following commands (shown in boldface) to the end of that line:

grub append> ro root=LABEL=/ single
grub append> ro root=LABEL=/ init=/bin/sh
grub append> ro root=LABEL=/ emergency
grub append> ro root=LABEL=/ 1

You can use the same technique to boot into another runlevel. For example, to boot from the GRUB boot loader into runlevel 3, navigate to where you can modify the kernel arguments, and add the following command to the end of the following line:

grub append> ro root=LABEL=/ 3



On the Job

The terms boot loader and bootloader are used interchangeably. In this book, I've normally used the term boot loader, as that seems to be the direction of the Red Hat documentation. However, the term bootloader is still common even in Red Hat documentation.

grub append> ro root=LABEL=/ 3

When you boot into runlevel 1, no password is required to access the system. As you'll see later in this topic, running your system in this runlevel is somewhat similar to running a system booted in rescue mode. Many of the commands and utilities you normally use are unavailable. You may have to mount additional drives or partitions and specify the full pathname when running some commands.

When you have corrected the problem, you can reboot the system. Alternatively, you can type the exit command to boot into the default runlevel as defined in /etc/ inittab, probably runlevel 3 or 5.


On the Job

In runlevel 1, any user can change the root password. You do not want people rebooting your computer to go into this runlevel to change your root password. Therefore, it's important to keep your server in a secure location. You can also password-protect GRUB or even the BIOS menu to keep anyone with physical access to your computer from booting it in single-user mode.

PHP Operators

Welcome! In this section we going to cover differect kinds of operators we use in programming. These operators are common to ever language. So, in PHP they are no diffrent. We will go through each type of operators with examples on how they are done PHP.

Arithmetic Operators
In programming, we often perform arthmenteic operations to calculate values. Below is the list of these oprators with examples.
Operator Name Example Output
+ Addition $num = 5+5;
echo $num
?>
10
- Subtraction $num = 5-5;
echo $num
?>
0
* Multiplication $num = 5*5;
echo $num
?>
25
/ Division $num = 5/5;
echo $num
?>
1

Comparison Operators

Comparison Operators prove very useful when checking the status of two variables or values. For example, if you wna tto check if one is equal to the other, we would use = operator. Comparasion operators are used in logic conditional statements (check PHP If...else section) to evalute if the condition is true or false.
Operator Name Example Output
> is greater than 6 > 5

5 > 6
First example returns true.

Second example returns false.
< is less than 6 < 5

5 < 6
First example returns false.

Second example returns true.
>= is greater than equal to 5 >= 4
returns true
<= is less than equal to 5 <= 4
returns false
== is equal to 5 = 4
returns false
!= is not equal to 5 != 4
returns true

Logic Operators

Logic operators can be used to combine two or more comparision statements combined into one statement to determine its status. For example, we can check to see if value A greater than value B and value B greater then value C. Let's check out some examples.
Operator Name Example Output
&& and (6 > 5 && 1 < 7) returns true
|| or (2 > 5 || 1 < 7) returns true

If you're not familiar with the logic operations and their usage, please refer to the table below for reference. The table shows what you would get back when performating logic operatioon on two values p and q where T = True and F = False.
p q p and q p or q
T T T T
T F F T
F T F T
F F F F

PHP Operators

Welcome! In this section we going to cover differect kinds of operators we use in programming. These operators are common to ever language. So, in PHP they are no diffrent. We will go through each type of operators with examples on how they are done PHP.

Arithmetic Operators
In programming, we often perform arthmenteic operations to calculate values. Below is the list of these oprators with examples.
Operator Name Example Output
+ Addition $num = 5+5;
echo $num
?>
10
- Subtraction $num = 5-5;
echo $num
?>
0
* Multiplication $num = 5*5;
echo $num
?>
25
/ Division $num = 5/5;
echo $num
?>
1

Comparison Operators

Comparison Operators prove very useful when checking the status of two variables or values. For example, if you wna tto check if one is equal to the other, we would use = operator. Comparasion operators are used in logic conditional statements (check PHP If...else section) to evalute if the condition is true or false.
Operator Name Example Output
> is greater than 6 > 5

5 > 6
First example returns true.

Second example returns false.
< is less than 6 < 5

5 < 6
First example returns false.

Second example returns true.
>= is greater than equal to 5 >= 4
returns true
<= is less than equal to 5 <= 4
returns false
== is equal to 5 = 4
returns false
!= is not equal to 5 != 4
returns true

Logic Operators

Logic operators can be used to combine two or more comparision statements combined into one statement to determine its status. For example, we can check to see if value A greater than value B and value B greater then value C. Let's check out some examples.
Operator Name Example Output
&& and (6 > 5 && 1 < 7) returns true
|| or (2 > 5 || 1 < 7) returns true

If you're not familiar with the logic operations and their usage, please refer to the table below for reference. The table shows what you would get back when performating logic operatioon on two values p and q where T = True and F = False.
p q p and q p or q
T T T T
T F F T
F T F T
F F F F

PHP Operators

Welcome! In this section we going to cover differect kinds of operators we use in programming. These operators are common to ever language. So, in PHP they are no diffrent. We will go through each type of operators with examples on how they are done PHP.

Arithmetic Operators
In programming, we often perform arthmenteic operations to calculate values. Below is the list of these oprators with examples.
Operator Name Example Output
+ Addition $num = 5+5;
echo $num
?>
10
- Subtraction $num = 5-5;
echo $num
?>
0
* Multiplication $num = 5*5;
echo $num
?>
25
/ Division $num = 5/5;
echo $num
?>
1

Comparison Operators

Comparison Operators prove very useful when checking the status of two variables or values. For example, if you wna tto check if one is equal to the other, we would use = operator. Comparasion operators are used in logic conditional statements (check PHP If...else section) to evalute if the condition is true or false.
Operator Name Example Output
> is greater than 6 > 5

5 > 6
First example returns true.

Second example returns false.
< is less than 6 < 5

5 < 6
First example returns false.

Second example returns true.
>= is greater than equal to 5 >= 4
returns true
<= is less than equal to 5 <= 4
returns false
== is equal to 5 = 4
returns false
!= is not equal to 5 != 4
returns true

Logic Operators

Logic operators can be used to combine two or more comparision statements combined into one statement to determine its status. For example, we can check to see if value A greater than value B and value B greater then value C. Let's check out some examples.
Operator Name Example Output
&& and (6 > 5 && 1 < 7) returns true
|| or (2 > 5 || 1 < 7) returns true

If you're not familiar with the logic operations and their usage, please refer to the table below for reference. The table shows what you would get back when performating logic operatioon on two values p and q where T = True and F = False.
p q p and q p or q
T T T T
T F F T
F T F T
F F F F

Strings in PHP

Welcome! In programming, a string is a sequence of letters, symbols, characters and arithmetic values or combination of all tied together in single or double quotes

Example - PHP String

$str = "I Love PHP";
echo $str
?>

In the above example, we store the string value "I Love PHP" in a variable name $str and use echo to output its value.

PHP Strings Operators

Concatenating Strings in PHP

Sometimes while working with strings in our code, we need to join two strings. In PHP, you can use '.' to concatenate two or more strings together to form a single string.

Example 1 - Concatenating PHP Strings

$str1 = "I Love PHP.";
$str2 = "PHP is fun to learn.";
echo $str1." ".$str2;
?>

In the above example we join $str1, empty string and $str2 to form a single string. The above code will output "I Love PHP. PHP is fun to learn."

Example 2 - Concatenating PHP Strings

Another way you to concatenate strings in PHP.

$str1 = "I Love PHP.";
$str2 = $str1." PHP is fun to learn.";
echo $str2;
?>

In the above example we join $str1 with " PHP is fun to learn." and set it $str2 to form a single string and echo str2. The above code will output the same value, "I Love PHP. PHP is fun to learn." as above.

PHP Strings in Single and Double Quotes

Strings in Double Quotes

As we saw in our examples, strings are wrapped in double quotes. Using double quotes is the primary method. Double quotes allow us to escape specials characters in our string. For example, you can use a single quotes with in double quotes.
Special characters are escaped using backslash. Sometimes we need escape special characters in our strings. We will learn about in the following section.

Example - String in Double Quotes

$str = "It's a nice day today."
echo $str;
?>

Notice the apostrophe. It's a special character which we didn't need to escape in double quotes.

Strings in Single Quotes

Example - String in Single Quotes

$str = 'This is a PHP string examples in single quotes';
echo $str;
?>

Single Quotes vs. Double Quotes

Thou looking at single quote strings and double strings you may think there is any difference. However, there are reasons for using single quotes and doubles in a string.

Single quotes should be used when outputting HTML code. Since HTML tag attributes use double quotes with in themselves and since using double quotes in HTML tags is the convention, therefore it is advisable to use single quotes when wrapping a HTML code in PHP. Here's an example.

Example - Single Quotes used for wrapping HTML Code

echo '';
?>

Double quotes are used when we want to use special characters in our strings such as new line characters \n and \r. Single quotes will treat them as regular characters. Also when printing a variable in a string, it is advisable to use double quotes. For example…

Example - Variable Wrapped in Double Quote String

$name = "Matt";
echo "Hello $name!";
?>

Escaping Special Characters

As mentioned above we can escape characters in a string using backslash. An example would be using quotes inside quotes in a string. Let's have a look.

Example - Escaping quotes with in quotes

$str = "\"This is a PHP string examples in double quotes\"";
echo $str;
?>

Notice the \". We escaped the double quote using a backslash. The above code will output "This is a PHP string examples in double quotes" in double quotes.

And same goes with single quotes. When you need to use single quotes within single quote, we need to escape it.

$str = 'It\'s a nice day today.';
echo $str;
?>

In the above example we escaped the apostrophe using a backslash like this \'.

Useful PHP String Functions

Here we will list some of the commonly used PHP string functions.

Example - strlen() Function

This function returns the number of characters in a string. It takes a string as an argument.

$str = "Hello!";
echo strlen($str);
?>

The above will output 6.

Example - str_replace() Function

This function replaces all occurrences of the search string in the main string with the replace string. Let's look at the example below.

$str = "Hello! How are you today?";
echo str_replace("Hello", "Hi", $str);
?>

In the above example, I'm saying replace the "Hello" with "Hi" in string $str. The above code will output "Hi! How are you today?"

Example - strtoupper() Function

This function converts all lower case letters to upper.

$str = "hello!";
echo strtoupper($str);
?>

The above example will output "HELLO!"

Example - ucfirst() Function

This function changes the first letter in the string to upper case.

$str = "hello!";
echo ucfirst($str);
?>

The above example will output "Hello!"

Example - trim() Function

This function removes whitespace from the beginning and from the end of the string.

$str = " hello! ";
echo trim($str);
?>

The above example will output "hello!"

Strings in PHP

Welcome! In programming, a string is a sequence of letters, symbols, characters and arithmetic values or combination of all tied together in single or double quotes

Example - PHP String

$str = "I Love PHP";
echo $str
?>

In the above example, we store the string value "I Love PHP" in a variable name $str and use echo to output its value.

PHP Strings Operators

Concatenating Strings in PHP

Sometimes while working with strings in our code, we need to join two strings. In PHP, you can use '.' to concatenate two or more strings together to form a single string.

Example 1 - Concatenating PHP Strings

$str1 = "I Love PHP.";
$str2 = "PHP is fun to learn.";
echo $str1." ".$str2;
?>

In the above example we join $str1, empty string and $str2 to form a single string. The above code will output "I Love PHP. PHP is fun to learn."

Example 2 - Concatenating PHP Strings

Another way you to concatenate strings in PHP.

$str1 = "I Love PHP.";
$str2 = $str1." PHP is fun to learn.";
echo $str2;
?>

In the above example we join $str1 with " PHP is fun to learn." and set it $str2 to form a single string and echo str2. The above code will output the same value, "I Love PHP. PHP is fun to learn." as above.

PHP Strings in Single and Double Quotes

Strings in Double Quotes

As we saw in our examples, strings are wrapped in double quotes. Using double quotes is the primary method. Double quotes allow us to escape specials characters in our string. For example, you can use a single quotes with in double quotes.
Special characters are escaped using backslash. Sometimes we need escape special characters in our strings. We will learn about in the following section.

Example - String in Double Quotes

$str = "It's a nice day today."
echo $str;
?>

Notice the apostrophe. It's a special character which we didn't need to escape in double quotes.

Strings in Single Quotes

Example - String in Single Quotes

$str = 'This is a PHP string examples in single quotes';
echo $str;
?>

Single Quotes vs. Double Quotes

Thou looking at single quote strings and double strings you may think there is any difference. However, there are reasons for using single quotes and doubles in a string.

Single quotes should be used when outputting HTML code. Since HTML tag attributes use double quotes with in themselves and since using double quotes in HTML tags is the convention, therefore it is advisable to use single quotes when wrapping a HTML code in PHP. Here's an example.

Example - Single Quotes used for wrapping HTML Code

echo '';
?>

Double quotes are used when we want to use special characters in our strings such as new line characters \n and \r. Single quotes will treat them as regular characters. Also when printing a variable in a string, it is advisable to use double quotes. For example…

Example - Variable Wrapped in Double Quote String

$name = "Matt";
echo "Hello $name!";
?>

Escaping Special Characters

As mentioned above we can escape characters in a string using backslash. An example would be using quotes inside quotes in a string. Let's have a look.

Example - Escaping quotes with in quotes

$str = "\"This is a PHP string examples in double quotes\"";
echo $str;
?>

Notice the \". We escaped the double quote using a backslash. The above code will output "This is a PHP string examples in double quotes" in double quotes.

And same goes with single quotes. When you need to use single quotes within single quote, we need to escape it.

$str = 'It\'s a nice day today.';
echo $str;
?>

In the above example we escaped the apostrophe using a backslash like this \'.

Useful PHP String Functions

Here we will list some of the commonly used PHP string functions.

Example - strlen() Function

This function returns the number of characters in a string. It takes a string as an argument.

$str = "Hello!";
echo strlen($str);
?>

The above will output 6.

Example - str_replace() Function

This function replaces all occurrences of the search string in the main string with the replace string. Let's look at the example below.

$str = "Hello! How are you today?";
echo str_replace("Hello", "Hi", $str);
?>

In the above example, I'm saying replace the "Hello" with "Hi" in string $str. The above code will output "Hi! How are you today?"

Example - strtoupper() Function

This function converts all lower case letters to upper.

$str = "hello!";
echo strtoupper($str);
?>

The above example will output "HELLO!"

Example - ucfirst() Function

This function changes the first letter in the string to upper case.

$str = "hello!";
echo ucfirst($str);
?>

The above example will output "Hello!"

Example - trim() Function

This function removes whitespace from the beginning and from the end of the string.

$str = " hello! ";
echo trim($str);
?>

The above example will output "hello!"

Strings in PHP

Welcome! In programming, a string is a sequence of letters, symbols, characters and arithmetic values or combination of all tied together in single or double quotes

Example - PHP String

$str = "I Love PHP";
echo $str
?>

In the above example, we store the string value "I Love PHP" in a variable name $str and use echo to output its value.

PHP Strings Operators

Concatenating Strings in PHP

Sometimes while working with strings in our code, we need to join two strings. In PHP, you can use '.' to concatenate two or more strings together to form a single string.

Example 1 - Concatenating PHP Strings

$str1 = "I Love PHP.";
$str2 = "PHP is fun to learn.";
echo $str1." ".$str2;
?>

In the above example we join $str1, empty string and $str2 to form a single string. The above code will output "I Love PHP. PHP is fun to learn."

Example 2 - Concatenating PHP Strings

Another way you to concatenate strings in PHP.

$str1 = "I Love PHP.";
$str2 = $str1." PHP is fun to learn.";
echo $str2;
?>

In the above example we join $str1 with " PHP is fun to learn." and set it $str2 to form a single string and echo str2. The above code will output the same value, "I Love PHP. PHP is fun to learn." as above.

PHP Strings in Single and Double Quotes

Strings in Double Quotes

As we saw in our examples, strings are wrapped in double quotes. Using double quotes is the primary method. Double quotes allow us to escape specials characters in our string. For example, you can use a single quotes with in double quotes.
Special characters are escaped using backslash. Sometimes we need escape special characters in our strings. We will learn about in the following section.

Example - String in Double Quotes

$str = "It's a nice day today."
echo $str;
?>

Notice the apostrophe. It's a special character which we didn't need to escape in double quotes.

Strings in Single Quotes

Example - String in Single Quotes

$str = 'This is a PHP string examples in single quotes';
echo $str;
?>

Single Quotes vs. Double Quotes

Thou looking at single quote strings and double strings you may think there is any difference. However, there are reasons for using single quotes and doubles in a string.

Single quotes should be used when outputting HTML code. Since HTML tag attributes use double quotes with in themselves and since using double quotes in HTML tags is the convention, therefore it is advisable to use single quotes when wrapping a HTML code in PHP. Here's an example.

Example - Single Quotes used for wrapping HTML Code

echo '';
?>

Double quotes are used when we want to use special characters in our strings such as new line characters \n and \r. Single quotes will treat them as regular characters. Also when printing a variable in a string, it is advisable to use double quotes. For example…

Example - Variable Wrapped in Double Quote String

$name = "Matt";
echo "Hello $name!";
?>

Escaping Special Characters

As mentioned above we can escape characters in a string using backslash. An example would be using quotes inside quotes in a string. Let's have a look.

Example - Escaping quotes with in quotes

$str = "\"This is a PHP string examples in double quotes\"";
echo $str;
?>

Notice the \". We escaped the double quote using a backslash. The above code will output "This is a PHP string examples in double quotes" in double quotes.

And same goes with single quotes. When you need to use single quotes within single quote, we need to escape it.

$str = 'It\'s a nice day today.';
echo $str;
?>

In the above example we escaped the apostrophe using a backslash like this \'.

Useful PHP String Functions

Here we will list some of the commonly used PHP string functions.

Example - strlen() Function

This function returns the number of characters in a string. It takes a string as an argument.

$str = "Hello!";
echo strlen($str);
?>

The above will output 6.

Example - str_replace() Function

This function replaces all occurrences of the search string in the main string with the replace string. Let's look at the example below.

$str = "Hello! How are you today?";
echo str_replace("Hello", "Hi", $str);
?>

In the above example, I'm saying replace the "Hello" with "Hi" in string $str. The above code will output "Hi! How are you today?"

Example - strtoupper() Function

This function converts all lower case letters to upper.

$str = "hello!";
echo strtoupper($str);
?>

The above example will output "HELLO!"

Example - ucfirst() Function

This function changes the first letter in the string to upper case.

$str = "hello!";
echo ucfirst($str);
?>

The above example will output "Hello!"

Example - trim() Function

This function removes whitespace from the beginning and from the end of the string.

$str = " hello! ";
echo trim($str);
?>

The above example will output "hello!"

Php veriables

Welcome! A variable is a mean to store values such as strings or integers so we can easily reuse those values in our code. For example, we can store a string value such as "I Love PHP" or an integer value such as 100 into a variable. When ever we need to use these values, we simply call that variable instead writing out those values over and over again in our code. Here is an example.

$str="I love PHP"; //here is one variable with a string value
echo $str; // here we print the $str value onto the browser

$num = 100; //another variable with a integer value
echo $num; // here we echo the $num variable to print its value

echo $str; //here we reuse the $str variable to print its value again in our code
echo $num; //here we reuse the $num variable to print its value again in our code
?>

The following code should print "I Love PHP100I Love PHP100". Try it. Copy the code in an empty file, save the file as php and run it on your browser.

Variables in PHP

Every language has its own semantics of defining variables. In PHP, we define a variable starting with a $ sign, then write the variable name and finally assign a value to it. Here is an example below.

$variable_name = value;

You must add the $ sign when declaring variables, otherwise it will not work. It is advisable that when you define a variable, you must initilaize it by assign it a value.

Working With PHP Variables

Few Naming Rules

There are few things we need to note when working with PHP variables.

* A variable name should only start with underscore "_" or a letter.
* A variable can only contain letters, numbers or underscore. In another words, you can't use other funky characters like <^# in your variables names.

Declaring a PHP Variable

Let say we want to store values using variables in PHP. Here's how we do it.

* First, think of a logical name for a variable. For example, if you we want to store the text of your company logo in a variable, the logical name for that variable would be something like $logo_text. Remember, you can name your variables whatever you like. But you must choose logical names so it is easier to remember what they are.
* Assign that variable a value.
* Remember to put the $ sign in front of the variable name.

Let's look at some example...

PHP String Variable

Example - PHP variable with a string value

$logo_text = "PHP-Learn-It! Learn PHP by examples";
echo $logo_text;
?>

In the above code we define a variable name $logo_text, assign it a string value "PHP-Learn-It! Learn PHP by examples" and print its value onto the page.

PHP Integer Variable

Example - PHP variable with an integer value

$number = 100;
echo $number;
?>

In the above code we define a variable name $number, assign it an integer value of 100 and print its value onto the page.

PHP Float or Decimal Variable

Example - PHP variable with a float or decimal value

$decimal_number = 100.01;
printf("%.2f", $decimal_number);
?>

In the above code we define a variable name $decimal_number, assign it a decimal value of 100.01 and print its value onto the page.

Php veriables

Welcome! A variable is a mean to store values such as strings or integers so we can easily reuse those values in our code. For example, we can store a string value such as "I Love PHP" or an integer value such as 100 into a variable. When ever we need to use these values, we simply call that variable instead writing out those values over and over again in our code. Here is an example.

$str="I love PHP"; //here is one variable with a string value
echo $str; // here we print the $str value onto the browser

$num = 100; //another variable with a integer value
echo $num; // here we echo the $num variable to print its value

echo $str; //here we reuse the $str variable to print its value again in our code
echo $num; //here we reuse the $num variable to print its value again in our code
?>

The following code should print "I Love PHP100I Love PHP100". Try it. Copy the code in an empty file, save the file as php and run it on your browser.

Variables in PHP

Every language has its own semantics of defining variables. In PHP, we define a variable starting with a $ sign, then write the variable name and finally assign a value to it. Here is an example below.

$variable_name = value;

You must add the $ sign when declaring variables, otherwise it will not work. It is advisable that when you define a variable, you must initilaize it by assign it a value.

Working With PHP Variables

Few Naming Rules

There are few things we need to note when working with PHP variables.

* A variable name should only start with underscore "_" or a letter.
* A variable can only contain letters, numbers or underscore. In another words, you can't use other funky characters like <^# in your variables names.

Declaring a PHP Variable

Let say we want to store values using variables in PHP. Here's how we do it.

* First, think of a logical name for a variable. For example, if you we want to store the text of your company logo in a variable, the logical name for that variable would be something like $logo_text. Remember, you can name your variables whatever you like. But you must choose logical names so it is easier to remember what they are.
* Assign that variable a value.
* Remember to put the $ sign in front of the variable name.

Let's look at some example...

PHP String Variable

Example - PHP variable with a string value

$logo_text = "PHP-Learn-It! Learn PHP by examples";
echo $logo_text;
?>

In the above code we define a variable name $logo_text, assign it a string value "PHP-Learn-It! Learn PHP by examples" and print its value onto the page.

PHP Integer Variable

Example - PHP variable with an integer value

$number = 100;
echo $number;
?>

In the above code we define a variable name $number, assign it an integer value of 100 and print its value onto the page.

PHP Float or Decimal Variable

Example - PHP variable with a float or decimal value

$decimal_number = 100.01;
printf("%.2f", $decimal_number);
?>

In the above code we define a variable name $decimal_number, assign it a decimal value of 100.01 and print its value onto the page.

Php veriables

Welcome! A variable is a mean to store values such as strings or integers so we can easily reuse those values in our code. For example, we can store a string value such as "I Love PHP" or an integer value such as 100 into a variable. When ever we need to use these values, we simply call that variable instead writing out those values over and over again in our code. Here is an example.

$str="I love PHP"; //here is one variable with a string value
echo $str; // here we print the $str value onto the browser

$num = 100; //another variable with a integer value
echo $num; // here we echo the $num variable to print its value

echo $str; //here we reuse the $str variable to print its value again in our code
echo $num; //here we reuse the $num variable to print its value again in our code
?>

The following code should print "I Love PHP100I Love PHP100". Try it. Copy the code in an empty file, save the file as php and run it on your browser.

Variables in PHP

Every language has its own semantics of defining variables. In PHP, we define a variable starting with a $ sign, then write the variable name and finally assign a value to it. Here is an example below.

$variable_name = value;

You must add the $ sign when declaring variables, otherwise it will not work. It is advisable that when you define a variable, you must initilaize it by assign it a value.

Working With PHP Variables

Few Naming Rules

There are few things we need to note when working with PHP variables.

* A variable name should only start with underscore "_" or a letter.
* A variable can only contain letters, numbers or underscore. In another words, you can't use other funky characters like <^# in your variables names.

Declaring a PHP Variable

Let say we want to store values using variables in PHP. Here's how we do it.

* First, think of a logical name for a variable. For example, if you we want to store the text of your company logo in a variable, the logical name for that variable would be something like $logo_text. Remember, you can name your variables whatever you like. But you must choose logical names so it is easier to remember what they are.
* Assign that variable a value.
* Remember to put the $ sign in front of the variable name.

Let's look at some example...

PHP String Variable

Example - PHP variable with a string value

$logo_text = "PHP-Learn-It! Learn PHP by examples";
echo $logo_text;
?>

In the above code we define a variable name $logo_text, assign it a string value "PHP-Learn-It! Learn PHP by examples" and print its value onto the page.

PHP Integer Variable

Example - PHP variable with an integer value

$number = 100;
echo $number;
?>

In the above code we define a variable name $number, assign it an integer value of 100 and print its value onto the page.

PHP Float or Decimal Variable

Example - PHP variable with a float or decimal value

$decimal_number = 100.01;
printf("%.2f", $decimal_number);
?>

In the above code we define a variable name $decimal_number, assign it a decimal value of 100.01 and print its value onto the page.