PHP字符串
EA PHP字符串是一系列字符,即用于存储和处理文本。 在PHP中有4种方法可用于指定字符串。
- 单引号
- 双引号
- heredoc语法
- newdoc语法(自PHP 5.3起)
1. 单引号PHP字符串
我们可以通过在单引号中包含文本在PHP中创建一个字符串。 这是在PHP中指定字符串的最简单的方法。如下一个示例 -
<?php
$str='Hello text within single quote';
echo $str;
?>
上面代码执行结果如下 -
Hello text within single quote
我们可以在单个引用的PHP字符串中存储多行文本,特殊字符和转义序列。
<?php
$str1='Hello text
multiple line
text within single quoted string';
$str2='Using double "quote" directly inside single quoted string';
$str3='Using escape sequences \n in single quoted string';
echo "$str1 <br/> $str2 <br/> $str3";
?>
输出结果如下 -
Hello text multiple line text within single quoted string
Using double "quote" directly inside single quoted string
Using escape sequences \n in single quoted string
参考下面实例代码 -
<?php
$num1=10;
$str1='trying variable $num1';
$str2='trying backslash n and backslash t inside single quoted string \n \t';
$str3='Using single quote \'my quote\' and \\backslash';
echo "$str1 <br/> $str2 <br/> $str3";
?>
输出结果如下-
trying variable $num1
trying backslash n and backslash t inside single quoted string \n \t
Using single quote 'my quote' and \backslash
2. 双引号PHP字符串
在PHP中,我们可以通过在双引号中包含文本来指定字符串。 但转义序列和变量将使用双引号PHP字符串进行解释。
<?php
$str="Hello text within double quote";
echo $str;
?>
上面代码执行输出结果 -
Hello text within double quote
`
现在,不能使用双引号直接在双引号字符串内。
<?php
$str1="Using double "quote" directly inside double quoted string";
echo $str1;
?>
上面代码执行输出结果 -
Parse error: syntax error, unexpected 'quote' (T_STRING) in D:\wamp\www\string1.php on line 2
`
我们可以在双引号的PHP字符串中存储多行文本,特殊字符和转义序列。参考如下代码 -
<?php
$str1="Hello text
multiple line
text within double quoted string";
$str2="Using double \"quote\" with backslash inside double quoted string";
$str3="Using escape sequences \n in double quoted string";
echo "$str1 <br/> $str2 <br/> $str3";
?>
上面代码执行输出结果 -
Hello text multiple line text within double quoted string
Using double "quote" with backslash inside double quoted string
Using escape sequences in double quoted string
`
在双引号字符串中,变量将会被解释,这是因为我们对特殊字符进行了转义。
<?php
$num1=10;
echo "Number is: $num1";
?>
上面代码输出结果为 -
Number is: 10
PHP字符串函数
PHP提供了各种字符串函数来访问和操作字符串。 下面给出了重要的PHP字符串函数的列表。
1. PHP strtolower()函数
strtolower()函数以小写字母返回字符串。
语法
string strtolower ( string $string )
示例
<?php
$str="My name is Yiibai";
$str=strtolower($str);
echo $str;
?>
执行结果 -
my name is yiibai
2. PHP strtoupper()函数
strtoupper()函数以大写字母返回字符串。
语法
string strtoupper ( string $string )
示例
<?php
$str="My name is Yiibai";
$str=strtolower($str);
echo $str;
?>
执行结果 -
MY NAME IS YIIBAI
3. PHP ucfirst()函数
ucfirst()函数返回将字符串的第一个字符转换为大写。 它不改变其他字符的大小写。
示例
<?php
$str="my name is Yiibai";
$str=ucfirst($str);
echo $str;
?>
执行结果 -
My name is Yiibai
4. PHP lcfirst()函数
lcfirst()函数返回将第一个字符转换为小写的字符串。 它不改变其他字符的情况。
语法
string lcfirst ( string $str )
示例
<?php
$str="MY name IS YIIBAI";
$str=lcfirst($str);
echo $str;
?>
执行结果 -
mY name IS YIIBAI
5. PHP ucwords()函数
ucwords()函数返回将字符串每个单词的第一个字符转换为大写。
语法
string ucwords ( string $str )
示例
<?php
$str="my name is max su";
$str=ucwords($str);
echo $str;
?>
执行结果 -
My Name Is Max Su
6. PHP strrev()函数
strrev()函数返回字符串反转的形式。
语法
string strrev ( string $string )
示例
<?php
$str="my name is Maxsu jaiswal";
$str=strrev($str);
echo $str;
?>
执行结果 -
lawsiaj oonoS si eman ym
7. PHP strlen()函数
strlen()函数返回字符串的长度。
语法
int strlen ( string $string )
示例
<?php
$str="my name is Max su";
$len=strlen($str);
echo $len;
?>
执行结果 -
16
PHP Cookie
PHP cookie是一个小段信息,存储在客户端浏览器中。它可用于识别用户。
Cookie在服务器端创建并保存到客户端浏览器。 每当客户端向服务器发送请求时,cookie都会嵌入请求。 这样,cookie数据信息可以在服务器端接收。
总之,可以在服务器端创建,发送和接收cookie。
PHP setcookie()函数
PHPsetcookie()函数用于设置带有HTTP响应的cookie。当有cookie设置,可通过作用$_COOKIE超全局变量访问它。
语法:
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
[, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
示例:
setcookie("CookieName", "CookieValue");/* defining name and value only*/
setcookie("CookieName", "CookieValue", time()+1*60*60);//using expiry in 1 hour(1*60*60 seconds or 3600 seconds)
setcookie("CookieName", "CookieValue", time()+1*60*60, "/mypath/", "yiibai.com", 1);
PHP $_COOKIE
PHP$_COOKIE超全局变量用于获取cookie。
示例
$value=$_COOKIE["CookieName"];//returns cookie value
PHP Cookie示例
文件:cookie1.php
<?php
setcookie("user", "Maxsu");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["user"])) {
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["user"];
}
?>
</body>
</html>
上面代码执行结果如下 -
再一刷新页面,看到结果如下 -
PHP删除Cookie
如果您设置cookie的过期时间,则Cookie到期后将被删除。
文件:cookie1.php
<?php
setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ago
?>
PHP Session(会话)
PHP会话(Session)用于临时存储和从一个页面传递信息到另一个页面(直到用户关闭网站)。
PHP会话技术广泛应用于购物网站,我们需要存储和传递购物车信息。 用户名,产品代码,产品名称,产品价格等信息从一个页面传递到另一个页面。
PHP会话为每个浏览器创建唯一的用户ID,以识别用户,并避免多个浏览器之间的冲突。
PHP session_start()函数
PHPsession_start()函数用于启动会话。 它启动一个新的或恢复现有会话。 如果已创建会话,则返回现有会话。 如果会话不可用,它将创建并返回新会话。
语法
bool session_start ( void )
使用示例代码:
session_start();
PHP $_SESSION
PHP$_SESSION是一个包含所有会话变量的关联数组。 它用于设置和获取会话变量值。
示例:存储信息
$_SESSION["user"] = "Minsu";
示例:获取信息
$user = $_SESSION["user"];
echo $user;
PHP会话示例
文件: session1.php
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["user"] = "Maxsu";
echo "Session information are set successfully.<br/>";
?>
<a href="session2.php">Visit next page</a>
</body>
</html>
文件: session2.php
<?php
session_start();
?>
<html>
<body>
<?php
echo "User is: ".$_SESSION["user"];
?>
</body>
</html>
PHP会话计数器示例
文件: sessioncounter.php
<?php
session_start();
if (!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
} else {
$_SESSION['counter']++;
}
echo ("Page Views: ".$_SESSION['counter']);
?>
PHP销毁会话
PHPsession_destroy()函数用于完全销毁所有会话变量。
文件:session3.php
<?php
session_start();
session_destroy();
?>
PHP处理操作
PHP文件系统允许我们创建文件,逐行读取文件,逐个字符读取文件,写入文件,附加文件,删除文件和关闭文件。
PHP打开文件 - fopen()函数
PHPfopen()函数用于打开文件。
语法
resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )
示例
<?php
$handle = fopen("c:\\folder\\file.txt", "r");
// 或者
$handle2 = fopen("c:/folder/file.txt", "r");
?>
PHP关闭文件 - fclose()函数
PHPfclose()函数用于关闭打开的文件指针。
语法
boolean fclose ( resource $handle )
示例代码
<?php
fclose($handle);
?>
PHP读取文件 - fread()函数
PHPfread()函数用于读取文件的内容。 它接受两个参数:资源和文件大小。
语法
string fread ( resource $handle , int $length )
示例
<?php
$filename = "c:\\myfile.txt";
$handle = fopen($filename, "r");//open file in read mode
$contents = fread($handle, filesize($filename));//read file
echo $contents;//printing data of file
fclose($handle);//close file
?>
上面代码输出结果 -
hello,this is PHP Read File - fread()...
PHP写文件 - fwrite()函数
PHPfwrite()函数用于将字符串的内容写入文件。
语法
int fwrite ( resource $handle , string $string [, int $length ] )
示例
<?php
$fp = fopen('data.txt', 'w');//open file in write mode
fwrite($fp, 'hello ');
fwrite($fp, 'php file');
fclose($fp);
echo "File written successfully";
?>
上面代码输出结果 -
File written successfully
PHP删除文件 - unlink()函数
PHPunlink()函数用于删除文件。
语法
bool unlink ( string $filename [, resource $context ] )
示例
<?php
unlink('data.txt');
echo "File deleted successfully";
?>
PHP打开文件
PHPfopen()函数用于打开文件或URL并返回资源。fopen()函数接受两个参数$ filename和$mode。$filename表示要被打开的文件,$mode表示文件模式,例如:只读,读写,只写等。
语法:
resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )
PHP打开文件模式
| 模式 | 描述 |
|---|---|
r |
以只读模式打开文件。 它将文件指针放在文件的开头。 |
r+ |
以读写模式打开文件。 它将文件指针放在文件的开头。 |
w |
以只写模式打开文件。 它将文件指针放在文件的开头,并将文件截断为零长度。 如果找不到文件,则会自动创建一个新文件。 |
w+ |
以读写模式打开文件。 它将文件指针放在文件的开头,并将文件截断为零长度。 如果找不到文件,则会自动创建一个新文件。 |
a |
以只写模式打开文件。 它将文件指针放在文件的末尾。 如果找不到文件,则会创建一个新文件。 |
a+ |
以读写模式打开文件。 它将文件指针放在文件的末尾。 如果找不到文件,则会创建一个新文件。 |
x |
以只写模式创建和打开文件。 它将文件指针放在文件的开头。 如果找到文件,fopen()函数返回FALSE。 |
x+ |
它与x相同,但它以读写模式创建和打开文件。 |
c |
以只写模式打开文件。 如果文件不存在,则会创建它。 如果存在,它不会被截断(与’w‘相反),也不会调用此函数失败(如’x‘的情况)。 文件指针位于文件的开头 |
c+ |
它与c相同,但它以读写模式打开文件。 |
PHP打开文件示例
<?php
$handle = fopen("c:\\folder\\file.txt", "r");
?>
PHP读取文件
PHP提供了从文件读取数据的各种功能(函数)。 可使用不同的函数来读取所有文件数据,逐行读取数据和字符读取数据。
下面给出了可用的几种PHP文件读取函数。
- fread()
- fgets()
- fgetc()
PHP读取文件 - fread()
PHPfread()函数用于读取文件的数据。 它需要两个参数:文件资源($handle)和文件大小($length)。
语法
string fread (resource $handle , int $length )
$handle表示由fopen()函数创建的文件指针。
$length表示要读取的字节长度。
示例
<?php
$filename = "c:\\file1.txt";
$fp = fopen($filename, "r");//open file in read mode
$contents = fread($fp, filesize($filename));//read file
echo "<pre>$contents</pre>";//printing data of file
fclose($fp);//close file
?>
上面代码执行结果如下 -
this is first line
this is another line
this is third line
PHP读取文件 - fgets()函数
PHPfgets()函数用于从文件中读取单行数据内容。
语法
string fgets ( resource $handle [, int $length ] )
示例
<?php
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
echo fgets($fp);
fclose($fp);
?>
上面代码输出结果如下 -
this is first line
PHP读取文件 - fgetc()函数
PHPfgetc()函数用于从文件中读取单个字符。 要使用fgetc()函数获取所有数据,请在while循环中使用!feof()函数作为条件。
语法
string fgetc ( resource $handle )
示例
<?php
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
while(!feof($fp)) {
echo fgetc($fp);
}
fclose($fp);
?>
上面代码输出结果如下 -
this is first line this is another line this is third line
PHP写入文件
PHPfwrite()和fputs()函数用于将数据写入文件。 要将数据写入文件,需要使用w,r+,w+,x,x+,c或c+等这些模式。
PHP写文件 - fwrite()函数
PHPfwrite()函数用于将字符串的内容写入文件。
语法
int fwrite ( resource $handle , string $string [, int $length ] )
示例
<?php
$fp = fopen('data.txt', 'w');//opens file in write-only mode
fwrite($fp, 'welcome ');
fwrite($fp, 'to php file write');
fclose($fp);
echo "File written successfully";
?>
执行上面代码得到以下结果(打开data.txt) -
welcome to php file write
PHP覆盖文件
如果再次运行上面的代码,它将擦除文件的前一个数据并写入新的数据。 下面来看看看只将新数据写入data.txt文件的代码。
<?php
$fp = fopen('data.txt', 'w');//opens file in write-only mode
fwrite($fp, 'hello');
fclose($fp);
echo "File written successfully";
?>
执行上面代码得到以下结果(打开data.txt) -
hello
PHP追加到文件
如果使用a模式,则将不会删除文件的数据。而是将在文件的末尾写入数据。 在下一个主题文章中我们将介绍如何把数据追加到文件中。
PHP删除文件
在PHP中,我们可以使用unlink()函数来删除任何文件。unlink()函数仅接受一个参数:文件名。 它类似于UNIX C的unlink()函数。
如果文件未被删除,PHPunlink()会产生E_WARNING级错误。 如果文件被成功删除,则返回TRUE,否则返回FALSE。
语法
bool unlink ( string $filename [, resource $context ] )
$filename表示要删除的文件的名称。
PHP删除文件示例
<?php
$status=unlink('data.txt');
if($status){
echo "File deleted successfully";
}else{
echo "Sorry!";
}
?>
执行上面代码得到以下结果 -
File deleted successfully
PHP追加文件
可以通过在fopen()函数中使用a或a+模式将数据追加到文件中。 下面来看看一个简单的例子,将数据附加(追加)到data.txt文件中。
让我们先看看文件(data.txt)中的数据。
welcome to php file write
PHP附加到文件 - fwrite()函数
PHPfwrite()函数用于将数据写入和追加到文件中。
示例
<?php
$fp = fopen('data.txt', 'a');//opens file in append mode
fwrite($fp, ' this is additional text ');
fwrite($fp, 'appending data');
fclose($fp);
echo "File appended successfully";
?>
执行上面代码输出结果(查看data.txt文件中的内容)如下 -
welcome to php file write this is additional text appending data
PHP上传文件
在PHP中,只需要通过几行代码,就能完成上传单个和多个文件的处理。
PHP文件上传功能允许上传二进制和文本文件。 此外,您可以通过PHP身份验证和文件操作功能完全控制要上传的文件。
PHP $_FILES
PHP全局$_FILES包含文件的所有信息。 在$_FILES全局变量的帮助下,我们可以得到文件名,文件类型,文件大小,临时文件名和与文件相关的错误。
这里,我们假设文件名是filename。请参考下表 -
| 变量名称 | 描述 |
|---|---|
$_FILES['filename']['name'] |
返回文件名称 |
$_FILES['filename']['type'] |
返回文件的MIME类型 |
$_FILES['filename']['size'] |
返回文件的大小(以字节为单位) |
$_FILES['filename']['tmp_name'] |
返回存储在服务器上的文件的临时文件名。 |
$_FILES['filename']['error'] |
返回与此文件相关联的错误代码。 |
move_uploaded_file()函数
move_uploaded_file()函数将上传的文件移动到新位置。move_uploaded_file()函数在内部检查文件是否通过POST请求上传。 如果文件是通过POST请求上传的,它将移动文件。
语法
bool move_uploaded_file ( string $filename , string $destination )
PHP文件上传示例
文件:uploadform.html
<form action="uploader.php" method="post" enctype="multipart/form-data">
选择上传的文件:
<input type="file" name="fileToUpload"/>
<input type="submit" value="Upload Image" name="submit"/>
</form>
文件:uploader.php
<?php
$target_path = "D:/";
$target_path = $target_path.basename( $_FILES['fileToUpload']['name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "File uploaded successfully!";
} else{
echo "Sorry, file not uploaded, please try again!";
}
?>
上面示例代码执行后,应该能在D:/下找到上传的文件。
PHP下载文件
在PHP中,可使用内置的readfile()函数来实现文件下载。readfile()函数读取一个文件并将其写入输出缓冲区。
PHP readfile()函数
语法
int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )
$filename:表示文件名$use_include_path:它是可选参数。它默认为false。可以将其设置为true以搜索included_path中的文件。$context:表示上下文流资源。int:它返回从文件读取的字节数。
HP下载文件示例:文本文件
在您的网站目录下(我使用的是D:/wamp/www)创建一个文本文件:text.txt。
文件: download1.php
<?php
$file_url = 'http://localhost/text.txt';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: utf-8");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);
?>
PHP下载文件示例:二进制文件
文件:download2.php
<?php
$file_url = 'http://www.myremoteserver.com/file.exe';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);
?>
