search
HomeBackend DevelopmentPHP Tutorial php资料的上传与删除方法

php文件的上传与删除方法

1.php文件的上传

先简单布局一个html操作界面:(图片上传为例)




submit提交之后,然后判断上传的文件是否为空。同时可以进行文件大小的控制,获取文件名之后,上传文件。

<?php if($_POST["submit"])
{       //通过字符串截取函数explode()截取出文件后缀名
	$name = $_FILES['photo']['name'];    <span style="font-family: Arial, Helvetica, sans-serif;">//获取上传文件的文件名
	$string = explode(".",$name);
	$i = count($string);
	$substring = $string[$i-1];
	
	//判断文件大小,名称
	if($_FILES['photo']['size'] > 0 && $_FILES['photo']['name'])
	{
		$dir = 'upfiles/';                     //设置保存目录
		if(!is_dir($dir))                      //如果没有该目录
		{
			mkdir($dir);                   //则创建该目录
		}
		
		$format = "Yndhis";
		$date = date($format);     //可以通过设置当前时间来重命名文件名


		$name = $date.".".$substring;  //重新组合文件名    当前时间.文件后缀名
		$path = 'upfiles/'.$name;             //组合成完整的保存路径(目录+文件名)
		
		$i = move_uploaded_file($_FILES['photo']['tmp_name'],$path);   //保存文件到创建的目录下
		if($i == false)
		{
			echo "<script>alert('文件保存失败!');</script>";
			//echo $path;
		}
		//保存到数据库中,保存链接信息(文件地址)到数据库中,即例中的p_url  
		$str = "INSERT INTO picture(s_id,p_url,p_info)VALUES($sid,'$path','$info')";
		$result = mysql_query($str);
	
		if($result)
		{
			echo "<script>alert('图片添加成功!');</script>";
		}
		else
		{
			//echo $str;
			echo "<script>alert('图片添加失败!');</script>";
		}
	}
}
	
?>

文件上传的主要php函数就是move_upload_file("文件名","文件路径"),注意不要写错了。


2.php文件删除

php文件删除只需要使用unlink()函数即可。

<?php /* 图片删除处理页 */
if($_GET["p_url"])
{
	$purl = $_GET["p_url"];    //获取文件保存路径
	$file_delete = "../".$purl;    //根据自己的文件目录设置路径信息
	
	$str = "DELETE FROM picture WHERE p_url='".$purl."'";    //从数据库中删除图片文件
	$delete = mysql_query($str);
	if($delete)
	{
		unlink($file_delete);    //从自己写入的路径删除图片文件
		echo "<script>alert('图片信息删除成功!');window.location.href='picture_manage.php'";
	}
	else
	{
		//echo $str;
		echo "<script>alert('图片信息删除失败!');window.location.href='picture_manage.php'</script>";
	}
}
else
{
	echo "<script>alert('请选择要删除的图片信息!');window.location.href='picture_manage.php'</script>";
}
?>


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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.