473,218 Members | 1,781 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,218 software developers and data experts.

[FAQ] FAQ Thread (Rev 2)

-----------------------------------------------------------------
This is the FAQ thread where the FAQ compilation project goes.
* If you wish to improve the contents, please copy the whole content,
fix it and then post it. When posting, please change the revision
number (increase by 1) in the subject line.
* If you want to comment, do it without changing the subject line.
* Do NOT add new question and answers here. Add here only after
posting it to the separate thread; subject line should begin with
"[FAQ]" tag, for example: [FAQ] What is foo?
* Always use www.example.com for example URLs.
-----------------------------------------------------------------
URL grabbing:
============
Q: How do I retrieve a page from a web site?
A: Pass a URL to file() or file_get_contents(). The former returns the
contents as an array of lines. The latter returns the same as string.

Example:

$html = file_get_contents('http://www.example.com');
Q: How do I retrieve a page from a web site that does browser
detection?
A: Use ini_set() to change the configuration option "user_agent." This
sets
the User-Agent header sent by PHP.

Example:

ini_set('user_agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT
5.1)');
$html = file_get_contents('http://www.example.com');
Q: How do I retrieve a page from a web site that requires a cookie?
A: Use stream_context_create() to create a HTTP context with Cookie as
one of the headers. Then, if you are coding in PHP 5, pass the context to
file() or file_get_contents() as the third parameter. In PHP 4 either
function
accepts a context, so you need to open the URL with fopen() and
retrieve the data a chunk at a time with fread().

Example:

$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>
"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);

$context = stream_context_create($opts);
$f = fopen($url, "rb", false, $context);
while($data = fread($f, 1024)) {
echo $data;
}

stream_context_create() is available in PHP 4.3.0 and above. If you are
using an older version, you would need the cURL functions or use fsockopen()
to open the connection and send the cookie header with fputs().

Example 1:

[cURL example here]

Example 2:

$fp = fsockopen($host, $port);
fputs($fp, "Cookie: foo=bar\r\n\r\n");
while ($data = fgets($fp, 1024)) {
echo $data;
}
-----------------------------------------------------------------
Q: How do I get the address of the referrer?

A: With the variable $_SERVER['HTTP_REFERER']. However, two
caveats:

1. A request might not have a Referer header, in which case
the variable would not be set. Some browsers do not send
Referer headers, for example, while others can be configured
not to.

'The Refer field MUST NOT be sent if the Request-URI was
obtained from a source that does not have its own URI, such
as input from the user keyboard.' [HTTP/1.1]

2. A Referer header can be faked. The information might not
be genuine.

Warning: As with all input, you should be cautious over the
value of $_SERVER['HTTP_REFERER'].

Note: The Referer header is misspelt; the word in English
is 'referrer', with four r's. As the misspelling has made
it into the HTTP specification, it is too late to correct
it.
-----------------------------------------------------------------
Register Globals:
================
Q: Why PHP not parsing forms?
Q: Why form variables not getting posted?
Q: Why form variables are always empty?
<form method="post" action="form.php">
Enter Your Name
<input type="text" name="UserName"></input><br>
<input type="submit" name="submit" value="click"></input>
</form>

<?php
if ($submit == "click"){
echo "Hello, $UserName";
}
</body></html>


Since 4.2.0 register_globals [1] is off by default due to security
reasons [2]. One should use super globals (introduced in 4.1.0) instead
to get to user supplied data [3]. So either fix:

-fix your code [4]:
if(isset($_POST['submit']) && $_POST['submit']=="click")
{
echo 'Hello, '.$_POST['UserName'];
}
-quick&dirty hack:
extract($_REQUEST);
in the global scope.
-enable register_globals

1: http://www.php.net/manual/en/ini.cor...gister-globals
2: http://www.php.net/manual/en/security.globals.php
3:
http://www.php.net/manual/en/languag...s.superglobals
4: $_POST['UserName'] should offcourse be escaped properly (with
htmlspecialchars in this particular case).

-----------------------------------------------------------------
Q: Why HTML is trunctating PHP text? As in
$test = "Mary had a little lamb"; ...
<input type="text" name="T1" value=<?php echo $test;?>>
Take a look at the source (the first place you should look to see what
PHP is actually doing) and you will see it's all there as:
<input type="text" name="T1" value=Mary had a little lamb>

See the html specs on attributes (that is what value is):
http://www.w3.org/TR/html401/intro/sgmltut.html#h-3.2.2

To make a long boring spec short:

The value should be surrounded by quotes if it contains whitespaces,
the quotes used to delimit should be escaped within the value.

eg:
<input type="text" name="T1" value="<?php echo $test;?>">
or
<input type="text" name="T1" value='<?php echo $test;?>'>

would be fine in this case, but will fail if there are quotes in $test:

$test = "The lamb will soon be Mary's little \"ham\"";

will break either quoting style unless escaped with:
<input type="text" name="T1" value='<?php echo
htmlspecialchars($test,ENT_QUOTES);?>'>

-----------------------------------------------------------------
Q: What does @ (at-sign) do?
A: @ is an operator, which, when prepended to an expression,
suppresses error messages. However the usage is discouraged.

Refer:
http://www.php.net/manual/en/languag...rorcontrol.php

Example:

$x = 'a';
extract($x);
@extract($x);
-----------------------------------------------------------------
Q. How do I differentiate an empty string or numeric zero from false?
A. Use the === operator.

Refer:
http://www.php.net/manual/en/languag...comparison.php
-----------------------------------------------------------------
Q. I'm using the GD functions to create thumbnail images. Why am I
getting
such crummy results?

A. imagecopyresized() does not do a very good job scaling down images.
Use
imagecopyresampled() instead. If you are already using
imagecopyresampled(),
the problem might be that the destination image has limited color
range.
Create it with imagecreatetruecolor() instead of imagecreate().
-----------------------------------------------------------------
Q. Where can I find PHP programming jobs?
A. Like Bigfoot, the Loch Ness Monster, and alien abductions, PHP jobs
are a
myth. The truth is, no one will pay you to program in PHP. If someone
tells
you he works as a PHP programmer, he is probably a spy.

A: --todo-- The above answer remains for historical reasons;-)
-----------------------------------------------------------------
Q: Why am I getting the error message 'Headers already sent'?

If you get this error your script flow is broken (in most cases). Using
OB is nothing more than hiding the symptoms of the error.

The error tells you where the real problem lies:
1:<?php
2:error_reporting(E_ALL);
3://do stuff
4:echo "redirecting";
5:
6://do more stuff
7:
8:header("Location: http://localhost/");
9:?>

will produce the error:

Warning: Cannot modify header information - headers already sent by
(output started at /path/to/script.php:4) in /path/to/script.php on
line 8

What is really is trying to say:

Error: line 8 at /path/to/script.php can't send headers. The problem is
at line 4 in /path/to/script.php, it produced some output to the client
so I already had sent all headers before getting to line 8.

But since you already have all required userinput you should find out
wheter you need to sent additional headers (like a redirect) before
outputting anything to the client. So the equivalent script with
correct
top down flow would be:
1:<?php
2:error_reporting(E_ALL);
3:if($condition){
4:header("Location: http://localhost/");
5:die("redirecting");
6:}
7:
8:echo "condition was false";
9:?>
The following script:
1:<?php
2://do stuff
3:?>
4:<html><body>

---------------------

A: PHP produces this error message when you try to set a header for a
web
page after you have already started sending out the content of the
page.

Web content is always delivered with a few headers at the top, ending
with a
blank line. For example, a web page might start like this:
HTTP/1.1 200 OK
Date: Tue, 01 Mar 2005 12:00:00 GMT
Content-Type: text/html

<html>
<body> ... etc...
Once you have started sending the content of a document, you can't add
any
more headers because they won't appear at the top.

To get round this problem, use PHP's output control functions to buffer
the
output before it is sent. For example, you can generate a
"Content-Length"
header as follows:
<?php

ob_start(); // Turn on output buffering

// Create your web page/jpeg file/whatever here
echo "<html><body> ... ";

// Generate a "Content-Length" header
$clen = ob_get_length();
header("Content-Length: $clen");

// Now send the buffered content
ob_flush();


Q. After turning on output buffering I am still getting 'Headers
already
sent.' What the?
A. Something, somewhere is sent to the browser prior to the call to
ob_start().

One possible culprit is white-spaces contained in an included file. To
fix
this, move the call to ob_start() ahead of any include/require
statements.

Another possible culprit is UTF-8 encoding. Unicode-capable editor
often
place an invisible character at the beginning of a UTF-8 text file to
mark
it as UTF-8. This character will be output before any PHP statements
are
executed. To fix this, resave the file as ASCII.

The character in question is the zero-width non-breaking space
(U+FFEF). In
UTF-16 text it's used as a byte order indicator. In UTF-8 it's just a
signature. If you leave it out then an editor might not be able to
correctly
sniff out the encoding, leaving to other problems.

-----------------------------------------------------------------
Error reporting:
===============
Q: Why I don't get any errors?
A: You might have turned the "display errors" off. Turn it on:
1. By changing 'display_errors' to true in php.ini (May require
Apache restart if it is mod_php)
2. Or with the ini_set('display_errors', 1) via script

Refer:
http://www.php.net/manual/en/ref.errorfunc.php
http://www.php.net/ini_set

Q: Why certain errors are not displayed?
A: The error reporting level might be low. Set it to higher value; via
script error_reporting(E_ALL|E_STRICT)

Refer:
http://www.php.net/error_reporting
-----------------------------------------------------------------
Login/Authentication:
====================
Q: How to implement a login system?
A: Use sessions. When the user logins, store the session id in the
database and then compare the current session id with the one stored in
the database on every page. May also check IP; but it may break if the
user is behind proxy.

Refer:
http://www.php.net/session
http://www.mt-dev.com/2002/07/creati...-login-script/
http://www.mt-dev.com/2002/09/php-login-script/

@todo Info about other authentications, better link to the login
implementation (above links use obsolete style)
-------------
Q: How to find the logged in users?
Q: How to find the number of logged in users?

A: If you use session based authentication/login mechanism, it is quite
easy when you use custom-DB-based session--so that the session
variables will be stored in database instead of default files. As the
session will be available in the database table, it is easy to query
it/count the number of sessions or records.

Refer:
http://www.php.net/session_set_save_handler
http://www.code.dearneighbor.com/db_esession.html
-----------------------------------------------------------------
-----------------------------------------------------------------
Contributors:
============
Chung Leong
John Dunlop
Daniel Tryba
Alan Little
Nospam
Philip Ronan
Jan Pieter Kunst

+++
@revision Combined texts. Changed the example URL to www.example.com
@todo Cleanup. Grammar fix. Find proper heading.
Jul 17 '05 #1
0 1474

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: R. Rajesh Jeba Anbiah | last post by:
----------------------------------------------------------------- This is the FAQ thread where the FAQ compilation project goes. * If you wish to improve the contents, please copy the whole...
0
by: Janwillem Borleffs | last post by:
----------------------------------------------------------------- This is the FAQ thread where the FAQ compilation project goes. * If you wish to improve the contents, please copy the whole...
0
by: Janwillem Borleffs | last post by:
----------------------------------------------------------------- This is the FAQ thread where the FAQ compilation project goes. * If you wish to improve the contents, please copy the whole...
3
by: R. Rajesh Jeba Anbiah | last post by:
----------------------------------------------------------------- This is the FAQ thread where the FAQ compilation project goes. * If you wish to improve the contents, please copy the whole...
6
by: Jan Roland Eriksson | last post by:
For those interested, read and rip it up as you wish :-) ===== Archive-name: www/stylesheets/newsgroup-faq Posting-Frequency: twice a week (mondays and thursdays) Last-modified: July 20, 2004...
2
by: Jan Roland Eriksson | last post by:
Archive-name: www/stylesheets/newsgroup-faq Posting-Frequency: once a week Last-modified: 2004-07-26 Version: 2.00 URL: <http://css.nu/faq/ciwas-mFAQ.html> Maintainer: Jan Roland Eriksson...
0
by: Jan Roland Eriksson | last post by:
Archive-name: www/stylesheets/newsgroup-faq Posting-Frequency: once a week Last-modified: 2004-07-26 Version: 2.00 URL: <http://css.nu/faq/ciwas-mFAQ.html> Maintainer: Jan Roland Eriksson...
0
by: Jan Roland Eriksson | last post by:
Archive-name: www/stylesheets/newsgroup-faq Posting-Frequency: once a week Last-modified: 2004-07-26 Version: 2.00 URL: <http://css.nu/faq/ciwas-mFAQ.html> Maintainer: Jan Roland Eriksson...
26
by: Harrie | last post by:
Hi, After Brian mentioned the use for <link rel=..> for navigational purposes in another thread, I've been looking into it and found that HTML 3.2 has two other recognized link types than HTML...
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.