How to edit a filename and delete the image from a folder? - javascript

I am trying to add edit option for image filename and also delete option for the images. All the images are in a folder and I haven't used database at all. I am able to display the image filenames along with button for edit and delete adjacent to every image name.
But I am not sure how to go forward. I know PHP has a unlink() and rename() functions. but I am not sure how to include this functions dynamically.
<?php
echo "<div class='container'>";
if(isset($_POST["submit"])) {
$files = glob("images/Kwebsite/". $_POST['path']."/*.*");
}
echo "<div class='col l5'>";
echo "<h3>Image Filename Actions</h3>";
echo "</div>";
for ($i=0; $i<count($files); $i++){
$num = $files[$i];
$filenamewithextension = basename($num);
$fileextenstion = pathinfo($filenamewithextension, PATHINFO_EXTENSION);
$filename = basename($num,$fileextenstion);
echo '<div class="imagename">';
echo $filename;
echo '<button type="submit" class="btn-flat" value="Delete" onClick="Delete()">Delete</button>';
if(isset($_POST["submit"])) {
$imgfile = glob("images/Kanishk website/". $_POST['path']."/*.*");
foreach $imgfile as $img {
unlink($img)
}
}
}
?>

You have to pass the file path to unlink().
If you want to remove multiple files, you will have to call unlink multiple times. If you push the file paths to an array you can loop over the paths.
$paths['/files/file1.jpg','/files/file2.jpg']
foreach $paths as $file {
unlink($file)
}
If you want to rename the file, you also have to provide the full path,
otherwise you will create a new file somewhere else:
rename ("/files/file1.jpg", "/files/file_1.jpg");
This info has to be provided by a user, at least in most cases.
I would recommend storing the paths and filenames in a database.

First of all, this a dangerous thing you are doing there and you should avoid it. Imagine what could happen if someone gives some level up dots combination like this ../../; the script would have listed all the files 2 levels up. In order to prevent such behavior, we need to check the path input string for slashes and backslashes and do not execute the glob function if some slashes found. Here is the regular expression to validate the path query:
// Check for backslash, level up dir .. and wildcards
$isValidPath = !preg_match('#([\\\.\?\*])#', $path);
I made a very simple example based on your code. All the commands are passed to PHP by posting form data to the server (not AJAX). When the user clicks on delete button, a message confirmation appears and if the user clicks OK, then the form posts the delete button data, which are its name="delete" and the value="path/filename.ext". We'll have a $_POST['delete'] == "path/filename.ext" value in PHP. If we detect the delete in our POST data, then we call the unlink and we delete the file. For the renaming functionality, we use the same method but with the javascript prompt this time, which prompts and asks the user to type a new filename. If the new filename is different from the original, then it updates a hidden field with the new filename and posts the form fields to our PHP server script; the POST data will have these values for the rename function $_POST['rename'] == "path/oldfilename.ext" and $_POST['renameto'] == "newfilename.ext". Then we just call the rename function at the beginning of our script.
Tip: Use PHP print_r function to print the $_POST array inside an HTML <pre></pre> to debug post data on each page refresh:
<pre><?php print_r($_POST) ?></pre>
The final working script
<pre><?php print_r($_POST) ?></pre>
<?php
$hasPath = isset($_POST['path']);
$basePath = __DIR__."/images/Kwebsite/";
$path = '';
$files = array();
if(isset($_POST['rename']) && isset($_POST['renameto'])) {
$fileToRename = $basePath.$_POST['rename'];
$renameTo = dirname($fileToRename).'/'. $_POST['renameto'];
rename($fileToRename, $renameTo);
}
if(isset($_POST['delete'])) {
$fileToDelete = $basePath.$_POST['delete'];
unlink($fileToDelete);
}
if($hasPath) {
// Check for backslash, level up dir .. and wildcards
$path = $_POST['path'];
$isValidPath = !preg_match('#([\\\.\?\*])#', $path);
if($isValidPath) {
$searchPath = $basePath.$path.'/*.*';
$files = glob($searchPath);
}
}
?>
<form method="post">
<label>Search directory: </label>
<input type="text" name="path" value="<?php echo $path ?>"/>
<button type="submit">Search</button>
<hr>
<table border="1">
<thead>
<tr>
<th>Image Filename</th><th>Actions</th>
</tr>
</thead>
<tbody>
<?php if($hasPath && $isValidPath && count($files) > 0): ?>
<?php foreach($files as $file):
$filenameWithExtension = basename($file);
$fileExtenstion = pathinfo($filenameWithExtension, PATHINFO_EXTENSION);
$filename = pathinfo($filenameWithExtension, PATHINFO_FILENAME);
?>
<tr>
<td><?php echo $filename ?></td>
<td>
<button type="submit" name="delete" value="<?php echo "{$path}/{$filenameWithExtension}" ?>" onClick="Delete(event)">Delete</button>
<button type="submit" name="rename" value="<?php echo "{$path}/{$filenameWithExtension}" ?>" onClick="Rename(event)">Rename</button>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
<input type="hidden" id="renameto" name="renameto"/>
</form>
<script type="text/javascript">
function Delete(e) {
var event = e || window.event,
filename = event.target.value.substr(event.target.value.lastIndexOf('/') + 1);
if(!confirm("Are you sure you want to delete this file '"+filename+"'?"))
event.preventDefault();
}
function Rename(e) {
var event = e || window.event,
oldFilename = event.target.value.substr(event.target.value.lastIndexOf('/') + 1),
newFilename = prompt("Enter a new filename", oldFilename);
if(newFilename != null) {
if(newFilename == oldFilename) {
alert("You must give a different filename");
event.preventDefault();
} else {
document.getElementById('renameto').value = newFilename;
}
} else {
event.preventDefault();
}
}
</script>

I am not sure how to include this functions dynamically
Based on your question and your code, it looks like you are capable of deleting or renaming the files but are looking for work flow advice.
I give the following suggestions. If you want code, I am happy to supply my solutions, but the scope of an interface is rather large and needs some clarification first. For example,
Do you have directories that the user navigates?
Do you want the user to have checkboxes to check individual files (recommended) OR do you want them to be able to enter a file pattern as you example shows (dangerous!)?
My recommendations:
Use a table to display the files. Above the table include buttons to "Delete Selected", "Cancel"
Include the following columns in the table:
Checkbox (for selecting multiple files if this is desired)
Filename (just text and can be the label portion of the checkbox)
Editable input with filename allowing user to rename
Input Button = "Rename" (to rename individual file)
Input Button = "Delete" (to delete individual file)
Thumbnail image which they can click on to see a full sized image.
The table is within a form so that each <input> with a name property will end up in $_POST For example, the inputs for renaming a file and submitting it looks like this:
<td><input type=text name=filer-<?php echo encodestr($filefull) ?> value='<?php echo $name ?>'></td>
<td><input type="submit" name="fprename-<?php echo encodestr($filefull) ?>" value="Rename" onClick='return confirm("Do you want to rename this file?");'></td>
where $filefull is the full existing path to the file and $name is without the path. When clicking on the Rename button, $_POST will contain elements with each filename prefixed with filer- so I can easily recognize them. I know which one to rename or delete based on which submit button was pressed which I can tell from the var which is prefixed with fprename-.
So if I get back from $_POST a var named $_POST['fprename-/path/myfile.jpg'], I look for the input var $_POST['filer-/path/myfile.jpg'] and rename the file to the value contained in it (of course checking first that a file with that name doesn't already exist).
Work Flow:
For deleting multiple files
User selects items using checkboxes for deleting and submits form by clicking on the Delete Selected submit button.
The form onSubmit gives a javascript alert() to allow cancelling the delete request.
After user confirms, you want to do a Post/Redirect/Get (to prevent multiple form submission). This involves submitting the form to another php (e.g. processFiles.php) which processes the unlink() code you have then redirects back to the userInterface.php.
For deleting or renaming individual files
User clicks on a submit button in the table next to the individual files.
The button onclick gives a javascript alert() to allow cancelling the delete or rename request.
After user confirms, the form will submit. Again, you want to do a Post/Redirect/Get where another php (e.g. processFiles.php) processes the unlink() or rename code then redirects back to the userInterface.php.
In the following example, I don't allow deleting multiple files, only Selecting multiple files - hence the "Select" button at the top instead of a "Delete Selected".

Related

PHP how to keep the already uploaded file in the edit form

I have uploaded a file in my database below row named 'file_name'. Now when I open my edit form in view mode, the file name does not show (is empty) and when I save the form, the file_name goes blank from the database. I want to save the file in edit form so each time I save the form, the already uploaded file should show in database. I know that value cannot be used for files for security reasons and I also know how to just echo the name of file, but I need to keep the already uploaded file in edit form.
This is my code in edit form in view mode:
<div class="form-group">
<label for="example-text"><?php echo get_phrase('Browse File');?></label>
<input type="file" name="file_name" id = "file_name" class="form-control-file"/><span name="old" id = "old"><?php echo $row['file_name'];?></span>
</div>
This is my code in model:
$page_data['file_name'] = $_FILES["file_name"]["name"];
$oldfile = $_POST['old'];
$file = $_FILES["file_name"]["name"];
if($file != "") {
move_uploaded_file($_FILES["file_name"]["tmp_name"], "uploads/parents_image/" . $_FILES["file_name"]["name"]);
} else {
$file = $oldfile;
$page_data['file_name'] = $this->input->post('file_name');
}
Any advice would be very helpful.
Many thanks. enter image description here
Add
if(isset($_FILES['file_name']) && !empty($_FILES['file_name']){
// your code here
}

Select data from mysql with php, display in html dropdown list and insert selected value as URL parameter via javascript

First, please understand I have just begun to learn php, javascript and ajax in the past 10 days so I will need some hand-holding and step-by-step examples and guidance. I've carefully read the courses for those topics at w3schools and found them very helpful; as a result, I was able to write some basic code for my project by using their examples and other snippets I've found here and other sites.
This post is a little lengthy so I can explain my ultimate goal for this code and what I've already tried.
I have started writing a piece of very complex code that has multiple parts, but the final result will be a dropdown selection list with an image thumbnail button of the main_image of that page linked to an external URL which is dynamically created based on the user's dropdown list selection.
This is my project:
I am building a website with Joomla 3.x.x, Bootstrap 3 and j2store (with other components and modules) that features photos for sale as digital images and that can be applied to physical products (canvas prints, t-shirts, coffee mugs, etc). Those physical products exist on a 3rd party website (Zazzle) which are embedded into my private website with Zazzle's RSS feed and another 3rd party javascript code (to embed Zazzle RSS feed grid displays into my website).
The Zazzle API allows my users to choose any image from my private website and apply that image to any product available in Zazzle's marketplace.
My users would ultimately select a category of products from a dropdown list on my website and then click a button that would open a new window to connect to the Zazzle marketplace which would display a grid of relevant physical products featuring the image shown on the active page of my website where the user clicked the button.
For example, the user starts by looking at the page on my website with the main_image "Light Purple African Daisy", chooses a category of electronic products from a dropdown list and then clicks the "Design Your Own Gifts" button which opens a new window, connects to the Zazzle marketplace and displays a grid of electronic products showing the "Light Purple African Daisy" image on the user's chosen products.
The URL behind the "Design Your Own Gifts" button needs to be created dynamically with the selected value after the user chooses a category of products from a dropdown list on my website.
This is the Zazzle API I need to use:
https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg= <DYNAMIC CATEGORY ID FROM DROPDOWN SELECTION LIST> &t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid= <URLENCODED DYNAMIC PATH OF ACTIVE PAGE MAIN_IMAGE>"
I have created 2 tables in mysql database that hold the Names, Category IDs and Department IDs for the products in my Zazzle marketplace. I am also getting the main_image path from my j2store productimages table.
The code I have been able to write so far accomplishes the following tasks:
Connect to the database
Choose Columns/Tables
GET Data from Columns/Tables
Create HTML Form to Display Result of MYSQL Query
Create Dropdown Selection List of Query Results
Echo encoded URL with Zazzle API concatenated with Parameters/Dynamic Values
This is my code so far:
<div class="form-group" style="margin: 30px 10%;">
<h3>Create Zazzle Products</h3><p><h4>Select a Template Category</h4>
<form name="create-zproducts" id="create-zproducts" action="create-zproduct.php" method="POST">
<?php
//connection
$con = mysqli_connect('localhost', 'user', 'password', 'database');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT * FROM david_cim_template_categories, david_j2store_productimages";
$cg = $_GET['cim_template_cg'];
$coverimage_iid = $_GET['main_image'];
$result = mysqli_query($con,$sql);
?>
<select name="selectZcategories" id="selectZcategories">
<?php
while($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['cim_template_cg'].':'.$row['cim_template_cgname']'">'.$row['cim_template_cgname'].'</option>';
}
?>
</select>
<button onclick="ajaxFunction();">Submit</button><br /><br />
<?php
<script>
function ajaxFunction() {
var selectedData=$("#selectZcategories option:selected").val();
$.ajax({
type : "POST",
url: "select_zproduct.php",
data: { selection : selectedData },
success: function (html) {
//Success handling
}
})
}
</script>
?>
<?php
echo $ZAPI = "https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg=";
echo $cg = ['cim_template_cg'];
echo $ZPARAM = "&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid=https%3A%2F%2Fwww.capturedimagesofmaine.com%2Fimages%2Fproducts%2Foriginal%2F";
echo $coverimage_iid = ['main_image'];
echo $product_text = "&t_text1_txt=Welcome";
?>
</form>
</div>
// new file (select_zproduct.php) added to same path as create_zproduct.php
// contents of select_zproduct.php below:
<?php
if( isset($_POST['selection']) )
{
$selecterData=$_POST['selection'];
$selecterArrayData=explode(':', $selecterData);
$cg=$selecterArrayData[0];
$coverimage_iid=$selecterArrayData[1];
$url='https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg='.$cg.'&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid='.$coverimage_iid.'';
?>
<script>
window.location.href=<?php echo $url; ?>;
</script>
<?php
}
?>
The code above is just the beginning of what I've been able to write by myself so far.
My obstacle at the moment is not being able to make the " cg= " parameter display the numeric value of $cg= which was selected by the user from the dropdown list. The current code returns the word "Array" in the URL instead of the selected value. (eg. cg=Array instead of cg=196215449301144739)
I believe I need to use AJAX and Javascript to accomplish this action but I don't know enough to write it by myself yet.
The Code I Need to Write will accomplish the following tasks:
Assign proper $variables to URL fragments ($ZAPI, $cg, etc) to be used for concatenation
Assign proper $variables to database dropdown SELECTION Result to be used in the URL above
Concatenate all $variables
Parse all $variables
Embed final encoded URL into button
Use thumbnail of active page main_image as button image src
What I need to know right now is how do I insert the numeric value of 'cim_template_cg' into the " cg= " parameter in the final URL so the final URL will output " &cg=196215449301144739 " when the user selects the 'cim_template_cgname' associated with that cg=.
Once I see the solution I can apply it to the other dynamic values I need to create. I've only written one javascript code with help from a snippet so any AJAX or Javascript code that needs to be written will need to be shown to me in an example and describing related files, please.
Thanks for your help in advance!
So if I understood your question properly, you have the necessary data to achieve this, i.e. you have the URL path and ID from the database, as well as the URL string, which needs these database values dynamically added upon selection?
And to answer one of your questions, yes this can be done via AJAX if you wish for the PHP logic to be handled in a seperate file.
What you could do, is concatenate your URL path and ID from the database with a seperator value that you could perform an explode(); on to get the values.
so, your <select> would look something like this instead:
<select name="selectZcategories" id="zCategories">
<?php
while($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['cim_template_cg'].':'.$row['cim_template_cgname'].'">'.$row['cim_template_cgname'].'</option>';
}
?>
</select>
Now to the AJAX function. Personally, I use the jQuery library, simply because it makes things easy and simple. It simplifies a lot of the code, so I am going to go by the jQuery standards in my AJAX example. If you wish to use jQuery AJAX to achieve the same results, you will need to install jQuery into a library that you include like any other normal JS/CSS file etc.
function ajaxFunction() {
var selectedData=$("#zCategories option:selected").val();
$.ajax({
type : "POST",
url: "/path/to/file.php",
data: { selection : selectedData },
success: function (html) {
//Success handling
}
})
}
What this achieves, is that the function will take the selected value of the <select> and parse the data to another file using the POST method. You are able to do a lot of things in the success function if you so desire, but for our purpose, I'll simply perform the redirect in the PHP file.
When the data has been parsed to the other file, you then perform an explode(); on the value to split it up into our two variables that we will parse along in our URL.
The PHP file could look something like this:
<?php
if( isset($_POST['selection']) )
{
$selecterData=$_POST['selection'];
$selecterArrayData=explode(':', $selecterData);
$categoryID=$selecterArrayData[0];
$imagePath=$selecterArrayData[1];
$url='https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg='.$categoryID.'&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid='.$imagePath.'';
?>
<script>
window.location.href=<?php echo $url; ?>;
</script>
<?php
}
?>
How you call the AJAX function initially is up to you. It could be via a button for instance.
<button onclick="ajaxFunction();">Submit</button>
Hope this helped, or pointed you towards the right direction.
For tests as per request by your comment,
Ajax for test:
function ajaxFunction() {
var selectedData=$("#zCategories option:selected").val();
$.ajax({
type : "POST",
url: "/path/to/file.php",
data: { selection : selectedData },
success: function (html) {
//Success handling
alert(html);
}
})
}
PHP:
<?php
if( isset($_POST['selection']) )
{
$selecterData=$_POST['selection'];
$selecterArrayData=explode(':', $selecterData);
$categoryID=$selecterArrayData[0];
$imagePath=$selecterArrayData[1];
$url='https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg='.$categoryID.'&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid='.$imagePath.'';
echo 'cg: '.$categoryID.' img path: '.$imagePath;
?>
<script>
//window.location.href=<?php echo $url; ?>;
</script>
<?php
}
?>
I contacted the developer of J2Store for help with getting the main_image value from the active J2Store product page and embedding my final API URL into my J2Store product pages so he rewrote my code to integrate error-free with both Joomla and J2Store, as follows:
<?php
/**
* #package J2Store
* #copyright Copyright (c)2014-17 Ramesh Elamathi / J2Store.org
* #license GNU GPL v3 or later
*
* Bootstrap 2 layout of product detail
*/
// No direct access
defined('_JEXEC') or die;
$db = JFactory::getDbo();
$query = $db->getQuery(true)->select('*')->from('#__cim_template_categories');
$db->setQuery($query);
$cg_values = $db->loadObjectList();
$image_path = JUri::root();
$main_image = $image_path.$this->product->main_image;
//$zazzle_api = 'https://www.zazzle.com/api/create/at-238500395169782226';
$zazzle_api = 'https://www.zazzle.com/api/create/at-238500395169782226';
?>
<?php if(count($cg_values)): ?>
<div class="cg_values">
<form method="get" class="zazzle_api_form" action="<?php echo $zazzle_api; ?>">
<select name="cg" class="cg">
<?php foreach($cg_values as $cg_value): ?>
<option value="<?php echo $cg_value->cim_template_cg; ?>">
<?php echo $cg_value->cim_template_cgname; ?>
</option>
<?php endforeach; ?>
</select>
<input type="hidden" name="rf" value="238500395169782226" />
<input type="hidden" name="ax" value="DesignBlast" />
<input type="hidden" name="sr" value="250508120301240636" />
<input type="hidden" name="t__useQpc" value="false" />
<input type="hidden" name="ed" value="true" />
<input type="hidden" name="t__smart" value="false" />
<input type="hidden" name="continueUrl" value="<?php echo urlencode('https://www.zazzle.com?www.capturedimagesmaine.com'); ?>" />
<input type="hidden" name="tc" value="" />
<input type="hidden" name="ic" value="" />
<input type="hidden" name="t_text1_txt" value="" />
<input type="hidden" name="t_coverimage_iid" value="<?php echo $main_image; ?>"
/>
<input class="btn btn-primary" type="submit" value="Create Your Own Custom Gifts"
/>
</form>
</div>
<?php endif; ?>

After redirect, how to display error messages coming from original file?

Here's what I'm trying to achieve: I want to redirect the user if any errors I check for are found to a html/php form (that the user see's first where inputs are previously created) with custom error messages.
Details: The User see's the HTML/PHP form first where they enter names in a csv format. After they click create, the names are processed in another file of just php where the names are checked for errors and other such things. If an error is found I want the User to be redirected to the HTML/PHP form where they can fix the errors and whatever corresponding error messages are displayed. Once they fix the names the User can click the 'create user' button and processed again (without errors hopefully) and upon completion, redirect user to a page where names and such things are displayed. The redirect happens after the headers are sent. From what I've read this isn't the best thing but, for now, it'll do for me.
Code For HTML/PHP form:
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formInputNames"><br>
Activate: <input type="checkbox" name="activate">
</form>
<?php
// include 'processForm.php';
// errorCheck($fullname,$nameSplit,$formInputNames);
?>
</body>
</html>
I tried messing around with 'include' but it doesn't seem to do anything, however, I kept it here to help illustrate what I'm trying to achieve.
Code For Process:
$formInputNames = $_POST['names'];
$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used
$email = '#grabby.com';
echo "<br>";
echo "<br>";
$fullnames = explode(", ", $_POST['names']);
if ($active == true) {
$active = '1';
//sets activate checkbox to '1' if it has been selected
}
/*----------------------Function to Insert User---------------------------*/
A Function is here to place names and other fields in database.
/*-------------------------End Function to Insert User--------------------*/
/*-----------------------Function for Errors---------------------*/
function errorCheck($fullname,$nameSplit,$formInputNames){
if ($formInputNames == empty($fullname)){
echo 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[0])) {
echo 'Error: First Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[1])) {
echo 'Error: Last Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
echo 'Error: Found Illegal Character in: '.$fullname.'<br><br>';
redirect('form.php');
}
}
/*-----------------------------End Function for Errors------------------------*/
/*--------------------------Function for Redirect-------------------------*/
function redirect($url){
$string = '<script type="text/javascript">';
$string .= 'window.location = "' .$url. '"';
$string .= '</script>';
echo $string;
}
/*-------------------------End Function for Redirect-----------------------*/
// Connect to database
I connect to the database here
foreach ($fullnames as $fullname) {
$nameSplit = explode(" ", $fullname);
//opens the database
I Open the database here
errorCheck($fullname,$nameSplit,$formInputNames);
$firstName = $nameSplit[0];//sets first part of name to first name
$lastName = $nameSplit[1];//sets second part of name to last name
$emailUser = $nameSplit[0].$email;//sets first part and adds email extension
newUser($firstName,$lastName,$emailUser,$active,$conn);
redirect('viewAll.php');
//echo '<META HTTP-EQUIV="Refresh" Content="0; URL=viewAll.php">';
//if you try this code out, you can see my redirect to viewAll doesn't work when errors are found...I would appreciate help fixing this as well. My immediate fix is using the line under it but I don't like it.
}
Any help is certainly appreciated.Thank You
Also it's worth noting I'm new to php. I would like to have an answer in php as well (if possible).
There's multiple ways of doing so. I personally would use AJAX. On a 'form submit', run a javascript function calling an AJAX request to a .php file to check the form information, all using post method. Calculate all the $_POST['variables'] checking for your defined errors. You would have an html element print the errors via AJAX request.
If there are 0 errors then in the request back return a string as so that your javascript function can look for if its ready to go. If ready to go, redirect the user to where ever you please.
AJAX is not hard and I only suggested the idea sense you put javascript in your tags.
Another method:
Having all your code on one .php file. When you submit the form to the same .php file check for the errors (at the top of the file). If $_POST['variables'] exist, which they do after you submit the form, you echo your errors in the needed places. If zero errors then you redirect the page.

Replace a php variable with textbox input

Ok I am confused with php, javascript and html and dont know what to do. On researching on the internet, i found js is client side and php is server side. when a php file is run on the browser, it converts everything into html and the page is loaded. Now let me tell you guys what i am doing.
I have a php file that give me some stats from a particular url (in the sample i am just showing url)
<?
$url="www.example.com";
echo "URL = " .$url;
?>
Result URL = www.example.com
The above code echoes the url which is www.example.com. I added a textbox to this code which i believe is javascript+html
<script>
function myFunction() {
$url=myurl.value;
}
</script>
<input type="text" name="myurl" id="myurl">
<input onclick="myFunction()" type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<?
$url="www.example.com";
echo "URL = " .$url;
?>
Here the result is same. only difference is that it has a textbox and button above the result.
When I enter another url in the textbox and press submit, it does nothing probably because the page is already loaded. I want to replace the result of www.example.com to the one which is entered in the textbox without changing the .php file. There will always be a default url in the .php file. whenever the file is opened in the browser, the default statistics will be shown... only when the user enters new url and clicks submit, the stats should change.
How can I achieve this? I am behind this since more than a couple of hours now and not sure how to get this done. Please help me.... Thank you.
EDIT
Can I have two .php files? one for the user to enter url and submit and another one to get the entered url and echo it? If yes, how? If I understand this logic, i can get a start for what I am doing.
I think you are trying to do more with your js function, but syntactically it is combining js and php. It should look like this
function myFunction() {
var url = document.getElementById('myurl').value;
}
Although this doesn't really do anything other then assign the content of the text box to a variable.
EDIT
<script>
function myFunction() {
document.getElementById('url').innerHTML = document.getElementById('myurl').value;
}
</script>
<input type="text" name="myurl" id="myurl">
<input onclick="myFunction()" type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<? $url = "www.example.com"; ?>
URL = <span id="url"><?= $url; ?></span>
natzim is correct if you are wanting to write the url back to the php file. If you use javascript to change the action of the form, it will submit to a different page.
//javascript
function myFunction() {
//this should change the page that loads after submit.
//If you want to go to a new page that the user enters, leave this code in...
//If not, remove it
document.getElementsByTagName("form")[0].action = document.getElementById("myUrl").value;
}
That is assuming you have a form tag somewhere (which you will need to submit the page). Also I am not sure this code will run if you use a submit and not a button. If you used a button instead you could append this to the code above to submit the form:
//This would be part of your myFunction if you used a button instead of a submit input
document.getElementsByTagName("form")[0].submit();
as per my comment -
this code is your old php:
<?
$url="www.example.com";
echo "URL = " .$url;
?>
and this is the php I suggested:
<?php
$url=isset($_POST['myurl']) ? $_POST['myurl'] : 'www.example.com';
echo "URL = " .$url;
?>
this would check the myurl input from that was submitted to the server and set the value of $url to its value if it existed then the $url variable would be echoed to the page under the inputs.
This code is assuming you are using the POST method rather than the GET method when your form was submitted.
**EDIT: **
To clarify - here is your page with the modifications I am suggesting. (Please ignore the javascript above as it seems you will not need it):
<form action='www.example.com' method='post'>
<input type="text" name="myurl" id="myurl">
<input type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<?php
$url=isset($_POST['myurl']) ? $_POST['myurl'] : 'www.example.com';
echo "URL = " .$url;
?>
</form>

Upload an image without refreshing page in php

I want to upload an image without refreshing page. please help me for this purpose. I find many thing but ever
Complete Script :
you need ajax to do it and here some code to work for u :
ajaximage.php
Contains PHP code.
This script helps you to upload images into uploads folder.
Image file name rename into timestamp+session_id.extention
<?php
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name)) {
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats)) {
if($size<(1024*1024)) // Image size max 1 MB
{
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name)) {
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
index.php
Contains simple PHP and HTML code.
Here $session_id=1 means user id session value.
<?php
include('db.php');
session_start();
$session_id='1'; // User login session value
?>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload image <input type="file" name="photoimg" id="photoimg" />
</form>
<div id='preview'>
</div>
Sample database design for Users.
Users
Contains user details username, password, email, profile_image and profile_image_small etc.
CREATE TABLE `users` (
`uid` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY,
`profile_image` varchar(200),
`profile_image_small` varchar(200),
)
Javascript Code
$("#photoimg").on('change',function(){})
// photoimg is the ID name of INPUT FILE tag and
$('#imageform').ajaxForm()
//imageform is the ID name of FORM. While changing INPUT it calls FORM submit without refreshing page using ajaxForm() method.
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#photoimg').on('change', function()
{
$("#preview").html('');
$("#preview").html('<img src="loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm(
{
target: '#preview'
}).submit();
});
});
</script>
Uploading files to the server without a page refresh requires some additional client-side tools. These tools will then need to communicate with the PHP backend that you have written. Here are some popular solutions which offer what you are looking for:
Uploadify, my favorite of these solutions: http://www.uploadify.com/
SWFUpload, similar to Uploadify: http://swfupload.org/
jQuery Form Plugin, an AJAX-based uploader: http://jquery.malsup.com/form/#file-upload
Hope that helps.
Two good tutorials:
http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html
http://css-tricks.com/6522-ajax-image-uploading/
You need to use ajax to do that. Ajax will send the request to a PHP script that will do the work without refreshing the entire page.
Submit it via XMLHttpRequest. In a nutshell you would need to initialise a FormData() object and append your file to the object, then initiate an xhr connection, and send your object via xhr xhr.send.
This is all at a very basic level...
Or, better yet, use a pre-existing tool.
Lot of jquery plug ins are available, you can show progress bar too. refer this
http://www.phpletter.com/Demo/AjaxFileUpload-Demo/

Categories