My photo upload script is not working in php - php

<?php include('header.php');
include ('config.php');
if(isset($_POST['submit_image'])){
$imgname=$_FILES["myimage"]["name"] ;
$target="ProfileImages/";
$filetarget=$target.$imgname;
$tempname=$_FILES["myimage"]["tmp_name"];
$result = move_uploaded_file($tempname,$filetarget);
if($result){
$id=$_SESSION['id'];
$caption=$_POST['caption'];
$q="INSERT into `images` (id,path,caption) VALUES ('$id','$filetarget','$caption')";
$res=mysqli_query($con,$q);
if($res)
{
$msg="Photo Uploaded Sucessfully..";
$_SESSION['msg']=$msg;
header('location:profile.php');
}
}
else{
$msg="Error Not Uploaded...Try Again";
$_SESSION['msg']=$msg;
header('location:profile.php');
}
}
?>
<form method="POST" enctype="multipart/form-data">
<h2><u>Select Image</u></h2><br><input type="file" name="myimage"><br>
<h2><u>Caption</u></h2><br>
<textarea rows="4" cols="25" name="caption"></textarea>
<input type="submit" name="submit_image" value="Upload">
</form>
Heading
I was trying to upload pictures through this code, but after some time I checked it was not working...Can any of you help me how to fix this?

Turn on the PHP Error Reporting!
Isolate the working script and try to find out where the issue is. Make sure if:
the parser enters the first if
is the $filetarget valid file name
was the file move successful
was the query successful
is the redirection to valid page
If you do not have debugger, disable the header('location:profile.php'); to stay on the page and see errors and/or print testing messages such as echo "I am here on line ".__LINE__; to make sure the parser is in.

Related

wordpress php post/redirect/get

I build some code to import csv file to MySQL database but run into form resubmission problem( refreshing the page, upload the file again). I am trying to use post/redirect/get pattern to solve this problem but in WordPress it gets kind of tricky since redirect is working correctly.
<?php
/***update csv file ***/
if(isset($_POST["submit"])) //if submit button is pressed
{
if($_FILES['file']['name']) //if file exists
{
$filename=explode('.', $_FILES['file']['name']);//seperate file into filename and csv
if($filename[1]=='csv'){ //if file format is csv
$handle= fopen($_FILES['file']['tmp_name'], "r");
while($data=fgetcsv($handle)){
$sql="INSERT INTO val_in (xxxx,xxxx,xxxx,xxxx,xxxx,xxxx) VALUES(?,?,?,?,?,?)";
//prepared statement
$stmt=mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt,$sql)){
echo "SQL prepared statement error";
}
else{
echo gettype($data[0]);
mysqli_stmt_bind_param($stmt,"issddi",$data[0],$data[1],$data[2],$data[3],$data[4],$data[5]);
mysqli_stmt_execute($stmt);
}
}
fclose($handle);
print "import done";
}
else{
echo "Incorrect file format. Please select a CSV file. ";
}
}
}
<form method='POST' enctype='multipart/form-data'>
<div align="center">
<label>Import CSV File:</label>
<input type="file" name="file" id="csvFile1" />
<input type="submit" name="submit" value="Import" class="btn btn-info" />
</div>
</form>
I tried a few ways to re-direct but haven't found a way to get things working:
wp_redirect( site_url(),303 );
header("Location: http://localhost:8888/dm_toolkit/wordpress/validation-data-input/?file=val_in_test.csv&submit=Import");
header("Location: xxx.php");
wp_redirect(get_permalink($post->ID) . '?success=true');
none of these are working.
In addition, if I put in a "exit" or "die()" in the end, it goes to a page that does not have any of my existing content.
you can attach a action to template redirect hook. There you can check if your post request is set and do your procession and then do redirection.
add_action('template_redirect', 'handle_post_csv_request');
function handle_post_csv_request()
{
if (isset($_POST["submit"])) { //if submit button is pressed
if ($_FILES['file']['name']) { //if file exists
//your code goes here
wp_redirect(site_url(), 303);
}
}
}

image storing in mysql using php. not showing any errors but my code is not working

I have a code for storing images in db, but its not getting work. anybodey can help me? my code is
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<h1>Test Page</h1>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<input type="file" name="image" />
<input type="submit" name="submit" />
</form>
<?php
if(isset($_POST['submit']))
{
if(getimagesize($_FILES['image']['tmp_name'])== FALSE)
{
echo "Please select an Image";
}
else
{
$image=addslashes($_FILES['image']['tmp_name']);
$name=addslashes($_FILES['image']['name']);
$image=file_get_contents($image);
$image=base64_encode($image);
saveimage($name,$image);
}
}
function saveimage($name,$image)
{
include 'conn.php';
$qry="INSERT INTO topic_images(echcode,topi_num,img_num,img,iname) VALUES('test001','01','01','$image','$name')";
$result=mysql_query($qry,$link);
if($result)
{
echo "<br/> uploaded successfully";
}
else
{
echo "<br/> not uploaded";
}
}
?>
</body>
</html>
how can correct this. this is always shopwing not uploaded. and not getting uploaded. anybody can help me? awaiting your replies.. and the thing is that i am a beginner.
It seems that $result is false, which would often indicate a problem with the MySQL query (assuming you were able to previously connect to and select the database).
PHP will not print MySQL errors by default, if I remember well. So you need to find out any MySQL error in another way.
Try running this just before echoing "not uploaded":
echo mysql_error();
http://php.net/manual/en/function.mysql-error.php
Another thing you can try, is echo the query itself ($qry) before executing it, and then copy it, paste it into an SQL client and run it there, you should be able to see any errors and be in a better environment for fixing them. But...
If you are doing that, make sure you upload a very, very small image (like 1K or less maybe), or maybe upload a small text file instead of an image, otherwise the printed query will be huge and might even crash your browser.
BTW, if this is code that you are developing right now, I think you should use mysqli_ functions instead of deprecated mysql_ functions.

How to prevent a php script form changing to another page

I used a sample I found here with a HTML page calling a PHP script, both are listed below.
It all works well - BUT, I end up with the PHP scrip page and I want to avoid it - I want to stay on the HTML page and NOT move anywhere. I read in some places that I will need JS or AJAX but can't see any actual example.
I am working on my PC under Windows 7 with IIS version 7.5 installed, PHP 5.3.28.
and executing the HTML file inside c:\inetpub.wwwroot
HTML
<div id="contact">
<h2>Enter your First and Last Name</h2>
<form action="frm_script.php" method="post" target="_parent">
<p><strong>First Name:</strong><br /> <input type="text" name="firstName" /></p>
<p><strong>Last Name:</strong><br /> <input type="text" name="lastName"/></p>
<input type="submit" name="submit" value="Add Customer" />
</form>
</div>
PHP Script
<?php
if(isset($_POST['submit']))
{
//get the name and comment entered by user
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
//connect to the database
$dbc = mysqli_connect('localhost', 'root', 'root', 'mdpdata') or die('Error connecting to
MySQL server');
$check=mysqli_query($dbc,"select * from clients where firstname='$firstname' and
lastname='$lastname'");
$checkrows=mysqli_num_rows($check);
if($checkrows>0)
{
print "customer exists";
}
else
{
//insert results from the form input
$query = "INSERT INTO clients(firstName, lastName) VALUES('$firstName', '$lastName')";
$result = mysqli_query($dbc, $query) or die("Sorry, Duplicate Record.'$php_errormsg'");
mysqli_close($dbc);
}
print '<script type="text/javascript">';
print 'alert("The Customer is NOW registered")';
print '</script>';
};
?>
A html document containing a form with an action="" statement results to change to the assigned page. Like yours, to frm_script.php
If you don´t want this to occure, you need an AJAX-request, as you mentioned above, or you can add a
header(location: 'FPRM.HTML');
to the bottom of the php script. So after processing, which should be very fast, the original page is loaded again.
Or you don´t use two pages at all. Just put the html code from FPRM.HTML to the bottom, after the php code, so the page just will be reloaded once the form values are saved. In this case, call the concatenated document simply FPRM.php, and the form action must be set to action="FPRM.php" or is simply not needed, as the form without action statement loads the same page anyway.

Redirecting to a new page after successful login

I'm sure this question has been asked before but I have searched thoroughly for an answer but to no avail. (The only answers I've seen involve ajax) But I'm using just javascript, PHP and HTML.
I have a login.php page and I have already created a HTML page which is to be the landing page right after a user is successfully logged in. How do I go about this?
The following is my code for the login page and the landing page after the login is called transfer.html:
LOGIN.PHP
<div id="content">
<h3>Login to Internet Banking</h3>
<form id="login" action="" method="post">
<p>
<label for="userid">UserID:</label>
<input type="text" name="UserID" id="UserID"/>
</p>
<p>
<label for="PIN">PIN:</label>
<input type="password" name="PIN" id="PIN" />
</p>
<p>
<input type="submit" name="btnSend" value="Login" class="submit_button" />
</p>
</form>
<td> </td>
<p>
Not yet registered?
Click here to register
</p>
<div id="wrap">
<!-- start PHP code -->
<?php
mysql_connect("localhost", "root", "") or die(mysql_error()); // Connect to database server(localhost) with UserID and PIN.
mysql_select_db("registrations") or die(mysql_error()); // Select registration database.
if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['PIN']) && !empty($_POST['PIN'])){
$UserID = mysql_escape_string($_POST['name']);
$PIN = mysql_escape_string(md5($_POST['PIN']));
$search = mysql_query("SELECT UserID, PIN, active FROM users WHERE UserID='".$UserID."' AND PIN='".$PIN."' AND active='1'") or die(mysql_error());
$match = mysql_num_rows($search);
if($match > 0){
$msg = 'Login Complete! Thanks';
}else{
$msg = 'Login Failed!<br /> Please make sure that you enter the correct details and that you have activated your account.';
}
}
?>
<!-- stop PHP Code -->
<?php
if(isset($msg)){ // Check if $msg is not empty
echo '<div class="statusmsg">'.$msg.'</div>'; // Display our message and add a div around it with the class statusmsg
} ?>
</div>
</div>
First of all, move all your PHP code to the top. Without it, my code below wont work.
To do the redirect, use:
header('Location: http://www.example.com/');
Also, please consider my advice. Since it's not the first question today and all your questions are related to basics, you should consider reading some good PHP book to understand how things work.
Here you can find useful links to free books:
https://stackoverflow.com/tags/php/info
Javascript redirection generated with php code:
if($match > 0){
$msg = 'Login Complete! Thanks';
echo "<script> window.location.assign('index.php'); </script>";
}
else{
$msg = 'Login Failed!<br /> Please make sure that you enter the correct details and that you have activated your account.';
}
Php redirection only:
<?php
header("Location: index.php");
exit;
?>
Try header("Location:home.php"); instead of showing $msg = 'Login Complete! Thanks';
Hope it'll help you.
You need to set the location header as follows:
header('Location: http://www.example.com/');
Replacing http://www.example.com of course with the url of your landing page.
Add this where you have finished logging the user in.
Note: When redirecting the user will be immediately redirected so you're message probably won't display.
Additionally, you need to move your PHP code to the top of the file for this solution to work.
On another side note, please see my comment above regarding the use of the deprecated mysql statements and consider using the newer, safer and improved mysqli or PDO statements.
May be use like this
if($match > 0){
$msg = 'Login Complete! Thanks';
echo "<a href='".$link_address."'>link</a>";
}
else{
$msg = 'Login Failed!<br /> Please make sure that you enter the correct details and that you have activated your account.';
}
You could also provide a link to the page after login and have it auto redirect using javascript after 10 seconds.
Just add the following code after the final message you give using PHP code
Print'window.location.assign("index.php")

How to use php in html form?

This is a simple Captcha form which is working well and prints the requested result after I press ‘submit’.
<?php
session_start();
$msgCaptcha = "";
?>
<?php
if (isset($_POST['submit'])){
$secCode = isset($_POST['secCode']) ? strtolower($_POST['secCode']) : "";
if ($secCode == $_SESSION['securityCode']) {
$msgCaptcha = "valid code";
$result = true;
}
else {
$msgCaptcha = "wrong security code";
$result = false;
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
name:<input name="myname" type="text"><br />
Security code: <input class="text" name="secCode" type="text">
<img src="securityCode.php" /><br />
<?php echo $msgCaptcha ?>
<input name="submit" type="submit" value="submit">
</form>
. i.e.
If my input is the same as like in the picture the printing is “valid security code”
and if the input is not the same, the printing is “wrong security code”.
When I change in the form the code to action="mailer.php" this file is opened but ignore of any input in the Captcha validation.
I need mailer.php to be open after Captcha validation.
I have tried onsubmit and some other options, but none of them works as a solution for the above.
Any help would be greatly appreciated.
You could try to include mailer.php after the $msgCaptcha = "valid code"; line.
Any code inside mailer.php would be executed in that block of code, and any $_POST variables required by mailer.php would be available.
The bottom line is, when you call mailer.php, you must have captcha validation in front of that file, otherwise any bot/spammer can bypass your captcha protection just by submitting the form directly to mailer.php
Keep in mind, bots generally ignore javascript, so the validation has to be done server side.
You may want to set a variable prior to including mailer.php that it will check so even if someone did try to directly submit to mailer.php, it won't process the form unless the file was included.
If this doesn't help, post the code for mailer.php so we know what the contents of that file are.
Use header()
if ($secCode == $_SESSION['securityCode']) {
$msgCaptcha = "valid code";
header("Location: http://www.website.com/ ... /mailer.php");
}

Categories