Page freezes after sending form - php

I have a script that has the following content:
<?php
if(isset($_POST['sent-urls']) || $_POST['sent-urls'] == true)
{
session_start();
error_reporting(E_ALL);
//ini_set('display_errors', 'Off');
include('includes/functions.php');
$url = str_replace('www.', '', url());
$images = explode("\n", $_POST['remote-urls']);
if(sizeof($images) > 30) {
$url_i = $url_t = $direct = 'You have added mroe than 30 links';
}
$links = array();
foreach($images as $image)
{
$srcfile = (isset($image)) ? trim($image) : '';
$extension = remoteEx($srcfile);
$filename = rand(124588, 543354) . '.' . remoteEx($image);
$file = remote_filesize($srcfile);
if ($file <= 3000000 && !empty($srcfile) && $extension == 'png' || $extension == 'peg' || $extension == 'jpg' || $extension == 'gif' || $extension == 'bmp')
{
$copied = copy($srcfile, 'i/' . $filename);
$direct = $url . 'i/' . $filename;
$url_i = $url . 'i/' . $filename . "\n";
if ($copied)
{
// make_thumb($direct, 't/' . $filename, 150, remoteEx($direct));
generate_thumbnail($image, $filename, 110, 110, true, 'file', false, false, '');
$url_t = $url . 't/' . $filename . "\n";
}
}
else if (empty($srcfile))
{
$url_i = $url_t = $direct = 'No links added';
}
else if ($file > 3000000)
{
$url_i = $url_t = $direct = 'Maximum size of photos exceed';
}
else
{
$url_i = $url_t = $direct = 'There was an error while submitting the form';
}
$links[] = array('direct' => $direct, 'thumb' => $url_t);
}
if ($file > 3000000) { echo 'You have exceed the limit of the file size'; }
echo '<br /><br />';
echo '<div id="links">';
echo '<table>';
echo "<tr><td><span class=\"green\">Direct:</span> <textarea class=\"link-area\" readonly=\"readonly\" onMouseOver=\"this.focus(); this.select(); $(this).css('height', '50px');\" onmouseout=\"$(this).animate({ height: '25px' }, 'fast'); $(this).blur();\">";
for($i = 0; $i < count($links); $i++) { echo $links[$i]['direct'] . "\n"; }
echo '</textarea></td></tr>';
echo "<tr><td><span class=\"green\">Thumbnail:</span> <textarea class=\"link-area\" readonly=\"readonly\" onMouseOver=\"this.focus(); this.select(); $(this).css('height', '50px');\" onmouseout=\"$(this).animate({ height: '25px' }, 'fast'); $(this).blur();\">";
for($i = 0; $i < count($links); $i++) { echo $links[$i]['thumb'] . "\n"; }
echo '</textarea></td></tr>';
echo "<tr><td><span class=\"green\">BBCode:</span> <textarea class=\"link-area\" readonly=\"readonly\" onMouseOver=\"this.focus(); this.select(); $(this).css('height', '50px');\" onmouseout=\"$(this).animate({ height: '25px' }, 'fast'); $(this).blur();\">";
for($i = 0; $i < count($links); $i++) { echo '[IMG]' . $links[$i]['direct'] . '[/IMG]' . "\n"; }
echo '</textarea></td></tr>';
echo "<tr><td><span class=\"green\">HTML:</span> <textarea class=\"link-area\" readonly=\"readonly\" onMouseOver=\"this.focus(); this.select(); $(this).css('height', '50px');\" onmouseout=\"$(this).animate({ height: '25px' }, 'fast'); $(this).blur();\">";
for($i = 0; $i < count($links); $i++) { echo '<img src="' . $links[$i]['thumb'] . '" />' . "\n"; }
echo '</textarea></td></tr>';
echo '</table>';
echo '<script type="text/javascript" src="scripts/img.core.js"></script>';
echo '<script type="text/javascript" src="scripts/jquery-1.5.js"></script>';
echo '<input type="reset" id="resetbtn-remote" class="button-sub" value="Reset" />';
echo '<br />';
echo '</div>';
}
else
{
header('Location: index.php');
}
?>
And the script gets called by this form:
<div id="remote" style="display: none;">
<form action="remote.php" method="post" id="remote-upload">
<br /><br />
<textarea name="remote-urls" id="remote-urls" rows="12"></textarea><br/>
<input type="button" name="remote-start" id="remote-start" class="remote-button" value="Upload Images" />
<input type="hidden" name="sent-urls" value="1" />
<input type="reset" id="remote-reset" class="remote-button" value="Reset" style="display: none;" />
<br /><br />
<span class="normal">
Maximum <strong>20</strong> images. <strong>10 MB</strong> for one image.
</span>
</form>
<div id="remoted">
<img id="loader1" src="css/images/loader.gif" style="display: none;" />
</div>
</div>
The form is connected with a jQuery plugin that send data from a form without refreshing the page. I hit the #remote start button, loader shows, and after a few seconds the page freezes and becomes inaccessible for ~4 seconds, then the page unfreezes with the desired results.
What might be causing the page to freeze?
EDIT: The JavaScript is like this:
$('#remote-start').live('click', function() {
$('#loader1').show();
$(this).hide();
$('#remote-reset').show();
$('#remote-upload').ajaxSubmit({
target: '#remoted',
success: function(response) {
$('#remoted').html(response).hide().slideDown('fast');
$('#loader1').fadeOut('normal');
}
});
});
$('#remote-reset').live('click', function() {
$('#remote-urls').empty();
$('#remoted').slideUp('medium', function() {
$(window.location).attr('href', 'http://localhost/imagehost');
});
});
$('#resetbtn-remote').live('click', function() {
$('#remote-urls').empty();
$('#remoted').slideUp('medium', function() {
$(window.location).attr('href', 'http://imgit.org');
});
});

Hard to say but I'd guess that your "jQuery plugin that send data from a form without refreshing the page" is calling $.ajax with async:false:
Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
The plugin is using AJAX and the above excerpt from the $.ajax documentation sounds exactly like what you're seeing.

Related

php Activating On Page Load While Inside Of onsubmit

I have a php function to create a file in a directory on submission of a form.
The code is:
<form id="myForm" onSubmit="<?php
error_reporting(E_ALL);
$directory = __DIR__ . "/images/"; $filecount = 0; $files = glob($directory . "*"); if ($files){
$filecount = count($files); }
$filecount = $filecount + 1;
$pagename = 'image_'.$filecount;
$newFileName = './images/'.$pagename;
$newFileContent = 'Page Content';
if (file_put_contents($newFileName, $newFileContent) !== false) {
echo "File created (" . basename($newFileName) . ")";
} else {
echo "Cannot create file (" . basename($newFileName) . ")";
}
?>">
<input placeholder="Username 0/25" name="user" id="user" maxlength="25" required>
<input placeholder="Password 0/45" name="password" id="password" maxlength="45" required>
<input placeholder="Image Name" name="name" id="name">
<input type="file" placeholder="Image" accept="image/*" name="img" required>
<button type="submit">Upload</button>
</form>
The problem is that it auto activates on page load.. is there a way to fix that
The problem is that it auto activates on page load
to prevent auto loading the page when you press on submit, you could use this trick "return false; \"..." but it doesn't create the image file :/ just stop the page from action.
if (file_put_contents($newFileName, $newFileContent) !== false) {
echo "return false; \"File created (" . basename($newFileName) . ")";
} else {
echo "return false; \" Cannot create file (" . basename($newFileName) . ")";
}
I try to imitate you're project, however i used txt files instead of images.
I used AJAX
index.html
<html>
<body>
<form id="myForm">
<button type="submit">create a file</button>
</form>
<script src="script.js"></script>
</body>
</html>
script.js
document.getElementById('myForm').onsubmit = function(e){
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open('GET','creating.php');
xhr.onreadystatechange = function(){
console.log(xhr.readyState)
if(xhr.readyState == XMLHttpRequest.DONE)
if(xhr.response.startsWith('Woow'))
alert('File created successfully!');
else
alert('Something went wrong!');
}
xhr.send();
}
creating.php
<?php
$directory = __DIR__ . "/files/";
$filecount = count(glob($directory . "*")) + 1;
$newFileName = $directory.'txt_'.$filecount.'.txt';
$newFileContent = "some text... in a file number $filecount.";
if(file_put_contents($newFileName, $newFileContent))
echo "Woow!";
else
echo "Oups!";
?>

How do I pass XML data to php upload to server

Please assist, I have the below code.
I am creating a an XML file and then attempting to post this data to my PHP file on the server so that it can save the file to the "uploads/" Directory where my 3rd party program will pick it up and extract the selected data.
My question is: How can I pass the xmlNew Data into a file and then pass that file to the "upload" functionality?
HTML:
//Several fields listed here.....
//Then:
<form method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload File" name="submit">
</form>
JS:
$(function () {
$('#DownloadButton').click(update);
})
var template = [
'<?xml version="1.0"?>',
'<unattend xmlns="urn:schemas-microsoft-com:unattend">',
'<Data>',
' <SubmitBy><?SubmitBy?></SubmitBy>',
' <Level1><?Level1?></Level1>',
' <Level2><?Level2?></Level2>',
' <Level3><?Level3?></Level3>',
' <Level4><?Level4?></Level4>',
' <Title><?Title?></Title>',
' <Subject><?Subject?></Subject>',
' <Author><?Author?></Author>',
' <Keywords1><?Keywords1?></Keywords1>',
' <Keywords2><?Keywords2?></Keywords2>',
' <Destroy_Date><?Destroy_Date?></Destroy_Date>',
'</Data>',
'</unattend>'
].join('\r\n');
function update() {
var variables = {
'SubmitBy': $('#SubmitBy').val(),
'Level1': $('#Level1').val(),
'Level2': $('#Level2').val(),
'Level3': $('#Level3').val(),
'Level4': $('#Level4').val(),
'Title': $('#Title').val(),
'Subject': $('#Subject').val(),
'Author': $('#Author').val(),
'Keywords1': $('#Keywords1').val(),
'Keywords2': $('#Keywords2').val(),
'Destroy_Date': $('#Destroy_Date').val(),
};
var newXml = template.replace(/<\?(\w+)\?>/g,
function(match, name) {
return variables[name];
});
$('#ResultXml').val(newXml);
$('#DownloadLink')
.attr('href', 'data:text/xml;base64,' + btoa(newXml))
.attr('download', 'xml_Export.xml');
$('#generated').show();
}
if (!window.btoa) {
btoa = function (input) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var result = '';
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
do {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
result += chars.charAt(enc1) + chars.charAt(enc2) + chars.charAt(enc3) + chars.charAt(enc4);
} while (i < input.length);
return result;
};
}
PHP:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_FILES['files'])) {
$errors = [];
$path = 'uploads/';
$extensions = ['jpg', 'jpeg', 'png', 'gif', 'xml'];
$all_files = count($_FILES['files']['tmp_name']);
for ($i = 0; $i < $all_files; $i++) {
$file_name = $_FILES['files']['name'][$i];
$file_tmp = $_FILES['files']['tmp_name'][$i];
$file_type = $_FILES['files']['type'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_ext = strtolower(end(explode('.', $_FILES['files']['name'][$i])));
$file = $path . $file_name;
if (!in_array($file_ext, $extensions)) {
$errors[] = 'Extension not allowed: ' . $file_name . ' ' . $file_type;
}
if ($file_size > 2097152) {
$errors[] = 'File size exceeds limit: ' . $file_name . ' ' . $file_type;
}
if (empty($errors)) {
move_uploaded_file($file_tmp, $file);
}
}
if ($errors) print_r($errors);
}
}
Any assistance would be greatly appreciated.
Thank you all!
A quick demo to show how you could send, using ajax, the XML as a string to the PHP server which would write the data to a file.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['xml'] ) ){
$file = __DIR__ . '/ytm.xml';
$bytes = file_put_contents( $file, $_POST['xml'] );
exit( sprintf('%d bytes written to %s',$bytes,realpath($file) ) );
}
?>
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>send XML data to server to be written to file</title>
<script>
var template = [
'<?xml version="1.0"?>',
'<unattend xmlns="urn:schemas-microsoft-com:unattend">',
'<Data>',
' <SubmitBy><?SubmitBy?></SubmitBy>',
' <Level1><?Level1?></Level1>',
' <Level2><?Level2?></Level2>',
' <Level3><?Level3?></Level3>',
' <Level4><?Level4?></Level4>',
' <Title><?Title?></Title>',
' <Subject><?Subject?></Subject>',
' <Author><?Author?></Author>',
' <Keywords1><?Keywords1?></Keywords1>',
' <Keywords2><?Keywords2?></Keywords2>',
' <Destroy_Date><?Destroy_Date?></Destroy_Date>',
'</Data>',
'</unattend>'
].join('\r\n');
const ajax=function( params ){
with( new XMLHttpRequest() ){
onreadystatechange=function(e){
if( this.status==200 && this.readyState==4 ){
alert( this.response )
}
}
open( 'POST', location.href, true );
setRequestHeader('Content-Type','application/x-www-form-urlencoded');
send( params );
}
}
document.addEventListener('DOMContentLoaded', ()=>{
document.querySelector('input[ type="button" ]').addEventListener('click', e=>{
let vars={};
Array.prototype.slice.call( document.querySelectorAll('form > input[ type="text" ]') ).forEach( field =>{
vars[ field.name ]=field.value
});
let xml=template.replace(/<\?(\w+)\?>/ig, (match,name)=>{
return vars[name];
});
ajax.call( this, 'xml='+xml );
})
});
</script>
</head>
<body>
<form method='post'>
<input type='text' name='SubmitBy' value='bob' />
<input type='text' name='Level1' value='alpha' />
<input type='text' name='Level2' value='bravo' />
<input type='text' name='Level3' value='charlie' />
<input type='text' name='Level4' value='delta' />
<input type='text' name='Title' value="geronimo's revenge" />
<input type='text' name='Subject' value="why is trump such a twit" />
<input type='text' name='Author' value='bill shakespeare' />
<input type='text' name='Keywords1' value='love,death,taxes' />
<input type='text' name='Keywords2' value='cat,dog,fox' />
<input type='text' name='Destroy_Date' value="2019-03-01" />
<input type='button' value='Send the XML' />
</form>
</body>
</html>

PHP on updating image changes to default

We are working on our own MVC framework and on edit if we unchange the image, image changes to default. We don't want image to change in edit mode unless image is re selected.
Our code is as follows:
HTML (View)
<form id="form-category" class="form-horizontal" action="<?php $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label class="col-sm-2 control-label">Image</label>
<div class="col-sm-10">
<a href="" id="thumb-image" data-toggle="image" class="img-thumbnail">
<img src="<?php echo HTTP_HOST ?>/image/<?php echo $data['industry_image']; ?>" alt="<?php echo $data['industry_name']; ?>" title="<?php echo $data['industry_name']; ?>" data-placeholder="<?php echo HTTP_HOST ?>/image/<?php echo $data['placeholder']; ?>" width="100" height="100">
<input type="hidden" name="delete_image" value="<?php echo $data['industry_image']; ?>">
</a>
<input type="file" class="hidden" name="industry_image" value="<?php echo $data['industry_image']; ?>" id="input-image" onchange="readURL(this);">
</div>
</div>
</form>
jQuery for displaying image on file select
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#thumb-image').children('img').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
jQuery for Bootstrap Popover
$(document).on('click', 'a[data-toggle=\'image\']', function(e) {
var $element = $(this);
var $popover = $element.data('bs.popover'); // element has bs popover?
e.preventDefault();
// destroy all image popovers
$('a[data-toggle="image"]').popover('destroy');
// remove flickering (do not re-add popover when clicking for removal)
if ($popover) {
return;
}
$element.popover({
html: true,
placement: 'right',
trigger: 'manual',
content: function() {
return '<button type="button" id="button-image" class="btn btn-primary"><i class="fa fa-pencil"></i></button> <button type="button" id="button-clear" class="btn btn-danger"><i class="fa fa-trash-o"></i></button>';
}
});
$element.popover('show');
$('#button-image').on('click', function() {
$('#input-image').trigger('click');
// $element.parent().find('input').attr('value', '');
$element.popover('destroy');
});
$('#button-clear').on('click', function() {
$element.find('img').attr('src', $element.find('img').attr('data-placeholder'));
$element.parent().find('input').attr('value', '');
//alert($('#input-image').attr('value', ''));
$element.popover('destroy');
});
});
Controller
$data = [
'industry_image' => isset($_POST['industry_image'] ? $_POST['industry_image'] : NULL
]
if(empty($_FILES['industry_image']['size'])) {
$data['industry_image'] = 'no-image.png';
} else {
$file = $_FILES['industry_image'];
$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('gif', 'jpg', 'jpeg', 'png');
$allowedFileSize = 2000000;
if(in_array($fileActualExt, $allowed)) {
if($fileError === 0) {
if($fileSize < $allowedFileSize) {
$fileNameNew = strtolower($data['industry_name']) . "." . $fileActualExt;
$fileDestination = DIR_IMAGE . 'industries/' . $fileNameNew;
$filePath = 'industries/' . $fileNameNew;
if(array_key_exists('delete_image', array($data['industry_image']))) {
if(file_exists($filePath)) {
unlink($filePath);
}
}
$moveResult = move_uploaded_file($fileTmpName, $fileDestination);
if($moveResult != true) {
echo "Error: File Upload Failed. Try again.";
unlink($fileTmpName);
exit;
} else {
if(file_exists($fileNameNew)) {
flash("file_alert alert-danger", "File already exists");
} else {
$data['industry_image'] = $filePath;
}
}
} else {
flash("file_alert alert-danger", "File size is $fileSize of $allowedFileSize");
}
} else {
flash("file_alert alert-danger", "Error uploading the file");
}
} else {
$a = "Please upload only ";
foreach($allowed as $ext) {
$a .= '<b>' . $ext . '</b>' . ', ';
}
$a .= " extensions";
flash("file_alert alert-danger", $a);
}
}
if($this->model->getIndustries($industry_id, $data) {
redirect("catalog/industries", $data);
} else {
redirect("catalog/industries_form", $data);
}
Model
public function editIndustry($industry_id, $data) {
# Prepare Query for category
$this->db->query("UPDATE industry SET industry_name = :industry_name, industry_description = :industry_description, sort_order = :sort_order, status = :status WHERE industry_id = '" . $industry_id ."'");
# Bind Values
$this->db->bind(':industry_name', $data['industry_name']);
$this->db->bind(':industry_description', $data['industry_description']);
$this->db->bind(':sort_order', $data['sort_order']);
$this->db->bind(':status', $data['status']);
# Execute
$this->db->execute();
if(isset($data['industry_image'])) {
$this->db->query("UPDATE industry SET industry_image = :image WHERE industry_id = '" . $industry_id . "'");
$this->db->bind(":image", $data['industry_image']);
//$this->db->execute();
}
# Execute
if($this->db->execute()) {
return $industry_id;
} else {
return false;
}
}
Bootstrap popover image
Above code works but as mentioned earlier, image gets updated even if we don't select on POST. If the image is unedited, same image should go to database. If we clear the database with the red delete button, value gets clear from input tag should send no-image.png to the database.
Hope, I could explain my problem and looking for a solution from you'll awesome guys.
Thank you.

Replace all the spaces in a file’s name with an underscore during the upload process

I have a file named upload_file.php which uploads an image file to my web server. The problem I am having is that I want to replace all the spaces in the file’s name with an underscore during the upload process. I know this could be done using str_replace(), but I have no idea where I should use str_replace() within my code. Any help will be greatly appreciated.
Here is the full code contained within my upload_file.php file:
<?php
require_once '../../config.php';
include '../secure.php';
if ($login_status != 1) exit();
if (isset($_GET['done'])) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else {
if ($_POST['type'] == 'wallpaper') {
$directory = "../../files/";
}
else {
$directory = "../../files/images/";
}
$filename = basename($_FILES['file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (file_exists($directory . $_FILES["file"]["name"])) {
echo htmlspecialchars($_FILES["file"]["name"]) . " already exists. ";
}
elseif (((strpos($ext, "php") !== false) || $ext == 'aspx' || $ext == 'py' || $ext == 'htaccess') && !isset($allow_php_uploads)) {
echo 'Uploading PHP files disabled (<a target="_blank" href=""></a>)';
}
else {
move_uploaded_file($_FILES["file"]["tmp_name"], $directory . $_FILES["file"]["name"]);
header("Location: upload-complete.php?type=".htmlspecialchars($_POST['type'])."&newfile=". htmlspecialchars($_FILES["file"]["name"])."&id=".intval($_POST['id'])."");
}
}
} else { ?>
<head>
<style type="text/css">
body {
margin:0px;
padding:0px;
}
</style>
</head>
<form action="upload_file.php?done=1" method="post"
enctype="multipart/form-data">
<input type="file" name="file" id="file" style="max-width:230px;" />
<input name="id" type="hidden" value="<?php echo intval($_GET['id']);?>" />
<input name="type" type="hidden" value="<?php echo htmlspecialchars($_GET['type']);?>" />
<input type="submit" name="submit" value="Upload" />
</form>
<?php } ?>
You could create a variable that holds the name of the file and replace all spaces there. Then in the rest of the code, replace $_FILES["file"]["name"] by that variable.
<?php
require_once '../../config.php';
include '../secure.php';
if ($login_status != 1) exit();
if (isset($_GET['done'])) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else {
if ($_POST['type'] == 'wallpaper') {
$directory = "../../files/";
}
else {
$directory = "../../files/images/";
}
$filename = basename($_FILES['file']['name']);
$file = preg_replace('/\s+/', '_', $_FILES['file']['name']); // <-- Replace spaces
$ext = substr($filename, strrpos($filename, '.') + 1);
if (file_exists($directory . $file)) {
echo htmlspecialchars($file) . " already exists. ";
}
elseif (((strpos($ext, "php") !== false) || $ext == 'aspx' || $ext == 'py' || $ext == 'htaccess') && !isset($allow_php_uploads)) {
echo 'Uploading PHP files disabled (<a target="_blank" href=""></a>)';
}
else {
move_uploaded_file($_FILES["file"]["tmp_name"], $directory . $file);
header("Location: upload-complete.php?type=".htmlspecialchars($_POST['type'])."&newfile=". htmlspecialchars($file)."&id=".intval($_POST['id'])."");
}
}
} else { ?>
<head>
<style type="text/css">
body {
margin:0px;
padding:0px;
}
</style>
</head>
<form action="upload_file.php?done=1" method="post"
enctype="multipart/form-data">
<input type="file" name="file" id="file" style="max-width:230px;" />
<input name="id" type="hidden" value="<?php echo intval($_GET['id']);?>" />
<input name="type" type="hidden" value="<?php echo htmlspecialchars($_GET['type']);?>" />
<input type="submit" name="submit" value="Upload" />
</form>
<?php } ?>
You have to try replace the spaces with underscores by having a whitelist and the replace function. So you can do something like:
$file = preg_replace("/[^-_a-z0-9]+/i", "_", $file);
I can't test it right now but something like that should work fine. Basically, it replaces the characters that they are not in the whitelist of the "[^-_a-z0-9]+/i".

Jquery ajax form submit response getting alert automatically

I am trying to upload an image using ajax form. Image upload is success. But the ajax response getting alerted automatically with a blank popup saying 'The page at www.xxx.com says'.
Here is my jQuery code
$('#profileImg').die('click').live('change', function()
{
$("#profileform").ajaxForm({target: '#preview_profile',
beforeSubmit:function(){
$("#profileloadstatus").show();
$("#profileloadbutton").hide();
},
success:function(s){
$("#profileloadstatus").hide();
$("#profileloadbutton").show();
},
error:function(){
$("#profileloadstatus").hide();
$("#profileloadbutton").show();
$('#profileform').reset();
} }).submit();
if(!s)
{
$("#profileform")[0].reset();
}
});
HTML FORM
<div id="preview_profile"></div><form id="profileform" method="post" enctype="multipart/form-data" action='message_profile_ajax.php'>
<div id="preview_prof"></div>
<div id="profileloadstatus" style="display:none; text-align:center;">
<img src='images/wall_icons/ajaxloader.gif'/> Uploading....
</div>
<div id="profileloadbutton">
<input type="file" id="profileImg" name="profileImg">
</div>
<input type="hidden" id="profvalues" value="" />
</form>
Php code
<?php
include_once 'includes.php';
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
function getImangeName($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,0,$i-1);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['profileImg']['name'];
$size = $_FILES['profileImg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
$imageName = getImangeName($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = $imageName.time().$uid.".".$ext;
$tmp = $_FILES['profileImg']['tmp_name'];
if(move_uploaded_file($tmp, $profile_path.$actual_image_name))
{
$data=$Wall->Profile_Image_Upload($uid,$actual_image_name);
if($data)
{
echo '<img src="'.$profile_path.$actual_image_name.'" class="img-circle" alt="User Image" />';
}
}
else
{
echo '<b>Sorry, </b>Falied to upload your file!';
}
}
else
echo '<b>Sorry, </b>Image file size must be less than 1 MB!';
}
else
echo '<b>Sorry, </b>Invalid file format!';
}
else
echo '<b>Sorry, </b>Please select image..!';
exit;
}
?>
Please help,
Thank you
Check jquery.wallform.js
//return data;
// Modification www.9lessons.info
var exp = /<img[^>]+>/i;
expResult = data.match(exp);
if(expResult == null) {
alert(data);
} else {
$(options.target).prepend(data);
}
$("#photoimg").val('');
// Modification End www.9lessons.info

Categories