CS174
Chris Pollett
Sep 28, 2020
$fruits = preg_split("/\s+/", "apples oranges banana");
//notice the extra spaces between oranges and banana.
would split on one or more white space characters. So in this case, $fruits = ['apples', 'oranges', 'banana'].
int preg_match ( string $pattern , string $subject [, array &$matches
[, int $flags = 0 [, int $offset = 0 ]]] )
int preg_match_all ( string $pattern , string $subject [, array &$matches
[, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )
that let you find matches to regular expressions. In the above, [] arguments are optional.
preg_match returns 1 (if pattern found), 0 otherwise.
preg_match_all returns the number of matches or false if the pattern is not found.
If a variable $matches is supplied to the function call, then
it will be populated with either the first match found in preg_match case,
or all matches in preg_match_all case. $flags controls the format
of how $matches will be populated, and $offset says at what character
to begin the search in $subject.
preg_replace($pattern, $replacement, $subject) function that let's you substitute regex $pattern matches with a string $replacement of your choice.
<form method="get" action="script.php">
<input type="text" name="my_textfield"
size="10" />
<input type="hidden" name="secret_data"
value="do not peak" />
<input type="submit" name="sendform"
value="Send this Form" />
</form>
script.php?my_textfield=hello&secret_data=do%20not%20peak&sendform=Send%20this%20Form
<form method="post" action="script.php" enctype="multipart/form-data"> <input type="file" name="my_file" />...</form>
$file_handle = fopen("my.dat", "r");
$file_string = fread($file_handle, filesize("my.dat"));
fclose($file_handle);
Here fread reads in its second parameter many bytes.$line = fgets($file_handle, $max_num_bytes_line);
$string = file_get_contents("my.dat");
$lines = file("my.dat");
$fileHandle = fopen("my.dat", "w"); // use "a" for append
fwrite($fileHandle, $out_data);
fclose($fileHandle);
file_put_contents("out.dat", $str);
<?php
/**
* simple_blog.php
* This program is used to maintain a simple web blog. It has two
* pages a landing page, where people can add new blog posts as
* well as see a list of previous posts and an entry page where
* people can read an old post
*/
/**
* Specify location of file containing all the blog posts
*/
define("BLOG_FILE", "blog.txt");
// Determine which activity to perform and call it
$activity = (isset($_REQUEST['a']) && in_array($_REQUEST['a'], [
"main", "entry"])) ? $_REQUEST['a'] . "Controller" : "mainController";
$activity();
/**
* Used to process perform activities realated to the blog landing page
*/
function mainController()
{
$data["BLOG_ENTRIES"] = getBlogEntries();
$data["BLOG_ENTRIES"] = processNewBlogEntries($data["BLOG_ENTRIES"]);
// maybe in the future could modify so also support RSS out
$layout = (isset($_REQUEST['f']) && in_array($_REQUEST['f'], [
"html"])) ? $_REQUEST['f'] . "Layout" : "htmlLayout";
$layout($data, "landingView");
}
/**
* Used to get an array of all the blog entries currently stored on disk.
*
* @return array blog entries [ title1 => post1, title2 => post2 ...] if
* file exists and unserializable, [] otherwise
*/
function getBlogEntries()
{
if (file_exists(BLOG_FILE)) {
$entries = unserialize(file_get_contents(BLOG_FILE));
if ($entries) {
return $entries;
}
}
return [];
}
/**
* Determines if a new blog post was sent from landing form. If so,
* adds the new post, to the end of a current list of posts, and saves the
* serialized result to BLOG_FILE
*
* @param array $entries an array of current blog entries:
* blog entries [ title1 =>post1, title2 => post2 ...]
* @return array blog entries (updated) [ title1 => post1, title2 => post2 ...]
* if file exists and unserializable, [] otherwise
*/
function processNewBlogEntries($entries)
{
$title = (isset($_REQUEST['title'])) ?
filter_var($_REQUEST['title'], FILTER_SANITIZE_STRING) : "";
$post = (isset($_REQUEST['post'])) ?
filter_var($_REQUEST['post'], FILTER_SANITIZE_STRING) : "";
if ($title == "" || $post == "") {
return $entries;
}
$entries = array_merge([$title => $post], $entries);
file_put_contents(BLOG_FILE, serialize($entries));
return $entries;
}
/**
* Used to set up and then display the view corresponding to a single blog
* post.
*/
function entryController()
{
$data["TITLE"] = (isset($_REQUEST['title'])) ?
filter_var($_REQUEST['title'], FILTER_SANITIZE_STRING) : "";
$entries = getBlogEntries();
if (!isset($entries[$data["TITLE"]])) {
mainController();
return;
}
$data["POST"] = $entries[$data["TITLE"]];
$layout = (isset($_REQUEST['f']) && in_array($_REQUEST['f'], [
"html"])) ? $_REQUEST['f'] . "Layout" : "htmlLayout";
$layout($data, "entryView");
}
/**
* Used to output the top and bottom boilerplate of a Web page. Within
* the body of the document the passed $view is draw
*
* @param array $data an associative array of field variables which might
* be echo'd by either this layout in the title, or by the view that is
* draw in the body
* @param string $view name of view function to call to draw body of web page
*/
function htmlLayout($data, $view)
{
?><!DOCTYPE html>
<html>
<head><title>Simple Blog <?php if (!empty($data['TITLE'])) {
echo ":" . $data['TITLE'];
} ?></title></head>
<body>
<?php
$view($data);
?>
</body>
</html><?php
}
/**
* Used to draw the main landing page with blog form on it as well as previous
* blog posts
*
* @param array $data an associative array of field variables which might
* be echo'd by this function. In this case, we will use $data["BLOG_ENTRIES"]
* to output old blog entries
*/
function landingView($data)
{
?>
<h1><a href="simple_blog.php">Simple Blog</a></h1>
<h2>New Blog Entry</h2>
<form>
<div>
<label for='post-title'>Title</label>:
<input id='post-title' name="title" placeholder="Post Title" type="text" />
</div>
<div>
<label for='post-body'>Post</label>:<br />
<textarea id='post-body' name="post" rows="30" cols="80"
placeholder="Type your blog post here" ></textarea>
</div>
<div>
<button>Save</button>
</div>
</form>
<h2>Previous Entries</h2>
<?php
if (!empty($data["BLOG_ENTRIES"])) {
foreach ($data["BLOG_ENTRIES"] as $title => $post) {
?><div><a href="simple_blog.php?a=entry&title=<?=urlencode($title)
?>"><?=$title ?></a></div><?php
}
}
}
/**
* Used to output to the browser an individual blog entry
*
* @param array $data an associative array of field variables which might
* be echo'd by this function. In this case, we will use $data["TITLE"]
* and $data['POST'] which contain the blog post
*/
function entryView($data)
{
?>
<h1><a href="simple_blog.php">Simple Blog</a> : <?=$data['TITLE'] ?></h1>
<h2><?=$data['TITLE'] ?></h2>
<div><?=$data['POST'] ?>
</div>
<?php
}
Which of the following statements is true?
$fp = fopen("/tmp/my-data.txt", "w");
if (flock($fp, LOCK_EX)) {
// do an exclusive/write lock. use LOCK_SH (for shared/read lock)
fwrite($fp, "Write something here\n");
flock($fp, LOCK_UN); // release the lock
} else {
echo "Couldn't lock the file !";
}
fclose($fp);
Locks are released when fclose() is called.
rename($oldname, $newname); //like Unix mv command, renames/moves a file copy($source, $dest); //copies a file, like Unix cp unlink($filename); // delete a file mkdir($path); // make a directory rmdir($path); // delete a directory link($target, $name); // create a link chmod($filename, $mode); // change file permissions chown($filename, $user); // change owner of a file or dir or link chgrp($filename, $group); //change group of a file or dir or link stat($filename); //returns an array saying size, last access, last modified, etc. for a file touch($filename [, int $time = time() [, int $atime ]]); //sets modification/ access times of a file
if(file_exists('/path/to/folder')) { //file_exists check if a file or dir exists
$h = opendir('/path/to/folder'); //can use is_dir to check is something is a directory
while (($item = readdir($h)) !== false) {
$type = is_dir($item) ? "directory" :
(is_link($item) ? "link" :
"file");
//there is also a is_file
echo "$item is a $type\n";
}
}
$text_files = glob("/some_path/*.txt");
foreach($text_files as $file_name) {
//do something
}
Set-Cookie: name=value;Expires=some date;Path=some path;Domain=some_domain;
Cookie: name=value
Cookie: name1=value1; name2=value2; ...to send back multiple cookies.