I have this code:
<?php
if (isset ($_FILES['UploadFileField'])){
$UploadName = $_FILES['UploadFileField'] ['name'];
$UploadName = mt_rand (100000, 999999).$UploadName;
$UploadTmp = $_FILES['UploadFileField'] ['tmp_name'];
$UploadType = $_FILES['UploadFileField'] ['type'];
$FileSize = $_FILES['UploadFileField'] ['size'];
$UploadName = preg_replace("#[^a-z0-9.]#i", "", $UploadName);
if(($FileSize > 1250000)){
die ("Error - File to Big");
}
if(!$UploadTmp) {
die ("No File Selected");
}
else {
move_uploaded_file($UploadTmp, "Upload/$UploadName");
}
header('Location: /index.php');
exit;
}
?>
This code works, but I need insert a message of successful after that is done Upload file.
Thank you!
if (move_uploaded_file($UploadTmp, "Upload/$UploadName")) {
$message = "Successfully inserted";
header('Location: /index.php?success=true&message='.$message);
}
else {
$message = "Something went wrong";
header('Location: /index.php?success=false&message='.$message);
}
use the if condition for the move_uploaded_file function it will help you. And get the success, message from index file
if ($_GET['success'] == true) {
echo $_GET['message'];
}
Or you can use the SESSION
You can add a parameter when you redirect like :
header('Location: /index.php?upload=true');
And in your index check if you get the parameter and display a message if it's the case and if it's where you want to display the message. You can check also with if else statement if the upload work and change the var to sent
Related
this is the Redirect page code
<?php
if(isset($_REQUEST['msg'])) {
echo base64_decode($_REQUEST['msg']);
}
?>
This code run on my action page
if (mysqli_query($dbcon,$sql)){
$msg=base64_encode('Successfully Registered');
//Redirection
if($msg!=""){
header("Location:../registration.php?msg=$msg");
exit();
}
} else{
$msg=mysqli_error($dbcon);
}
actually my problem is now error messages are show in my redirect page correctly, but this message always show in my redirect page. i refresh the page that message not going But thing i'm in the register page then i go to the home page come back again register page then message in gone. how to fix this error help me place
thi is the full code in my action page
<?php
ob_start();
session_start();
$msg="";
include 'db_connection.php';
$fullname=$_POST['fullname'];
$address=$_POST['address'];
$email=$_POST['email'];
$nic=$_POST['nic'];
$telephone_no=$_POST['telephone_no'];
$loantype=$_POST['loantype'];
$bank=$_POST['bank'];
$amount=$_POST['amount'];
$plan_file=basename($_FILES["plan_file"]["name"]);
$payment_slip_url=basename($_FILES["payment_slip_url"]["name"]);
$date=date('Y-m-d H:i:s');
//$job_description_img_url = basename($_FILES["job_description_img_url"]["name"]);
$sql= "INSERT INTO user_register (fullname,address,email,nic,telephone_no,loantype,bank,amount,plan_file,payment_slip_url,dateposted) VALUES ('$fullname','$address','$email','$nic','$telephone_no','$loantype','$bank','$amount','$plan_file','$payment_slip_url',NOW())";
//slip add START
$folder = "payment_slip/";
$file = $folder.basename($_FILES["payment_slip_url"]["name"]);
//$success = move_uploaded_file($_FILES["payment_slip_url"]["tmp_name"],$file);
$ok=1;
$file_type=$_FILES['payment_slip_url']['type'];
if ($file_type=="image/png" || $file_type=="image/jpeg") {
if(move_uploaded_file($_FILES['payment_slip_url']['tmp_name'], $file))
{
echo "The file ". basename( $_FILES['payment_slip_url']['name']). " is uploaded";
}
else {
echo "Problem uploading file";
}
}
else {
echo "You may only upload JPEGs or PNG files.<br>";
//$msg=base64_encode("You may only upload JPEGs or PNG for Payment Slip");
}
//slip add END
//plan add START
$folder = "plans/";
$file = $folder.basename($_FILES["plan_file"]["name"]);
//$success = move_uploaded_file($_FILES["payment_slip_url"]["tmp_name"],$file);
$ok=1;
$file_type=$_FILES['plan_file']['type'];
if ($file_type=="application/pdf") {
if(move_uploaded_file($_FILES['plan_file']['tmp_name'], $file))
{
echo "The file ". basename( $_FILES['plan_file']['name']). " is uploaded";
}
else {
echo "Problem uploading file";
}
}
else {
//echo "You may only upload PDFs.<br>";
$msg=base64_encode("You may only upload PDFs for Plan Images");
}
//plan add END
if (mysqli_query($dbcon,$sql)){
//echo "OK";
//$msg=base64_encode("Successfully Registered");
$msg=base64_encode('Successfully Registered');
//}else{
//echo "NO";
//$msg=base64_encode("Please enter your details correctly");
//}
//Redirection
if($msg!=""){
header("Location:../registration.php?msg=$msg");
exit();
}
}
else{
$msg=mysqli_error($dbcon);
}
ob_end_flush();
?>
On my form , i allow users to upload files to the database and i send them to another page, which is submission_successful.php, that says "Thank You for Submitting". But i noticed that when i hit the back button on the submission successful php file, it goes back to the form and the same information is there and allows another submission. What i want to do is kill the code, upon hitting back button, or clear everything that was inputted by the user. I found a couple of answers around like using cache control but, some were vague and others didn't work for me. And plus i don't want the user going back to the upload page when they're on the success page. So thats why i will create 2 buttons for "logout" or "go back to upload page" and if they hit back button, it will crash. I want to show the Confirm Form Resubmission page. In other post they are trying to actually prevent the "Confirm Form Resubmission" but i would like to have it for security. Here is my code
developerUpload.php
<?php
session_start();
if(array_key_exists("invalid", $_GET)){
echo '<br><h3 style="color:red;">File(s) were already submitted! Please re-name file or select a different file...</h3>';
}
if(isset($_COOKIE['username'])){
if($_SERVER['REQUEST_METHOD'] =="POST"){
$price = addslashes(trim($_POST['price']));
$description = addslashes(trim($_POST['description']));
if(!empty($price) && !empty($description)){
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
echo '<br>'.$userid;
$pack_id = rand();
//Check file 1
if($_FILES['file1']['error'] !== UPLOAD_ERR_OK){
$file1 = null;
}else{
$target1 = "devFiles/";
$target_file1 = addslashes(trim($target1 . basename($_FILES["file1"]["name"])));
$file1 = addslashes(trim($_FILES['file1']['tmp_name']));
}
//Check file 2
if($_FILES['file2']['error'] !== UPLOAD_ERR_OK){
$file2 = null;
}else{
$target2 = "devFiles/";
$target_file2 = addslashes(trim($target2 . basename($_FILES["file2"]["name"])));
$file2 = addslashes(trim($_FILES['file2']['tmp_name']));
}
//Check file 3
if($_FILES['file3']['error'] !== UPLOAD_ERR_OK){
$file3 = null;
}else{
$target3 = "devFiles/";
$target_file3 = addslashes(trim($target3 . basename($_FILES["file3"]["name"])));
$file3 = addslashes(trim($_FILES['file3']['tmp_name']));
}
//Check file 4
if($_FILES['file4']['error'] !== UPLOAD_ERR_OK){
$file4 = null;
}else{
$target4 = "devFiles/";
$target_file4 = addslashes(trim($target4 . basename($_FILES["file4"]["name"])));
$file4 = addslashes(trim($_FILES['file4']['tmp_name']));
}
//Check file 5
if($_FILES['file5']['error'] !== UPLOAD_ERR_OK){
$file5 = null;
}else{
$target5 = "devFiles/";
$target_file5 = addslashes(trim($target5 . basename($_FILES["file5"]["name"])));
$file5 = addslashes(trim($_FILES['file5']['tmp_name']));
}
//Check video
if($_FILES['video']['error'] !== UPLOAD_ERR_OK){
$video = null;
$videoName = null;
}else{
$target = "devFiles/";
$target_file = addslashes(trim($target . basename($_FILES["video"]["name"])));
$video = addslashes(trim($_FILES['video']['tmp_name']));
$videoName = addslashes(trim($_FILES['video']['name']));
}
if(file_exists($target_file1)
or file_exists($target_file2)
or file_exists($target_file3)
or file_exists($target_file4)
or file_exists($target_file5)
or file_exists($target_file)){
header("Location: developerUpload.php?invalid");
exit;
}
if(move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file1)
&& move_uploaded_file($_FILES["file2"]["tmp_name"], $target_file2)
&& move_uploaded_file($_FILES["file3"]["tmp_name"], $target_file3)
&& move_uploaded_file($_FILES["file4"]["tmp_name"], $target_file4)
&& move_uploaded_file($_FILES["file5"]["tmp_name"], $target_file5)
&& move_uploaded_file($_FILES["video"]["tmp_name"], $target_file)){
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
header("Location: submission_successful.php?");
die();
}
}else{
echo '<br><h1 style="color:red;">VALUES MISSING!</h1>';
}
}
}else {
header("Location: developerLogin.php");
}
?>
submission_successful.php
<?php
session_start();
if(array_key_exists("invalid", $_GET)){
header("Location: developerUpload.php?invalid");
}
if(isset($_COOKIE['username'])){
echo '<br><h1 style="color:red; text_align:center;">Thank You for Submitting!</h1>';
}else{
header("Location: developerLogin.php");
}
?>
I was searching around for days and finally found something. IF you use a HTML command it will remove any input the user put when the user goes back. Because my problem was when the user goes back after be redirected, their information was still there but if you use
<form method="post" enctype="multipart/form-data" autocomplete="off">
it removes everything so it kinda helps. The user will still be allowed to go back but at least now they can't resubmit the data.
Not sure whether you can check if a value exists twice in the database (thus preventing multiple submissions), but you could block users from submitting the form too frequently. Create a timestamp that gets saved upon first submission, and if the second resubmission's timestamp is not too far(big) from the first one, you could try sth like (you are submitting too frequently), or you could use ajax, or this https://es.m.wikipedia.org/wiki/Post/Redirect/Get
Use a session variable like this
$_SESSION["post_id"] = "";
if($_POST) {
if($_POST["post_id"] != $_SESSION["post_id"]) {
$_SESSION["post_id"] = $_POST["post_id"];
// do database submission here
}
}
This sets a session variable and if they resubmit the form it won't post the data twice.
I'v been trying to make a content insert page with php and here is my code
<?php // Initialize variables to null.
$title =""; // Sender Name
$author =''; // Sender's email ID
$date =date('d-m-y'); // Subject of mail
$desc="";//meta description
$keywords="";//meta keywords
$content =""; // Sender's Message
$category="";//chosen category
$pattern1="";//preg_match pattern
$nameError ="";
$contentError ="";
$purposeError ="";
$messageError ="";
$successMessage =""; // On submittingform below function will execute.
$img_dir=$_SERVER["DOCUMENT_ROOT"] . '/practise/grafitti/images/';
$img;
if(isset($_POST['submit'])) { // Checking null values in message.
//check and assign title title
if(empty($_POST["title_post"])){
$nameError = "A title is required";
errors($nameError);
exit();
}
else{
if (preg_match("/^(\w|\s)$/",$_POST['title_post']))
{
$titleError = "Only letters,numbers and white space allowed";
errors($titleError);
}else{
$title=$_POST['title_post'];
}
}
// Checking null values inthe content.
if (empty($_POST["content_post"]))
{
$contentError = "You have not posted any content.<br/> Please do to proceed";
errors($contentError);
exit();
}else {
$content=$_POST["content_post"];
}
//check and assign category
if(!empty($_POST["categories_post"]))
{
$category=$_POST["categories_post"];
}
//Chexk and assign authors name
if (!empty($_POST["author_post"]))
{
$author=$_POST["author_post"];
}
//check and assign value of description
if (!empty($_POST["desc_post"]))
{
$desc=$_POST["desc_post"];
}
//check and assign keywords
if (!empty($_POST["keywords_post"]))
{
$keywords=$_POST["keywords_post"];
}
//process images
if(isset($_FILES["img_post"])){
echo "good to go";
$name=$_FILES["img_post"]["name"];
$tmp_name=$_FILES["img_post"]["tmp_name"];
$type=$_FILES["img_post"]["type"];
$size=$_FILES["img_post"]["size"];
$img_dir;
if(upload($name,$type,$size,$tmp_name,$img_dir)){
if(move_uploaded_file($tmp_name,$img_dir.$name)){
echo "success";
}else{echo php_info;}
$img_upload_Success="File was uploaded successfully";
errors($img_upload_Success);
}else{
$img_upload_Error="File could not be uploaded";
errors($img_upload_Error);
exit();
}
}
echo $title."<br/>";
echo $author."<br/>";
echo $desc."<br/>";
echo $keywords."<br/>";
echo $category."<br/>";
echo $date."<br/>";
}
// Function for filtering input values.function test_input($data)
function errors($err){
echo "<script>
var err='$err'
alert(err)
</script>
";
}
#validate file upload
function upload($fl_name,$fl_type,$fl_size,$fl_tmp_name,$dir){
#check to see if the file is an image or not
if($fl_type!="image/jpeg" && $fl_type!="image/png" && $fl_type!="image/jpg" && $fl_type!="image/gif"){
$typeError="The file type you uploaded is not supported";
errors($fl_type);
exit();
}
#check file size limits
if($fl_size>512000){
$sizeError="Size of the file is too big. Should be at least 500KB";
errors($sizeError);
exit();
}
if(file_exists($dir.$fl_name)){
$existError="Sorry. File already exists";
errors($existError);
exit();
}
}
?>
the problem is,when I want to validate with the file upload. If I don't upload anything the the code still assumes that my $_FILES['img_post'] isset and it therefore runs the code that satisfies that conditions.
Moreover, if I manage to set the $_FILE variable, it still won't upload.Its like the
if(upload($name,$type,$size,$tmp_name,$img_dir))
returns a false value but the upload() is executed.Can someone please tell me how to handle the isset problem and at least a way to show the error causing the file not to be uploaded
you can try this.
if($_FILES['img_post']['error']==0) {
// process
} else {
$error_message = $error_types[$_FILES['img_post']['error']];
// do whatever with the error message
}
For more details you can refer this.
Use this condition below:
if($_FILES['img_post']['error'] == 0){
//uplode file
}
This will check is it's empty or file been selected. If selected, then it will only upload the file.
change this code
if(isset($_FILES["img_post"])){
to
if(isset($_FILES["img_post"]["tmp_name"])){
Use below code:-
if(isset($_FILES["img_post"]["tmp_name"]) && $_FILES["img_post"]["tmp_name"] != ''){
//uplode file
}
OR
if(!empty($_FILES["img_post"]["tmp_name"])){
//uplode file
}
I am trying to restrict Image file type to only JPG,PNG,JPEG but this script is not allowing any file (even if its above mentioned formats) and the NO FILE selected part is also not working. though I am selecting the file it's still alerting you have to select profile picture(the JS alert msg mentioned in the code) what's wrong in the code?
if(isset($_POST['submit'])){
//this part is part of the HTML form. please neglect this. this's working
$user = $_POST['username'];
$pass = $_POST['password'];
$email =$_POST['email'];
if($_FILES["profpic"]["tmp_name"] =="") { //even $_FILES['profpic']['name']=="" is not working
echo "<script>alert('You have to upload Profile Picture.');</script>";
exit();
}
//$check = getimagesize($_FILES["profpic"]["tmp_name"]);
if(getimagesize($_FILES["profpic"]["tmp_name"])) {
echo "<script>alert('Invalid Image.');</script>";
exit();
}
if ($_FILES["profpic"]["size"] > 1000000) {
echo "<script>alert('Your Image is too big,Maximum Image Size is 1MB');</script>";
exit();
}
$type = $_FILES['profpic']['type'];
$allowedImageType = array('image/jpg','image/png','image/jpeg');
function imageType($image){
global $allowedImageType;
if(in_array($image,$allowedImageType))
return true;
else
return false;
}
if(!imageType($type)) {
echo "<script>alert('Only JPG,JPEG,PNG Image Allowed!');</script>";
exit();
}
//the code if everything went right-------------------------
$sql = $conn->query("INSERT INTO users(id,username,password,email) VALUES('','$user','$pass','$email')");
$id = $conn->insert_id;
$picname = "$id.jpg";
move_uploaded_file($_FILES['profpic']['tmp_name'], "images/$picname");
echo "<script>document.getElementById('noti').innerHTML='Account Creation Successful. <a href=\'login.php\'>Click here</a> to Login';</script>";
}
I'm having trouble with a PHP script which apparently is getting errors from one single line. The top line in this bit of code is apparently causing quite a bit of trouble:
if (move_uploaded_file($_FILES["image"]["tmp_name"], "./upload/".$imageName)) {
mysql_query("INSERT " .$pages. " SET inmenu='$inmenu', pagid='$pagid', title='$titlename', content='$contentname', image='$image', youtube='$youtube'")
or die(mysql_error());
header("Location: index.php");
}
The errors I'm getting for the top line of code:
Warning: Unexpected character in input: ' in cms/new.php on line 131
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at cms/new.php:131) in cms/new.php on line 85
First I thought CHmodding the upload folder to 777 would solve this error, but apparently it doesn't. I really don't know what to do anymore. Is there anyone who can help?
The complete block of code that includes the little snippet above:
<?php
}
session_start();
if(!isset($_SESSION['username'])){
header("location:login.php");
}
include("config.php");
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
//set root
$root = getcwd ();
// get form data, making sure it is valid
$inmenu = mysql_real_escape_string(htmlspecialchars($_POST['inmenu']));
$pagid = strtolower(str_replace(" ", "-", mysql_real_escape_string(htmlspecialchars($_POST['pagid']))));
$titlename = mysql_real_escape_string(htmlspecialchars($_POST['title']));
$contentname = mysql_real_escape_string(htmlspecialchars($_POST['contentedit']));
$youtube = mysql_real_escape_string(htmlspecialchars($_POST['youtube']));
// check to make sure both fields are entered
if ($titlename == '' || $pagid == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($pagid, $titlename, $contentname, $error);
}
else
{
if(file_exists($root."/upload/".$_FILES["image"]["name"]))
{
$filename = explode(".",$_FILES['image']['name']);
$randomnumber = rand(0, 10000);
$imageName = $filename[0].$randomnumber.".".$filename[1];
}
else
{
$imageName = $_FILES['image']['name'];
}
$image = mysql_real_escape_string(htmlspecialchars("/upload/".$imageName));
if (move_uploaded_file($_FILES["image"]["tmp_name"], "./upload/".$imageName)) {
// save the data to the database
mysql_query("INSERT " .$pages. " SET inmenu='$inmenu', pagid='$pagid', title='$titlename', content='$contentname', image='$image', youtube='$youtube'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: index.php");
}
else {
// save the data to the database
mysql_query("INSERT " .$pages. " SET inmenu='$inmenu', pagid='$pagid', title='$titlename', content='$contentname', youtube='$youtube'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: index.php");
}
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
?>
When using double quotes you can just insert PHP variables so
Try this:
if (move_uploaded_file($_FILES["image"]["tmp_name"], "./upload/".$imageName)) {
$query = "INSERT " . $pages . SET inmenu=$inmenu, pagid=$pagid, title=$titlename, contenct=$contentname, image=$image, youtube=$youtube";
mysql_query($query) or die(mysql_error());
header("Location: index.php");
}
Another way (if you'd like) would be this:
if (move_uploaded_file($_FILES["image"]["tmp_name"], "./upload/".$imageName)) {
mysql_query("INSERT " .$pages. " SET inmenu='".$inmenu."', pagid='".$pagid."', title='".$titlename."', content='".$contentname."', image='".$image."', youtube='".$youtube."'")
or die(mysql_error());
header("Location: index.php");
}