How do you maintain a session in a PHP quiz script?
All you have to do to maintain a session is start it before you call any variables. Once you've started the session, you can store variables for use in later scripts.
Beware though, once the user closes the browser, the sessions' over.
I'd use the following
SCRIPT 1:
<?php
// Start session
session_start();
// Set some variables (this simulates form input)
$_SESSION['answers']['Q1'] = 18;
$_SESSION['answers']['Q2'] = 36;
$_SESSION['answers']['Q4'] = "Fred";
?>
=============================
Hope that helps...
Is PHP an easy language to learn?
I found it easy because I already knew a fair bit of C++, C and Perl.
The syntaxes are very similar
How can you check if the URL exists using PHP?
PHP has a large number of functions which accommodate this. Primarily it sounds like you want to physically check that a page exists remotely by attempting to access it and dealing with the results.
If you are able to, the best solution would be to use the cURL extension which allows PHP to be a full-fledged browser of sorts - it knows about HTTP and can deal with the various issues that come up when checking a page exists (404 errors, etc). You would initiate a request to the provided URL and see if you get content or an error in reply.
The cURL documentation is at: http://www.php.net/manual/en/book.curl.php
If you cannot install extensions, it's OK - most PHP functions that accept filenames can also take URLs! For example, you could attempt loading the page using: $page = file_get_contents($URL). However, there's less definition as to what happens if the remote end provides a large 404 response, etc - so cURL would be preferrable.
Please keep in mind that any URL provided may be malicious: check with the parse_url() function to restrict to HTTP/HTTPS and keep "URLs" like file:///etc/passwd from succeeding!
How do you use an Access database with PHP?
Something I never thought about doing before, but this is possible.
First, you must make sure that your PHP installation has ODBC capabilities. If it does not. see http://php.net/odbc
You must use PHP's ODBC commands. I have never worked with these, you I cannot help you any further. I would recommend a mySQL database. It's simpler and more widely used in the field of web design. I could help you with that instead.
How do you create a loop using PHP?
There are a number of different ways to loop using PHP. They're as follows:
Below are some examples of how each of these types of loop work.
Forfor ($x = 0; $x < 100; $x++) {
echo $x.'
';
}
?>
Foreach$array = array(1, 5, 8, 2, 9);
foreach ($array as $number) {
echo $number.'
';
}
?>
Whilewhile ($x < 10) {
$x++;
echo $x.'
';
}
?>
Do-whiledo {
$x++;
echo $x.'
';
} while ($x < 10);
?>
How do you retrieve and save PHP variables using text files?
Saving and retrieving PHP variables to and from a text file is bad programming practice in most cases, and can have repercussions (for example, the possibility of a variable changing between any two times running a script, and the script not being prepared for the new value).
There are better alternatives available, such as using a database system like MySQL, or a more standardized "text file" system using INI files. See the related links for information on MySQL and INI files. With that in mind:
There are many routes to making a script that retrieves and saves PHP variables in a text file, but a simple and common one may use the functions file_get_contents and file_put_contents, along with others like preg_match.
file_get_contents($filename) can be used to get the variables (and any other content) in our text file.
file_put_contents($filename) can be used to save variables to our text file.
preg_match($pattern, $string) can be used to validate a string and see if it matches the specified pattern.
See the related links for more information on these variables.
Before actually writing the script, a format of writing our variables (and their values) should be planned out. Simply put, what should your text file look like? For this example, we'll assume a style like this:
var1 = "something"
var2 = TRUE
var3 = 59
The style rule we're going to use here is the name of a variable, followed by a space, an equal sign, and another space, then the PHP syntax of a variable value (var1 will be a string, var2 will be a boolean, var3 will be an integer, and such). A new line specifies a new variable declaration.
Now lets go ahead and write our script. The one in this example will be called "index.php", but any name will do.
index.php// First, lay out where our text file is for future use
$path = 'vars.txt';
// Create a function that will take the contents of our text file and transform it into PHP variables
function get_vars() {// This allows us to access the path variable in this custom functionglobal $path;// Get the actual contents of the text file and put it in a variable$contents = file_get_contents($path);// Seperate the content line-by-line$contents = explode("\n", $contents);// Take each line and evaluate itforeach ($contents as $key=>$line) { // Check if the syntax of the line is correct with a regular expressionif (!preg_match('/^[^0-9][A-Za-z0-9_]* = (TRUE|FALSE|NULL|[0-9]*|".*")$/', $line) { // Stop the function so we don't parse any bad syntaxreturn FALSE;
}
// Divide the line by spaces; there should be three divisions
$divisions = explode(' ', $line);
// Now lets give the divisions their rightful names
$varname = $divisions[0];
$value = $divisions[2];
// Lets assign the variable in PHP depending on its value type
if ($value NULL) {$value = 'NULL';
}
elseif (is_int($value)) {$value = $value;
}
elseif (is_str($value)) {$value = '"' . $value . '"';
}
// If the value isn't formatted yet, the value cant be contained by our format
else {return FALSE;
}
// Add the formatted value to the line
$line .= $value;
// Add the line to the file's new content and then a new line
$content .= $line . "\n";
// Repeat this loop if there are more variables to add
}
// Now put the variables in the text file
if (!file_put_contents($path, $content)) {// Something went wrong with putting the content inreturn FALSE;
}
}
// Now play with the functions!
get_vars();
echo $var1; // echos "something" if using example text file from earlier
$var2 = FALSE;
$var3 = 60;
if (!save_vars('$var2,$var3')) {exit('Variables were not saved!');
}
exit('Variables were saved!');
?>
This is a very simple way of going about retrieving and saving PHP variables in text files; its not perfect.
If you're more experienced, toy around with the code and make it more advanced!
What PHP 5 versions are currently released?
As of 01 May 2010 the latest released versions are PHP 5.2.13 and PHP 5.3.2.
How do you select a substring from a string using PHP?
In php to select a sub string from a string, use the command: string substr ( string string, int start [, int length]);Simple Examples:
$rest = substr("abcdef", 1); // returns "bcdef"
$rest = substr("abcdef", 1, 3); // returns "bcd"
$rest = substr("abcdef", 0, 4); // returns "abcd"
$rest = substr("abcdef", 0, 8); // returns "abcdef"
$rest = substr('abcdef', -1, 1); // returns "f"
// Accessing via curly braces is another option
$string = 'abcdef';
echo $string{0}; // returns a
echo $string{3}; // returns d
?>
Meaing of Associative Array in PHP?
There are two types of arrays, associative arrays, and indexed arrays.
Indexed arrays are where you access the items in order, for example
$myArray[0] would be the first item in the array, $myArray[1] would be the second item, and so on.
You can create an indexed array like this:
$myArray = array("item1","item2","item3");
echo $myArray[0]; //item1
echo $myArray[2]; //item3
You can also set your own indexes:
$myArray = array(0=>"item1", 1=>"item2", 5=>"number 5");
echo $myArray[0]; //item1
echo $myArray[2]; //null or doesnt exist, i cant remember
You can also add items after using the square-brackets. If you include a number, that index is set, otherwise it just adds it to the end of the array.
$myArray[9] = "set index 9";
$myArray[] = "add to the end of the array";
Associative arrays use strings instead of numbers.
$colors = array("cat"=>"brown", "dog"=>"yellow", "fish"=>"purple");
echo $colors["cat"]; //brown
echo $colors["fish"]; //purple
And you can add more with the square-brackets again.
$colors["camel"] = "green";
To loop through both types of arrays you can use a foreach loop, or to loop through indexed arrays you can get the length into a variable and a do normal for loop.
URL rewriting is a technique that allows you to use a URL that actually goes to another URL within the same website. This is used mostly in dynamic database generated websites so the final URL is more Search Engine friendly. Example: You have an online store selling widgets. The page for the red widgets is: www.yourwidgetstore.com/products.php?productID=50 Using URL rewrites you could change this to: www.yourwidgetstore.com/red-widgets.html Both of those links would go to the same place but the second one would have much more value to the search engines. To do this you need to be using the .htaccess file. Example: RewriteEngine On RewriteRule red-widgets\.html www.yourwidgetstore.com/products.php?productID=50 To avoid any duplicate links within your site, you would then only link to: www.yourwidgetstore.com/red-widgets.html
How do you print a particular value using PHP?
To print a particular value in PHP you have to select which variable you wish to print. Below is an example of how this can be done.
<?php
$var[1] = "Hello";
$var[2] = "Lalala";
print $var[2]; // prints Lalala but not Hello
?>
Parse error expecting semicolon or comma in PHP file?
Most lines require a semi-colon and the end. It's likely that that line does. A parse error is an error in syntax so you need to add ; at the end of the line like so:
//WRONG
echo "Hello World"
// Right
echo "Hello World";
?>
How are the simple coding of php with database?
Working with mySQL databases:
<?php
// Connects to the database
mysql_connect(servername,username,password);
// Inserts into a database mysql_query(INSERT INTO table(cat1, cat2, cat3) VALUES(one,two,three)); ?>
How do you set the form action to self using PHP?
<form method="post" action="$_SERVER['PHP_SELF']>
(form contents here)
</form>
Paging, or technically referred to as "Pagination" is when you split multiple records into pages, so that they are not all lined up on one long page. For example, if you were to write a query like so: mysql_query("SELECT * FROM to_do_list"); and it generated 500 results... That would not only take quite a bit of CPU power on the server to generate, but it will also generate an incredibly long page - just imagine if when you "Googled" something, it returned all 5 million results... The pagination is the part of the scrip that splits the results into pages with a certain number of query results on each page.
Is there an alternative to using an ampersand to separate GET variables in PHP?
By default, PHP only uses and recognizes the ampersand; however, per the related link, you can change which string is placed in new URLs to separate a query's parameter=argument pairs (arg_separator.output) and which individual characters are recognized as separators in existing URLs (arg_separator.input). Because each individual character in input is a potential separator while the entirety of output is a separator, output must contain only a single character which occurs in input in order for the server to be compatible with itself.
How do you create a script to upload a file in PHP?
Hope your requirement is to upload a file to server .
follow this code.
$files=array();
$file=handleUpload($_FILES);
function handleUpload($upload_file){
if(!$upload_file) return;
$files=array();
$file->file_orig_name = $upload_file['name'];
$file->file_size = $upload_file['size'];
$path_parts = pathinfo($file->file_orig_name);
$file->file_extension = strtolower($path_parts['extension']);
$file->file_mime_type = $upload_file['type'];
$file->file_tmp_name = $upload_file['tmp_name'];
return $files;
}
What does the increment operator do in PHP?
The incremental operator increases the variable by 1. See the example below:
<?php
$number = 10;
$number++;
echo $number; // outputs 11
?>
What is the latest PHP version?
The latest PHP versions are:
PHP 5.3.4 (09 December 2010)
Stable:
PHP 5.3: version 5.3.3 (22 July 2010)
PHP 5.2: version 5.2.14 (22 July 2010)
Release Candidates:
PHP 5.2: version 5.2.14RC1 (17 June 2010)
What are the available encryptions in PHP?
PHP has built-in one way hashing using the md5 function. Additional encryption capabilities are available using the Mcrypt extension.
How do you calculate APR in PHP?
<?php
$month = 360; //How many month you have for payment
$monthlyPayment = 671.96; //Your monthly payment
$moneyBorrowed = 99000; //How much you borrowed
$totalPaid = $month * $monthlyPayment; //Number of months * Monthly payment
$APRequ = $moneyBorrowed / $totalPaid; //Money Borrowed * Total money paid back
$APRMonthly = abs($APRequ-1); //Returns the absolute value of the monthly APR
$APR = $APRMonthly * 12; // Monthly APR to get Yearly APR
echo $APR;
?>
How do you install PHP on a Mac?
Hypertext PreProcessor or we can call it as Personnel Home Page
How can I find the biggest integer my computer can handle using PHP?
You may use the following code to see how far you can push your computer via storing integers; the biggest integer allowed in PHP actually depends on the system PHP is running on, and how big of an integer it allows in its memory. It's advised that, if you really want to do this, that you turn off PHP output limiting, so then you don't get an exhaustion error. <?php for ($i = 0; TRUE; $i++) { echo $i; } ?>