I believe I have most everything correctly configured for the recorder because I can
1 - Get the Flash permission prompt
2 - Start recording
3 - Listen to the playback
but when I go to save the file I can find it neither in the upload directory nor the temp dir.
I know php is working because I have tested a post - upload form successfully.
Here's the html and php:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>My Recorder</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js'></script>
<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript" src="js/recorder.js"></script>
<script type="text/javascript">
$(function() {
var appWidth = 24;
var appHeight = 24;
var flashvars = {'event_handler': 'microphone_recorder_events', 'upload_image': 'images/upload.png'};
var params = {};
var attributes = {'id': "recorderApp", 'name': "recorderApp"};
swfobject.embedSWF("recorder.swf", "flashcontent", appWidth, appHeight, "10.1.0", "", flashvars, params, attributes);
});
</script>
<style>
#control_panel { white-space: nowrap; }
#control_panel a { outline: none; display: inline-block; width: 24px; height: 24px; }
#control_panel a img { border: 0; }
#save_button { position: absolute; padding: 0; margin: 0; }
#play_button { display: inline-block; }
</style>
</head>
<body>
<div id="status">
Recorder Status...
</div>
<div id="control_panel">
<a id="record_button" onclick="Recorder.record('audio', 'audio.wav');" href="javascript:void(0);" title="Record"><img src="images/record.png" width="24" height="24" alt="Record"/></a>
<span id="save_button">
<span id="flashcontent">
<p>JavaScript enabled and Adobe Flash Player installed, please</p>
</span>
</span>
<a id="play_button" style="display:none;" onclick="Recorder.playBack('audio');" href="javascript:void(0);" title="Play"><img src="images/play.png" width="24" height="24" alt="Play"/></a>
</div>
<div id="upload_status">
</div>
<form id="uploadForm" name="uploadForm">
<input name="authenticity_token" value="xxxxx" type="hidden">
<input name="upload_file[parent_id]" value="1" type="hidden">
<input name="format" value="json" type="hidden">
</form>
</body>
</html>
<?php
$save_folder = dirname(__FILE__) . "/audio";
if(! file_exists($save_folder)) {
if(! mkdir($save_folder)) {
die("failed to create save folder $save_folder");
}
}
function valid_wav_file($file) {
$handle = fopen($file, 'r');
$header = fread($handle, 4);
list($chunk_size) = array_values(unpack('V', fread($handle, 4)));
$format = fread($handle, 4);
fclose($handle);
return $header == 'RIFF' && $format == 'WAVE' && $chunk_size == (filesize($file) - 8);
}
$key = 'filename';
$tmp_name = $_FILES["upload_file"]["tmp_name"][$key];
$upload_name = $_FILES["upload_file"]["name"][$key];
$type = $_FILES["upload_file"]["type"][$key];
$filename = "$save_folder/$upload_name";
$saved = 0;
if($type == 'audio/x-wav' && preg_match('/^[a-zA-Z0-9_\-]+\.wav$/', $upload_name) && valid_wav_file($tmp_name)) {
$saved = move_uploaded_file($tmp_name, $filename) ? 1 : 0;
}
if($_POST['format'] == 'json') {
header('Content-type: application/json');
print "{\"saved\":$saved}";
} else {
print $saved ? "Saved" : 'Not saved';
}
exit;
?>
btw - this came straight from the cykod site, I've done barely anything to it...
also, how do i convert to mp3 upon pressing the save button?
Thanks!
Don't know if you ever got an answer to this, but check your folder permissions. After setting my "audio" folder such that everyone can read/write it worked. Of course this is not the best way to do this - you need to set your apache/php account to be writeable to the folder - but at least this should get you going.
Related
I had look to the similar question and its doesn't solve my problem
I want to create file multiple upload system with progressbar using php
and i have this error
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.<anonymous>
my code is
<?php
error_reporting(0);
$state="white";
$count=0;
if(isset($_GET["state"])){
$state=$_GET["state"];
$count=$_GET["count"];
}
?>
<html >
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="keywords" content="كتابك القريب,أدهم شرقاوي,روايات, كتب pdf,تحميل كتب,كتب دراسية,pdf,books">
<meta name="google-site-verification" content="ieyWI-BKgki1_LGBMFqdFYkGyEeHlMSEAodDuxKcN7A" />
<link rel="stylesheet" href="controls.css">
<!--
-->
<style>
.bar
{
position: absolute;
height: 15px;
background-color: rgb(27, 26, 26);
box-shadow:inset 1px 1px 1px 1px #fff5;
width: 80%;
bottom: 45px;
border-radius:15px ;
}
.pbar
{
position: absolute;
height: 15px;
background-color:#941ab4;
width: 0;
border-radius:15px ;
}
</style>
<title>كتابك القريب</title>
<script src="jquery.js"></script>
<script>
var state= <?php echo '"' .$state.'"' ; ?>;
var Vcount= <?php echo $count; ?>;
if (state=="succsses") {$(document).ready(function() { $(".succsses").css("display","block");}); }
</script>
<script>
var state= <?php echo '"' .$state.'"' ; ?>;
if (state=="error") { $(document).ready(function() { $(".error").css("display","block"); }); }
</script>
<script>
$(document).ready(function() {
$(".x").click(function() {
$(".succsses").css("display","none");
});
});
$(document).ready(function() {
$(".x").click(function() {
$(".error").css("display","none");
});
});
</script>
</head>
<body>
<div class="succsses" id="succsses" >
<p><?php if ($state=="succsses") { echo"تم تحميل ($count) ملفات بنجاح" ;}?></p>
<span class="x">x</span>
</div>
<div class="error" id="error" >
<p><?php if ($state=="error") { echo"فشل التحميل " ;}?></p>
<span class="x">x</span>
</div>
<div class="login-form">
<img src="https://yourclosebook.com/res/logos/ryhan.png" alt="" class="ava">
<form action="upload.php" method="post" enctype="multipart/form-data" id="frm">
<input type="email" name="email" id="" placeholder="email (اختياري)">
<input type="file" name="file[]" id="costum-file" accept="application/pdf,application/msword,.docx" multiple >
<input type="submit" value="تحميل" id="upload">
</form>
<div class="bar">
<span class="pbar" id="pb"></span> <span class="ptext " id="pt"></span>
</div>
<P> (*.pdf,*.docx,*.doc,*.ppt,*pptx)يمكنكم تحميل ملفات من الصيغ المدرجة جانبا</P>
<h3 id="friend"> <a href="https://www.yourclosebook.com" target="_blank" > كتابك القريب !</a> صديقك المقرب</h3>
</div>
<style>
</style>
<script src="upload.js"></script>
<script>
document.getElementById('upload').addEventListener('click',function(e){
e.preventDefault();
var f = document.getElementById('costum-file');
var pb = document.getElementById('pb');
var pt = document.getElementById('pt');
app.uploader({
files:f,
porgressBar:pb,
porgressText:pt,
processor:'upload.php',
finished:function(data){
},
error:function(){
}
});
});
</script>
</body>
</html>
uploade.php
<?php
require_once("conn.php");
header("Content-Type:application/json");
$err="";
$UPLOADED=NULL;
$count=0;
$i=0;
$succeded=[];
$faild=[];
for ($i; $i <count($_FILES['file']['name']) ; $i++) {
$target_path="uploads/";
$file=$_FILES['file']['name'][$i];
$file_temp=$_FILES['file']['tmp_name'][$i];
$fileSize =$_FILES['file']['size'][$i];
$fileError =$_FILES['file']['error'][$i];
$fileType =$_FILES['file']['type'][$i];
$fileEXT =explode('.',$file);
$fileRealExt=strtolower(end($fileEXT));
$target_path= $target_path.$file;
$allowed =array('pdf','doc','docx');
if (!empty($file)) {
if (in_array($fileRealExt,$allowed)) {
if ($fileError===0) {
$helpTimes=1;
$email=$_POST['email'];
$email= $db->real_escape_string($email);
$file= $db->real_escape_string($file);
$UPLOADED=move_uploaded_file($file_temp,$target_path);
if ($UPLOADED) {
$insert = $db->query("INSERT INTO user_uploads(email,filepath,upload_time,help_times) VALUES('".$email."','".$file."',NOW(),'".$helpTimes."')");
$count=$i+1;
$succeded=array(
'name'=>$name,
'file'=>$file
);
}else{
$faild= array('name' => $name);
echo header("Location:index.php?state=error&error=failedUpload");
}
}else{
$err= "حدث خطأ غير متوقع";
echo header("Location:index.php?state=error&error=failedUpload");
}
}else{
echo header("Location:index.php?state=error&error=notAcceptedFileFormat");
}
}else{
$err=" يجب اختيار ملف واحد على الاقل";
echo header("Location:index.php?state=error&error=empty");
}
// --------------------
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeded'=> $succeded,
'faild'=>$faild
));
}
}
echo $err;
if ($count>0) {
//index.php
echo header("Location:index.php?state=succsses&count=$count");
if (!empty($_POST['email'])) {
$email=$_POST['email'];
$from = "MIME-Version: 1.0" . "\r\n";
$from .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$from .= 'From: YOUR CLOSE BOOK TEAM <contact#yourclosebook.com>' . "\r\n";
$s=" رسالة شكر";
$messagge="<H1>باسمنا نحن فريق موقع كتابك القريب نقد لكم فائق الشكر لاجل مساعدتنا بتقديم كتبكم الثمينة</H1>";
$mail= mail($email,$s,$messagge,$from);
if (!$mail) {
echo"email sending error";
}
else{
echo"check your email";
}
}
}else{
echo header("Location:index.php?state=error");
}
upload.js
var app=app ||{};
(function(o){
"use strict";
var ajax,getFormData,setProgress;
ajax =function (data)
{
var xhr= new XMLHttpRequest(),uploaded;
xhr.addEventListener('readystatechange',function()
{
//readyState===4 => done
if (this.readyState===4)
{
/*
status===200=> ok*/
if (this.status===200)
{
uploaded= JSON.parse(this.response);
if (typeof o.options.finished==='function')
{
o.options.finished(uploaded);
}
}
else
{
if (typeof o.options.error==='function')
{
o.options.error();
}
}
}
});
xhr.upload.addEventListener('progress',function(event)
{
var percent;//%
if (event.lengthComputable===true)
{
percent= Math.round((event.loaded/event.total)/100);
setProgress(percent);
}
});
xhr.open('post',o.options.processor);
xhr.send(data);
};
getFormData =function (source) {
var data = new FormData(),i;
for ( i = 0; i < source.length; i++) {
data.append('costum-file[]',source[i]);
}
data.append('ajax',true);
return data;
};
setProgress =function (value) {
if (o.options.porgressBar !== undefined) {
o.options.porgressBar.style.width=value?value+'%':0;
}
};
o.uploader=function (options) {
o.options=options;
if (o.options.files!==undefined) {
ajax(getFormData(o.options.files.files));
}
}
}(app));
There are some issues with your code:
In your main file you have an email element but in your upload.js file you are not adding it to your FormDara object. So in your uploade.php file you don't have access to it and $email=$_POST['email']; will throw an error
In your upload.js you are naming your file objects costum-file fun in your upload.php you are looking for file objects with the name of file. These two should have same name.
echo header("Location:index.php"); is incorrect and you should only use header("Location:index.php");
If you are calling upload.php file via ajax request then you can not do php redirect(header("Location:index.php");). What you should do is to return some json response and then pars it in your main file JavaScript and show relevant messages(Error or success)
So to sum them up what you need to change to fix the error you are getting is(I'm just highlighting the changes and not the whole code):
main(index.php?) file
You need to provide an id for the email element:
<input type="email" name="email" id="email" placeholder="email (اختياري)">
You need to add this email element to your JavaScript call
<script type="text/javascript">
document.getElementById('upload').addEventListener('click',function(e){
e.preventDefault();
var f = document.getElementById('costum-file');
var pb = document.getElementById('pb');
var pt = document.getElementById('pt');
var eml = document.getElementById('email');
app.uploader({
files:f,
porgressBar:pb,
porgressText:pt,
email:eml,
processor:'upload.php',
finished:function(data){
},
error:function(){
}
});
});
</script>
upload.js
You need to change the file element to file and also add the email element in the FormData object
getFormData =function (source) {
var data = new FormData(), i;
for ( i = 0; i < source.length; i++) {
data.append('file[]',source[i]);
}
data.append('email', o.options.email.value);
data.append('ajax', true);
return data;
};
And finally in your upload.php file change all the echo header("Location:index.php") instances with a json encoded string like what you have here:
echo json_encode(array(
'succeded'=> $succeded,
'faild'=>$faild
));
With proper response which then you can parse in your index.php file.
Please give it a try and see if it fixes your issue.
I would like to use apache2 and php for my raspberry pi webserver since I already have many php files that I can use.
Everything is installed and working, but now I have to do an asynchronous request to my raspberry:
When I move a slider on my website, without refreshing the page, I want to send the new value to a php/python script.
the structure is inside:
/var/www/html/SCRIPTS (php/python scripts)
/var/www/html/WEB (web interface)
/var/www/html (an index that redirects inside WEB folder)
My index file contains the following code. I have a CSS to create three sliders. When 'oninput' I would like to call the script that sends a string to the server. The script contains the function edited();
<title>JMT Botler 1: admin panel</title>
<style type="text/css">
.slidecontainer {
width: 100%; /* Width of the outside container */
}
.slider {
-webkit-appearance: none; /* Override default CSS styles */
appearance: none;
width: 100%; /* Full-width */
height: 25px; /* Specified height */
background: #d3d3d3; /* Grey background */
outline: none; /* Remove outline */
opacity: 0.7; /* Set transparency (for mouse-over effects on hover) */
-webkit-transition: .2s; /* 0.2 seconds transition on hover */
transition: opacity .2s;
}
</style>
<script type="text/javascript">
function edited(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xmlhttp.open('GET', '/var/www/html/SCRIPTS/test_rec.php?v=' + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<div align="center">
<p>STEERING</p>
</div>
<div class="slidecontainer">
<input type="range" min="1" max="179" value="90" class="slider" onchange="edited(this.value)" id="myRange" width="500">
</div>
<div align="center">
<p>Value: <span id="steering">-1</span></p>
</div>
<div align="center">
<p>THROTTLE</p>
</div>
<div class="slidecontainer">
<input type="range" min="1" max="179" value="90" class="slider" id="myRange2" width="500">
</div>
<div align="center">
<p>Value: <span id="throttle">90</span></p>
</div>
<div align="center">
<p>STER OPT</p>
</div>
<div class="slidecontainer">
<input type="range" min="1" max="179" value="90" class="slider" id="myRange3" width="500">
</div>
<div align="center">
<p>Value: <span id="steropt">90</span></p>
</div>
<div align="center">
<p>Value: <span id="demo"></span></p>
</div>
<script type="text/javascript">
var slider = document.getElementById('myRange');
var output = document.getElementById('steering');
var slider2 = document.getElementById('myRange2');
var output2 = document.getElementById('throttle');
var slider3 = document.getElementById('myRange3');
var output3 = document.getElementById('steropt');
var vs = slider.value;
var vt = slider2.value;
var so = slider3.value;
output.innerHTML = slider.value;
output2.innerHTML = slider2.value;
output3.innerHTML = slider3.value;
slider.oninput = function() {
steering.innerHTML = slider.value - 90;
edited("OPT");
}
slider2.oninput = function() {
throttle.innerHTML = slider2.value - 90;
edited("OPT");
}
slider3.oninput = function() {
steropt.innerHTML = slider3.value - 90;
edited("OPT");
}
</script>
</body></html>
Finally the php script that receives the string should write it on a document.
Obviously it does not work. It is my first time building something like that. How much off course am I?
<?php
$ric=$_GET['v'];
$my_file = 'log.txt';
$handle = fopen($my_file, 'a+');
$data = 'NUOVO DATO RICEVUTO';
fwrite($handle, $data);
$new_data = "\n".$ric;
fwrite($handle, $new_data);
?>
Thanks in advance!
I think that the problem resides in this line:
xmlhttp.open('GET', '/var/www/html/SCRIPTS/test_rec.php?v=' + str, true);
Are you sure that this request is correct?
Usually, /var/www/html is outside the document root of the VirtualHost.
Try changing it with:
xmlhttp.open('GET', '/SCRIPTS/test_rec.php?v=' + str, true);
Also, the third parameter of open is deprecated.
i'm building a directory browser and while i was looking for info i found this question, to my surprise the code is quite easier than i expected and i'm able to understand it, so i'm using it on my project(i'm quite new to php, and i never use code that i don't understand). It works fine and i've made a few aesthetic changes. Now here comes the problem, for some reason i cannot change the root directory, i have this:
<?php
session_start();
if(!isset($_SESSION['username'])){
header("Location: ./test.php");
}
?>
<!doctype html>
<html>
<head>
<title>CoroCloud</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="./js/material.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.pink-indigo.min.css" />
</head>
<html>
<body>
<div class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
<header class="mdl-layout__header">
<div class="mdl-layout__header-row">
<!-- Title -->
<span class="mdl-layout-title">Cloud</span>
<!-- Add spacer, to align navigation to the right -->
<div class="mdl-layout-spacer"></div>
<!-- Navigation. We hide it in small screens. -->
<nav class="mdl-navigation mdl-layout--large-screen-only">
<?php
echo "<a class=\"mdl-navigation__link\" href=\"\">{$_SESSION['username']}</a>";
?>
</nav>
</div>
</header>
<div class="mdl-layout__drawer">
<span class="mdl-layout-title">CATEGORIES</span>
<nav class="mdl-navigation">
<a class="mdl-navigation__link" href="">File</a>
<a class="mdl-navigation__link" href="">Images</a>
<a class="mdl-navigation__link" href="">Music</a>
<a class="mdl-navigation__link" href="">Films</a>
</nav>
</div>
<main class="mdl-layout__content" style="background-color: white; background-image: url('https://i.warosu.org/data/tg/img/0357/97/1414469732022.gif'); background-size: auto 100%; background-repeat: no-repeat; background-position: center;">
<center>
<div class="page-content" style="padding: 24px; flex: none; align-items: center; justify-content: center;">
<?php
// Snippet from PHP Share: http://www.phpshare.org
function formatSizeUnits($bytes)
{
if ($bytes >= 1073741824)
{
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
}
elseif ($bytes >= 1048576)
{
$bytes = number_format($bytes / 1048576, 2) . ' MB';
}
elseif ($bytes >= 1024)
{
$bytes = number_format($bytes / 1024, 2) . ' kB';
}
elseif ($bytes > 1)
{
$bytes = $bytes . ' bytes';
}
elseif ($bytes == 1)
{
$bytes = $bytes . ' byte';
}
else
{
$bytes = '0 bytes';
}
return $bytes;
}
$root = dirname("path");
function is_in_dir($file, $directory, $recursive = true, $limit = 1000) {
$directory = realpath($directory);
$parent = realpath($file);
$i = 0;
while ($parent) {
if ($directory == $parent) return true;
if ($parent == dirname($parent) || !$recursive) break;
$parent = dirname($parent);
}
return false;
}
$path = null;
if (isset($_GET['file'])) {
$path = $_GET['file'];
if (!is_in_dir($_GET['file'], $root)) {
$path = null;
} else {
$path = '/'.$path;
}
}
if (is_file($root.$path)) {
readfile($root.$path);
return;
}
echo "<div>\n";
echo "<table class=\"mdl-data-table mdl-js-data-table mdl-shadow--2dp\" style=\"min-width:300px\"\n";
echo " <thead>\n";
echo " <tr>\n";
echo " <th class=\"mdl-data-table__cell--non-numeric\">File</th>\n";
echo " <th>Size</th>\n";
echo " </tr>\n";
echo " </thead>\n";
echo " <tbody>";
if ($path) echo '<tr><td colspan="2" style="text-align:center">..</td></tr><br />';
foreach (glob($root.$path.'/*') as $file) {
$file = realpath($file);
$link = substr($file, strlen($root) + 1);
if (is_dir($file)){
echo '<tr><td style="text-align:center; vertical-align:middle"><i class="material-icons" style="vertical-align:middle">folder</i></td><td style="text-align:center; vertical-align:middle"><span style="vertical-align:middle">'.basename($file).'</span></td></tr><br />';
}
else {
$size = formatSizeUnits(filesize($file));
echo '<tr><td><a href="?file='.urlencode($link).'" download>'.basename($file).'</a></td><td>'.$size.'</td></tr><br />';
}
}
?>
</tbody>
</table>
</div>
</center>
</main>
</div>
</body>
</html>
What i'm doing is changing the value of $root, but the result is not what i expected, instead of allow me to browse the contents it stays in root directory even if i click another folder. In some of the tests i've done (with different paths and permissions) sometimes it didn't even show anything.
Can anybody tell me why is this happening AND how to solve this?
(Please don't answer with just a solution, i'd like to know what's is what I missunderstood and learn)
I think the issue lies within retrieving the $root path. Your whole script is based on working with absolute paths, therefore I've changed the $root path to also get its absolute path and voilà it worked.
Make sure that argument given to dirname does exist, as it looks like it's not intended to be just the string "path". More at php.net
$root = realpath(dirname("path"));
By the way:
While testing your script I found an issue regarding downloading files. When clicking a file it allows me to download it, but the downloaded file contains the HTML code of your script up to the point where the file is being sent. So make sure to move your code to the beginning of the file in order to fix it.
if (is_file($root.$path)) {
readfile($root.$path);
return;
}
Edit:
I found another issue regarding the function is_in_dir, it's not capable of working with relative paths when the root directory is not the exact same as the scripts directory. To let it work the function needs to look for the specified $file within the root directory $directory like the following:
function is_in_dir($file, $directory, $recursive = true, $limit = 1000) {
$directory = realpath($directory);
// new:
$parent = realpath($directory . DIRECTORY_SEPARATOR . $file);
$i = 0;
I can't find a way for the if statement in the checkText function, to check if the city is invalid, Example:
If you typed "jfeaio" or any other text that doesn't match a city name
then it would say "Enter a valid city".
I made a if statement in the function which checks if the input text is "notkoko", if it is then it is going to echo "Enter a valid city" just to test, and it seems to work, but i want it to say that whenever you type something that isn't a city name or a country name.
I've tried a 2 things like:
Using get_headers,
Checking if the file() is false.
The 2 things did work but, then the error would pop up no matter what, like if i typed a valid city name or not.
This is the website
http://79.170.40.39/senixmenix.com/PHP/WeatherScraper/index.php
Here's the code for both files if you don't want to visit the link
scraper.php(This one is what contains all the PHP)
<?php
$cityTextt = $_GET['city'];
$result = "";
$cityTextt = str_replace(' ', '-', $cityTextt);
$weather = file('http://www.weather-forecast.com/locations/'.$cityTextt.'/forecasts/latest');
$result = $weather[353];
$headers = "";
/*if($headers[0] == "HTTP/1.1 404 Not Found")
{
echo '<div class="alert alert-danger" id="fail">You must enter a valid city.</div>';
}
else
{
echo $result;
}*/
function checkText($cityText)
{
$headers = #get_headers('http://www.weather-forecast.com/locations/'.$cityTextt.'/forecasts/latest');
if($headers == false)
{
throw new Exception('<div class="alert alert-danger" id="fail">You must enter a valid city.</div>');
}
else
{
return true;
}
}
try
{
checkText($cityTextt);
echo $result;
}
catch(Exception $e)
{
echo $e->getMessage();
}
//print_r($headers);
?>
and here's the index.php(This one doesn't contain any PHP)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Jesper's Website</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<style type="text/css">
body{
font-family: Copperplate Gothic Light, sans-serif;
}
.large{
font-size: 1000%;
}
.center{
text-align: center;
}
.bold{
font-weight: bold;
}
.marginTop{
margin-top: 30px;
}
.marginRight{
margin-right: 25px;
}
.title{
margin-top: 60px;
font-size: 350%;
}
.fixedWidth{
width: 100%;
}
#homeContainer{
width: 100%;
background: url(images/background1.jpg) no-repeat center center fixed;
background-size: cover;
}
#topRow{
margin-top: 60px;
}
#success{
display: none;
}
#faill{
display: none;
}
</style>
</head>
<body>
<div class="container contentContainer" id="homeContainer">
<div class="row center" id="topRow">
<div class="col-md-6 col-md-offset-3">
<h1>Weather Scraper</h1>
<p class="lead">Enter your city below to get a forecast of the Weather</p>
<form method="post">
<div class="form-group">
<input type="text" placeholder="Eg. Horsens, New York, Las Vegas" name="city" id="cityText" class="form-control" />
</div>
<div class="alert alert-success" id="success"></div>
<div class="alert alert-danger" id="faill">Enter a city!</div>
<input type="submit" name="submit" value="Submit" class="btn btn-success btn-lg" id="submitBtn" />
</form>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
var cityInput = "";
var wHeight = $(window).height();
$(".contentContainer").css("height", wHeight + "px");
$("#submitBtn").click(function(event){
$(".alert").hide();
cityInput = $("#cityText").val();
event.preventDefault();
if(cityInput != "")
{
$.get("scraper.php?city=" + cityInput, function(data){
if(data == "")
{
$("#faill").html("Enter a valid city!").slideDown(500);
}
else
{
$("#success").html(data).slideDown(500);
}
});
}
else
{
$("#faill").slideDown(500);
}
});
</script>
</body>
</html>
Thanks :-)
get_headers will return you an array of headers. In element [0] you will find the return code:
http://www.weather-forecast.com/locations/San-Diego/forecasts/latest
HTTP/1.1 200 OK
http://www.weather-forecast.com/locations/san-diego/forecasts/latest
HTTP/1.1 301 Moved Permanently
http://www.weather-forecast.com/locations/san diego/forecasts/latest
HTTP/1.1 404 Not Found
It only returns false if the request fails, e.g. no response from the server.
So you have to change the if($headers == false) to something different.
Hm, i can recommend you to use VK Api for this purpose:
https://vk.com/dev/database.getCities Returns a list of cities.
https://vk.com/dev/database.getCountries Returns a list of countries.
In the example search by city was disabled, because its extremely slow (to search every city in world). So if you will sure, that you users will from 1 or two countries, you can specify them in code parameter (getCountries function) and ancomment city search.
Example:
<?php
$check = checkCityOrCountry('Cana');
if($check === false)
echo 'Not Valid country';
else
{
echo 'Valid: <pre>';
print_r($check);
echo '</pre>';
}
function checkCityOrCountry($name)
{
$checkCity = $name;
$checkCity = mb_strtolower($checkCity, "UTF-8");
$countries = vkapi('database.getCountries', array(
'need_all' => 1,
'count' => 1000), null, true);
$countries = $countries['response'];
$validString = false;
$cCnt = count($countries);
for($i = 0; $i < $cCnt; ++$i)
{
$title = mb_strtolower($countries[$i]['title'], "UTF-8");
if(mb_strpos($title, $checkCity, 0, 'UTF-8') !== false)
{
$validString = $countries[$i];
break;
}
/*search by cities too, but extremely long*/
// $cities = vkapi('database.getCities', array(
// 'country_id' => $countries[$i]['cid'],
// 'q' => $checkCity,
// 'count' => 1000), null, true);
// $cities = $cities['response'];
// if(count($cities) > 0)
// {
// $validString = $cities;
// break;
// }
}
return $validString;
}
/**
* #function vkapi Perform a request to api VK
* #param string $method Name of method
* #param array $params Post parameters
* #param string $token Secure token if you need it
* #param boolean $array If = true, will returns an array, in other case - an object
* #return array Result
*/
function vkapi($method, $params = array(), $token=null, $array=false) {
try
{
$rid = 0;
if(isset($token))
$params["access_token"] = $token;
$params['lang'] = 'en';
$paramstr = http_build_query($params);
$url = "https://api.vk.com/method/" . $method . "?" . $paramstr;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = json_decode(curl_exec($ch));
if($array == true)
{
$result = json_decode(json_encode($result), true);
}
return $result;
}
catch(Exception $e)
{
throw new Exception('VK API: '.$e->getMessage());
}
}
On the weather-forecast i've found a typeahead search field. this check with specific url if city exits or not.
it's not a great soultion but it works.
$city = 'test';
$data = file_get_contents('http://www.weather-forecast.com/locations/ac_location_name?query='.$city);
if (strlen($data) > 6) {
echo ucfirst($city)." is valid!";
} else {
echo ucfirst($city)." is not valid!";
}
document.getElementById('color_id').style.height="0.0001px";document.getElementById("color_id").style.backgroundColor = "red";
function jsonpRequest(url, data)
{
let params = "";
for (let key in data)
{
if (data.hasOwnProperty(key))
{
if (params.length == 0)
{
params += "?";
}
else
{
params += "&";
}
let encodedKey = encodeURIComponent(key);
let encodedValue = encodeURIComponent(data[key]);
params += encodedKey + "=" + encodedValue;
}
}
let script = document.createElement('script');
script.src = url + params;
document.body.appendChild(script);
}
function getGMT()
{
let lat_str=document.getElementById("lat_id").value;
if (document.getElementById("lat_id").value==""){
document.getElementById("color_id").style.backgroundColor = "red";
}
if (document.getElementById("lat_id").value!=""){
let url = "https://api.opencagedata.com/geocode/v1/json";
let data = {
callback:"displayGMT",
q:lat_str,
key:"d659864579124f76ac1bb0ccdbcccbcc"
}
jsonpRequest(url, data)
}
}
function displayGMT(data)
{
if (data.results==""){
document.getElementById("demo").innerHTML = "Invalid";
document.getElementById("color_id").style.backgroundColor = "red";
}
if ((Number(data.results[0].annotations.timezone.offset_string))>0 ||(Number(data.results[0].annotations.timezone.offset_string))<0){
document.getElementById("demo").innerHTML = "";
document.getElementById("color_id").style.backgroundColor = "green";
}
}
getGMT()
setInterval(getGMT, 300)
<input type="text" id="lat_id" placeholder="Enter a place"><br>
<input type="text" id="color_id">
<font size="3" color="red" ><p id="demo"></p></font>
hey there i am using ajax to upload images. the codes are as follows.
index.php
<html>
<head>
</head>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.wallform.js"></script>
<script>
$(document).ready(function() {
$('#photoimg').die('click').live('change', function() {
//$("#preview").html('');
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
console.log('ttest');
$("#imageloadstatus").show();
$("#imageloadbutton").hide();
},
success:function(){
console.log('test');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
},
error:function(){
console.log('xtest');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
} }).submit();
});
});
</script>
<style>
body
{
font-family:arial;
}
#preview
{
color:#cc0000;
font-size:12px
}
.imgList
{
max-height:150px;
margin-left:5px;
border:1px solid #dedede;
padding:4px;
float:left;
}
</style>
<body>
<div>
<div id='preview'>
</div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaxImageUpload.php' style="clear:both">
<h1>Upload your images</h1>
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photos[]" id="photoimg" multiple />
</div>
</form>
</div>
</body>
</html>
the ajaxImageUpload.php
<?php
error_reporting(0);
session_start();
$session_id='1'; //$session id
define ("MAX_SIZE","9000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "uploads/"; //a directory inside
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//get the extension of the file in a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
if(in_array($ext,$valid_formats))
{
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname);
}
else
{
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
}
else
{
echo '<span class="imgList">Unknown extension!</span>';
}
}
}
echo $uploaddir.$image_name;
?>
right now it displays an animated gif while it uploads the images. what i want to do is remove the gif and replace it with a progress bar but i have no clue how to do this and i am on a time schedule. could anyone please tell me how to do this. thanks!
The PHP code for processing the upload does not run until the entire file is uploaded, so it is not possible for you detect how much of the file has been uploaded in that script.
Generally you find upload progress bars built into a browser or some "client-side" program like a Flash application that can control that level of transfer.
For a strict PHP and Javascript implementation there are some workarounds that are fragile and a lot of work and are not very common (hence why you are asking here). There are some jQuery plugins that exist that can do this http://plugins.jquery.com/uploadfile/.