search
HomeBackend DevelopmentPHP TutorialLearn php(3) in ten days_PHP tutorial

Learn php(3) in ten days_PHP tutorial

Jul 21, 2016 pm 04:09 PM
phpsessioneffectuseInsidestudylearnuseofPurposesitepage


第七天 学习目的:学会SESSION的使用

SESSION的作用很多,最多用的就是站点内页面间变量传递。在页面开始我们要session_start();开启SESSION;
然后就可以使用SESSION变量了,比如说要赋值就是:$_SESSION['item']="item1";要得到值就是$item1=$_SESSION['item'];,很简单吧。这里我们可能会使用到一些函数,比如说判断是不是某SESSION变量为空,可以这么写:empty($_SESSION['inum'])返回true or false。

下面综合一下前面所说的我们来看一个登陆程序,判断用户名密码是否正确。
登陆表单是这样:login.php




















Administrators Login
Username


Password







处理文件是这样

require_once('conn.php');
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
$exec="select * from admin where username='".$username."'";
if($result=mysql_query($exec))
{
  if($rs=mysql_fetch_object($result))
  {
    if($rs->password==$password)
    {
      $_SESSION['adminname']=$username;
      header("location:index.php");
    }
    else
    {
      echo "<script>alert('Password Check Error!');location.href='login.php';</script>";
    }
  }
  else
  {
  echo "<script>alert('Username Check Error!');location.href='login.php';</script>";
  }
  }
else
{
echo "<script>alert('Database Connection Error!');location.href='login.php';</script>";
} ?>

conn.php是这样:

$conn=mysql_connect ("127.0.0.1", "", "");
mysql_select_db("shop");
?>

由于 $_SESSION['adminname']=$username;我们可以这样写验证是否登陆语句的文件:checkadmin.asp

session_start();
if($_SESSION['adminname']=='')
{
echo "<script>alert('Please Login First');location.href='login.php';</script>";
}
?>

呵呵,今天说到这里,明天说一下怎么弄一个分页。 第八天 学习目的:做一个分页显示

关键就是用到了SQL语句中的limit来限定显示的记录从几到几。我们需要一个记录当前页的变量$page,还需要总共的记录数$num

对于$page如果没有我们就让它=0,如果有
$execc="select count(*) from tablename ";
$resultc=mysql_query($execc);
$rsc=mysql_fetch_array($resultc);
$num=$rsc[0];

这样可以得到记录总数
ceil($num/10))如果一页10记录的话,这个就是总的页数

所以可以这么写
if(empty($_GET['page']))
{
$page=0;
}
else
{
$page=$_GET['page'];
if($pageif($page>=ceil($num/10))$page=ceil($num/10)-1;//因为page是从0开始的,所以要-1
}

这样$exec可以这么写 $exec="select * from tablename limit ".($page*10).",10";
//一页是10记录的

最后我们需要做的就是几个连接:
FirstPage
PrevPage
NextPage
LastPage

这是一个大致的思路,大家可以想想怎么来优化?今天说到这里,明天说一下一些注意的问题。
第九天 学习目的:注意事项

因为我是先学ASP的,所以再做PHP的时候会发现很多地方需要适应。

1、注意不要漏了分号
2、注意不要漏了变量前的$
3、使用SESSION的时候注意不要遗漏session_start();

如果发生错误的时候,可以采用以下方法:
1、如果是SQL语句出错,就注释了然后输出SQL语句,注意也要注释调后续的执行SQL语句
2、如果是变量为空,大多是没有传递到位,输出变量检查一下,检查一下表单的id和name
3、如果是数据库连接出错,检查是否正确打开MY SQL和是否遗漏了连接语句
4、注意缩进,排除括号不区配的错误

在做大网站的时候,我的思路是先构建数据库,确定每一个字段的作用,和表之间的关系。然后设计后台界面,从添加数据开始做起,因为添加是否成功可以直接到数据库里面验证,做好了添加再做显示的页面,最后才是两者的结合。一般来说后台就包括添加删除修改和显示,后台没有问题了,前台也没有什么大问题。前台还需要注意安全性和容错还有就是输出格式。

好了,今天说到这里,明天说一下如果用PHP上传文件和发邮件。
Day 10 Learning purpose: Learn to use PHP to upload files and send emails

The file upload form must add enctype="multipart/form-data"
and Look at the code below:

$f=&$HTTP_POST_FILES['file'];
$dest_dir='uploads';//Set the upload directory
$dest=$ dest_dir.'/'.date("ymd")."_".$f['name'];//I set the file name here plus the date plus the file name to avoid duplication
$r=move_uploaded_file($f ['tmp_name'],$dest);
chmod($dest, 0755);//Set the attributes of the uploaded file

The name of the uploaded file is date("ymd")."_ ".$f['name'] can be used when inserting into the database later. PHP actually moves the file you uploaded from the temporary directory to the specified directory. move_uploaded_file($f['tmp_name'],$dest); This is the key

As for sending emails, it is even simpler. You can use the mail() function

mail("recipient address" ,"Subject","Text","From: sender rnReply-to: sender's address");

However, mail() requires server support, and SMTP server needs to be configured under WINDOWS , Generally speaking, any external LINUX space will work.
It seems that uploading files and sending emails is much simpler than ASP. You only need to call functions. ASP also needs to use different components of the server such as FSO, JMAIL and so on.

That’s it for learning PHP in ten days. My three major series of articles all use “Learning in Ten Days” as their names. What I want to tell you is that getting started with ASP, PHP, and ASP.NET can all take ten days. But mastery is by no means ten days, and everyone still needs to study it by themselves.
Learning purpose: Learn to use PHP to upload files and send emails

The upload file form must add enctype="multipart/form-data"
and
Look at the code below:

$f=&$HTTP_POST_FILES['file'];
$dest_dir='uploads';//Set the upload directory
$ dest=$dest_dir.'/'.date("ymd")."_".$f['name'];//I set the file name here with the date plus the file name to avoid duplication
$r=move_uploaded_file ($f['tmp_name'],$dest);
chmod($dest, 0755);//Set the attributes of the uploaded file

The name of the uploaded file is date("ymd") ."_".$f['name'] can be used when inserting into the database later. PHP actually moves the file you uploaded from the temporary directory to the specified directory. move_uploaded_file($f['tmp_name'],$dest); This is the key

As for sending emails, it is even simpler. You can use the mail() function

mail("recipient address" ,"Subject","Text","From: sender rnReply-to: sender's address");

However, mail() requires server support, and SMTP server needs to be configured under WINDOWS , Generally speaking, any external LINUX space will work.
It seems that uploading files and sending emails is much simpler than ASP. You only need to call functions. ASP also needs to use different components of the server such as FSO, JMAIL and so on.

That’s it for learning PHP in ten days. My three major series of articles all use “Learning in Ten Days” as their names. What I want to tell you is that getting started with ASP, PHP, and ASP.NET can all take ten days. But mastery is by no means ten days, and everyone still needs to study it by themselves.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/314611.htmlTechArticleDay 7 Learning Objective: Learn how to use SESSION. SESSION has many functions. The most commonly used one is the variables between pages within the site. transfer. At the beginning of the page we need session_start(); to open SESSION; then...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Give an example of how to store a user's name in a PHP session.Give an example of how to store a user's name in a PHP session.Apr 26, 2025 am 12:03 AM

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools